Files
repoctl/src/stewardship/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

135 lines
5.0 KiB
Python

"""`repoctl skills`: put the stewardship agent skills where an agent looks for them.
The skills were distributed by exactly one path: `init`, which only ever runs on
a *new* repository. Adopting an existing repository needs the adoption skill,
and nothing could install it there -- so the entry point to the whole procedure
depended on the operator already having the skill from somewhere else.
This command is deliberately not plan-then-approve. That discipline exists to
protect a repository's own content, and nothing here touches it: the targets are
a fixed set of tool-owned files under a fixed subdirectory, with content
determined entirely by the installed version of repoctl. What it does keep is
the house rule that a write never destroys something it did not author -- a
skill whose content differs is reported, not overwritten.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from . import io
from .paths import PathViolation, confined_path
from .skills_content import (
KDB_TABLE_SKILL,
REPO_HANDOFF_SKILL,
REPOSITORY_ADOPTION_SKILL,
REPOSITORY_BOOTSTRAP_SKILL,
)
SKILLS_SUBPATH = ".claude/skills"
SKILLS: dict[str, str] = {
"kdb-table": KDB_TABLE_SKILL,
"repo-handoff": REPO_HANDOFF_SKILL,
"repository-adoption": REPOSITORY_ADOPTION_SKILL,
"repository-bootstrap": REPOSITORY_BOOTSTRAP_SKILL,
}
class SkillsError(ValueError):
"""`repoctl skills` refused to proceed, carrying a stable finding code."""
def __init__(self, code: str, message: str) -> None:
super().__init__(f"{code}: {message}")
self.code = code
def target_base(repo: Path | None, *, global_scope: bool) -> Path:
"""The directory the skills tree hangs under: a repository, or the user's home.
A repository-local install travels with the repository and is what a
teammate cloning it gets; a global install follows the operator across every
repository, including ones not adopted yet. Both are legitimate, and which
one is wanted cannot be guessed, so one of them must be stated.
"""
if global_scope and repo is not None:
raise SkillsError("SKILLS_SCOPE_AMBIGUOUS", "Use either --repo or --global, not both")
if global_scope:
return Path.home()
if repo is None:
raise SkillsError(
"SKILLS_SCOPE_MISSING",
"Say where the skills go: --repo PATH for one repository, or --global for every one",
)
base = repo.expanduser()
if not base.is_dir():
raise SkillsError("SKILLS_TARGET_MISSING", f"No such directory: {base}")
return base.resolve()
def skills_dir(base: Path) -> Path:
"""Where the skills live under ``base``."""
return base / SKILLS_SUBPATH
def _skill_path(base: Path, name: str) -> Path:
# Confined against the base rather than the skills directory: the latter
# routinely does not exist yet, and confinement needs a real root to
# resolve against.
try:
return confined_path(base, f"{SKILLS_SUBPATH}/{name}/SKILL.md")
except PathViolation as exc: # pragma: no cover - names are module constants
raise SkillsError("SKILLS_PATH_OUTSIDE_TARGET", f"{name}: {exc}") from exc
def status(base: Path) -> list[dict[str, str]]:
"""Report each skill as ``missing``, ``current`` or ``modified``.
``modified`` deliberately does not distinguish "the operator edited it" from
"repoctl moved on": both mean the file on disk is not the one this version
ships, and neither is safe to overwrite without being asked.
"""
report: list[dict[str, str]] = []
for name, content in SKILLS.items():
path = _skill_path(base, name)
if not path.exists():
state = "missing"
else:
on_disk = path.read_text(encoding="utf-8", errors="replace")
state = "current" if on_disk.strip() == content.strip() else "modified"
report.append({"skill": name, "state": state, "path": path.as_posix()})
return report
def install(base: Path, *, force: bool = False) -> dict[str, Any]:
"""Write every missing skill; refuse to replace one whose content differs.
Nothing is written until every target has been checked, so a refusal leaves
the directory exactly as it was rather than half-updated.
"""
current = status(base)
modified = [item["skill"] for item in current if item["state"] == "modified"]
if modified and not force:
raise SkillsError(
"SKILLS_MODIFIED",
"Already present with different content: "
+ ", ".join(sorted(modified))
+ ". Re-run with --force to replace them.",
)
written: list[str] = []
for item in current:
if item["state"] == "current":
continue
name = item["skill"]
io.write_text_atomic(_skill_path(base, name), SKILLS[name])
written.append(name)
return {
"target": skills_dir(base).as_posix(),
"installed": sorted(written),
"unchanged": sorted(i["skill"] for i in current if i["state"] == "current"),
"skills": status(base),
}