Files
repoctl/tests/test_skills.py
Alexander BaranovandClaude Opus 5 c10df0e3af feat(cli): add repoctl kdb, the one command whose human output is content
Обзор базы знаний жил как `python -m stewardship.kdb_table` - работало, но не
как остальной инструмент. Теперь это обычная подкоманда:

    repoctl kdb --repo .

Вписана в контракт, а не рядом с ним: `--output json|yaml` возвращает штатный
конверт с `stewardship/knowledge-overview@0.1` внутри, находки уходят в stderr,
коды возврата прежние (0, и 3 при отсутствии базы знаний).

Одно осознанное отличие от прочих команд: `--output human` печатает саму
таблицу, а не строку статуса. Для `emit` это не исключение - параметр
`human_renderer` был предусмотрен и до сих пор не использовался. Вопрос «что в
базе знаний» отвечается содержимым; строка «kdb: success» на него не отвечает.
Таблица идёт в stdout, поэтому `repoctl kdb > kdb.md` даёт чистый markdown.

Точка входа берётся из `spec.knowledge.entrypoint` контракта с откатом на
`kdb/kdb.yaml` - репозиторий, держащий базу в другом месте, не будет объявлен
не имеющим её.

Скилл kdb-table переписан на команду вместо вызова модуля. docs/repoctl.md
получил раздел. Спецификацию править не пришлось: закрытого перечня команд она
не содержит.

Тесты: три на CLI (таблица в stdout и находки в stderr, конверт в json, отказ с
кодом 3), плюс прежние два на разбор entrypoint. 159 passed, mypy strict чист.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 13:07:36 +03:00

188 lines
7.0 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 "<!-- kb/index.yaml -->" 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")