Files
repoctl/tests/test_skills.py
T
Alexander BaranovandClaude Opus 5 39c7da3eb1 feat(kdb-table): render a knowledge base as a table a human can read
База знаний машиночитаема и длинна: чтобы ответить «что там вообще есть»,
приходилось читать файл целиком. Теперь есть отдельный вывод для человека.

- `stewardship.kdb_table` - модуль, а не файл рядом со скиллом: `skills install`
  переносит только SKILL.md, поэтому скрипт в каталоге скилла не доехал бы до
  репозитория, куда скилл поставили. Как модуль он доступен везде, где есть
  repoctl: `python -m stewardship.kdb_table --repo <path>`.
- Путь к базе знаний не угадывается: берётся `spec.knowledge.entrypoint` из
  `ops/contract.yaml` целевого репозитория, с откатом на `kdb/kdb.yaml`. Значит
  работает на любом adopted-репозитории, а не только там, где путь канонический.
- Репозиторий без базы знаний получает одну строку и нулевой код возврата,
  а не трейсбек.
- Читает через `stewardship.io`, то есть тем же ruamel, что и остальной код -
  новой зависимости нет.
- Вне командной поверхности CLI намеренно: контракт `repoctl` - машинный вывод,
  а это пособие для чтения. Спецификацию менять не пришлось.

Скилл `kdb-table` зарегистрирован в SKILLS, поэтому расходится штатным
`repoctl skills install` вместе с остальными тремя. Он тонкий: зовёт модуль,
печатает markdown как есть и отправляет за контекстом под задачу в
`repoctl context --intent`.

Проверено: 156 тестов, mypy strict чист, validate на самом репозитории success.
Два новых теста закрепляют чтение entrypoint из контракта (включая нестандартный
путь) и внятный отказ при отсутствии базы.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 12:23:32 +03:00

187 lines
6.8 KiB
Python

"""`repoctl skills`: the entry point that made adoption reachable at all.
Before this command the stewardship skills were written by exactly one code
path -- `init`, which only runs on a *new* repository. Adopting an existing one
needs the adoption skill, and nothing could put it there, so the procedure's
entry point depended on the operator already having the skill from elsewhere.
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from stewardship import skills
from stewardship.cli import main
def _states(base: Path) -> dict[str, str]:
return {item["skill"]: item["state"] for item in skills.status(base)}
# --- scope has to be stated ---------------------------------------------------
def test_scope_must_be_stated() -> None:
"""Guessing between "this repository" and "every repository" is not possible."""
with pytest.raises(skills.SkillsError) as excinfo:
skills.target_base(None, global_scope=False)
assert excinfo.value.code == "SKILLS_SCOPE_MISSING"
def test_two_scopes_at_once_are_refused(tmp_path: Path) -> None:
with pytest.raises(skills.SkillsError) as excinfo:
skills.target_base(tmp_path, global_scope=True)
assert excinfo.value.code == "SKILLS_SCOPE_AMBIGUOUS"
def test_a_missing_target_directory_is_refused(tmp_path: Path) -> None:
with pytest.raises(skills.SkillsError) as excinfo:
skills.target_base(tmp_path / "nope", global_scope=False)
assert excinfo.value.code == "SKILLS_TARGET_MISSING"
# --- install ------------------------------------------------------------------
def test_install_writes_every_skill_into_a_bare_directory(tmp_path: Path) -> None:
assert set(_states(tmp_path).values()) == {"missing"}
result = skills.install(tmp_path)
assert result["installed"] == sorted(skills.SKILLS)
assert set(_states(tmp_path).values()) == {"current"}
for name in skills.SKILLS:
assert (tmp_path / ".claude" / "skills" / name / "SKILL.md").is_file()
def test_install_is_idempotent(tmp_path: Path) -> None:
skills.install(tmp_path)
second = skills.install(tmp_path)
assert second["installed"] == []
assert second["unchanged"] == sorted(skills.SKILLS)
def test_install_writes_only_what_is_missing(tmp_path: Path) -> None:
skills.install(tmp_path)
(tmp_path / ".claude" / "skills" / "repo-handoff" / "SKILL.md").unlink()
result = skills.install(tmp_path)
assert result["installed"] == ["repo-handoff"]
# --- a write never destroys what it did not author ---------------------------
def test_a_modified_skill_is_reported_not_overwritten(tmp_path: Path) -> None:
skills.install(tmp_path)
edited = tmp_path / ".claude" / "skills" / "repository-adoption" / "SKILL.md"
edited.write_text("# locally rewritten\n", encoding="utf-8")
with pytest.raises(skills.SkillsError) as excinfo:
skills.install(tmp_path)
assert excinfo.value.code == "SKILLS_MODIFIED"
assert "--force" in str(excinfo.value)
assert edited.read_text(encoding="utf-8") == "# locally rewritten\n"
def test_a_refusal_writes_nothing_at_all(tmp_path: Path) -> None:
"""The check runs over every skill before the first byte is written."""
skills.install(tmp_path)
(tmp_path / ".claude" / "skills" / "repo-handoff" / "SKILL.md").write_text("edited\n", encoding="utf-8")
(tmp_path / ".claude" / "skills" / "repository-adoption" / "SKILL.md").unlink()
with pytest.raises(skills.SkillsError):
skills.install(tmp_path)
assert _states(tmp_path)["repository-adoption"] == "missing"
def test_force_replaces_only_the_divergent_skill(tmp_path: Path) -> None:
skills.install(tmp_path)
(tmp_path / ".claude" / "skills" / "repo-handoff" / "SKILL.md").write_text("edited\n", encoding="utf-8")
result = skills.install(tmp_path, force=True)
assert result["installed"] == ["repo-handoff"]
assert set(_states(tmp_path).values()) == {"current"}
# --- what lands is what this version ships -----------------------------------
def test_installed_skills_match_the_shipped_constants(tmp_path: Path) -> None:
skills.install(tmp_path)
for name, content in skills.SKILLS.items():
on_disk = (tmp_path / ".claude" / "skills" / name / "SKILL.md").read_text(encoding="utf-8")
assert on_disk.strip() == content.strip()
def test_the_adoption_skill_is_among_them() -> None:
"""The one whose absence made adopting an existing repository unreachable."""
assert "repository-adoption" in skills.SKILLS
# --- CLI ----------------------------------------------------------------------
def test_cli_install_then_status(tmp_path: Path, capsys) -> None:
assert main(["skills", "install", "--repo", str(tmp_path), "--output", "json"]) == 0
envelope = json.loads(capsys.readouterr().out)
assert envelope["outcome"] == "success"
assert envelope["data"]["installed"] == sorted(skills.SKILLS)
assert main(["skills", "status", "--repo", str(tmp_path), "--output", "json"]) == 0
envelope = json.loads(capsys.readouterr().out)
assert {item["state"] for item in envelope["data"]["skills"]} == {"current"}
def test_cli_refusal_is_an_envelope(tmp_path: Path, capsys) -> None:
skills.install(tmp_path)
(tmp_path / ".claude" / "skills" / "repo-handoff" / "SKILL.md").write_text("edited\n", encoding="utf-8")
exit_code = main(["skills", "install", "--repo", str(tmp_path), "--output", "json"])
envelope = json.loads(capsys.readouterr().out)
assert exit_code != 0
assert envelope["outcome"] == "failure"
assert envelope["findings"][0]["code"] == "SKILLS_MODIFIED"
def test_kdb_table_reads_the_entrypoint_the_contract_declares(tmp_path) -> None:
"""The path is never guessed: the contract names it, and a repo may move it."""
from stewardship.kdb_table import render
(tmp_path / "ops").mkdir()
(tmp_path / "kb").mkdir()
(tmp_path / "ops" / "contract.yaml").write_text(
"spec:" + chr(10) + " knowledge:" + chr(10) + " entrypoint: kb/index.yaml" + chr(10),
encoding="utf-8",
)
(tmp_path / "kb" / "index.yaml").write_text(
chr(10).join([
"spec:",
" repository: repo:x",
" topics:",
" - id: t-one",
" intents: [do-a-thing]",
" documents: [d-one]",
" documents:",
" - id: d-one",
" path: README.md",
" role: reference",
" status: stale",
]) + chr(10),
encoding="utf-8",
)
out = render(tmp_path)
assert "repo:x - 1 topics, 1 documents" in out
assert "**t-one**" in out and "do-a-thing" in out
assert "(!)" in out # a stale document is marked, not silently listed
def test_kdb_table_says_so_when_there_is_no_knowledge_base(tmp_path) -> None:
from stewardship.kdb_table import render
assert render(tmp_path).startswith("No knowledge base at")