From c80d39cc73e5de7429cdc772db7ba680ad53d312 Mon Sep 17 00:00:00 2001 From: Alexander Baranov Date: Wed, 26 Aug 2026 14:35:38 +0300 Subject: [PATCH] feat(skills): install the agent skills into any repository The stewardship skills were written by exactly one code path: `init`, which only runs on a new repository. Adopting an existing one starts from the repository-adoption skill, and nothing could put that skill there -- so the entry point to the procedure depended on the operator already having it from somewhere else. Services/Monitoring carries three domain skills of its own and no stewardship skill; `adopt` lists `.claude/skills` among its collision paths and installs nothing. repoctl skills install --repo . # travels with the repository repoctl skills install --global # follows the operator everywhere repoctl skills status --repo . Scope is stated, never guessed: the two answers differ in who ends up with the skills, and neither is the obvious default. No plan and no approval hash. That discipline protects a repository's own content; this writes only tool-owned files, in a fixed subdirectory, whose content is fully determined by the installed version. The house rule it does keep is that a write never destroys what it did not author: a skill whose content differs is reported as SKILLS_MODIFIED and left alone until `--force` says otherwise, and the check covers every skill before the first byte is written, so a refusal leaves nothing half-updated. Co-Authored-By: Claude Opus 5 --- AGENTS.md | 9 ++- docs/PLAN.md | 2 + docs/repoctl.md | 16 +++++ src/stewardship/cli.py | 49 ++++++++++++- src/stewardship/skills.py | 132 ++++++++++++++++++++++++++++++++++ tests/test_skills.py | 147 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 352 insertions(+), 3 deletions(-) create mode 100644 src/stewardship/skills.py create mode 100644 tests/test_skills.py diff --git a/AGENTS.md b/AGENTS.md index 79376ca..8165250 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,8 +6,13 @@ This repository defines Repository Stewardship: harness-neutral contracts, knowl It now ships an L1 implementation: the `repoctl` CLI (Python package `repository-stewardship`, module `stewardship`, run via `uv run repoctl`) implements -`config`, `validate`, `discover`, `describe`, `context`, `init` and `adopt`. Executable -`ops/handlers/`, the L2 handler ABI and an MCP server remain planned, not implemented. +`config`, `skills`, `validate`, `discover`, `describe`, `context`, `init` and `adopt`. +Executable `ops/handlers/`, the L2 handler ABI and an MCP server remain planned, not +implemented. + +To work with another repository, put the skills where its agent looks first: +`uv run repoctl skills install --repo ` (or `--global` once, for every +repository). Adoption then starts from the `repository-adoption` skill. ## Start here diff --git a/docs/PLAN.md b/docs/PLAN.md index 354f01d..7b16d5d 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -38,6 +38,8 @@ repoctl describe --repo NAME|PATH [--root PATH ...] repoctl context --repo NAME|PATH --intent INTENT [--include-related] [--materialize] [--budget-bytes N] [--strict] +repoctl skills install --repo PATH | --global [--force] +repoctl skills status --repo PATH | --global repoctl init --repo PATH --name NAME --type TYPE --owner NAME [--answers FILE] [--title T] [--lifecycle L] [--git-init|--no-git-init] diff --git a/docs/repoctl.md b/docs/repoctl.md index 9c2cb75..9973f14 100644 --- a/docs/repoctl.md +++ b/docs/repoctl.md @@ -70,6 +70,22 @@ repoctl validate --repo . --output json При ошибке `outcome` становится `"failure"`, `findings` заполняется, а процесс завершается кодом `1`. +### `skills` — поставить агентские скиллы туда, где агент их ищет + +```bash +repoctl skills install --repo . # в этот репозиторий, .claude/skills/ +repoctl skills install --global # в ~/.claude/skills/, для всех репозиториев +repoctl skills status --repo . # что установлено и не разошлось ли +``` + +Ставит `repository-adoption`, `repository-bootstrap` и `repo-handoff`. Это точка входа: до появления команды скиллы записывал только `init`, то есть они попадали исключительно в **новые** репозитории, а для приёма существующего нужен был скилл, который туда нечем было положить. + +Область обязательно указывается явно — `--repo` или `--global`: локальная установка едет вместе с репозиторием и достаётся тому, кто его склонирует, глобальная следует за оператором в том числе в ещё не принятые репозитории. Угадывать между ними команда не будет (`SKILLS_SCOPE_MISSING`). + +Повторный запуск идемпотентен. Скилл, содержимое которого отличается от поставляемого этой версией, **не перезаписывается**: команда сообщает `SKILLS_MODIFIED` и завершается кодом `1`, заменить его можно явным `--force`. Различить «оператор поправил файл» и «repoctl ушёл вперёд» нельзя, поэтому оба случая требуют подтверждения. Проверка проходит по всем скиллам до первой записи, так что отказ не оставляет каталог наполовину обновлённым. + +В отличие от `init` и `adopt`, здесь нет плана и подтверждения по хэшу: эта дисциплина защищает содержимое репозитория, а команда пишет только файлы, принадлежащие инструменту, в фиксированный подкаталог. + ### `discover` — что есть в каталоге репозиториев ```bash diff --git a/src/stewardship/cli.py b/src/stewardship/cli.py index c8cb8ad..035e402 100644 --- a/src/stewardship/cli.py +++ b/src/stewardship/cli.py @@ -12,7 +12,7 @@ import sys from pathlib import Path from typing import Any -from . import adoption, bootstrap, config, discovery, io +from . import adoption, bootstrap, config, discovery, io, skills from .constants import CONTRACT_PATH, REPOSITORY_TYPES, RESULT_SCHEMA from .context import build_context from .paths import find_repository_root @@ -87,6 +87,35 @@ def cmd_config(args: argparse.Namespace) -> int: raise CliError("Unknown config action") +def cmd_skills(args: argparse.Namespace) -> int: + repo = Path(args.repo).expanduser() if args.repo else None + try: + base = skills.target_base(repo, global_scope=args.global_scope) + if args.skills_action == "status": + report = skills.status(base) + findings = [ + Finding("info", f"SKILL_{item['state'].upper()}", item["skill"], path=item["path"]) + for item in report + ] + _write( + build_envelope( + "skills status", "success", {"target": skills.skills_dir(base).as_posix(), "skills": report}, findings + ), + args.output, + ) + return EXIT_SUCCESS + result = skills.install(base, force=args.force) + except skills.SkillsError as exc: + # Same envelope path as init/adopt: a refusal stays machine-readable. + _write( + build_envelope("skills " + args.skills_action, "failure", None, [Finding("error", exc.code, str(exc).split(": ", 1)[1])]), + args.output, + ) + return EXIT_VALIDATION_FAILURE + _write(build_envelope("skills install", "success", result, []), args.output) + return EXIT_SUCCESS + + def cmd_validate(args: argparse.Namespace) -> int: root = _resolve_repo(args.repo, args.root) result = validate_repository(root) @@ -312,6 +341,24 @@ def build_parser() -> argparse.ArgumentParser: p_remove_root.add_argument("path") p_config.set_defaults(func=cmd_config) + p_skills = sub.add_parser("skills") + add_common(p_skills) + skills_sub = p_skills.add_subparsers(dest="skills_action", required=True) + for action in ("install", "status"): + p_action = skills_sub.add_parser(action) + add_common(p_action) + p_action.add_argument("--repo") + p_action.add_argument("--global", dest="global_scope", action="store_true") + if action == "install": + p_action.add_argument( + "--force", + action="store_true", + help="Replace a skill whose content differs from the one this version ships", + ) + else: + p_action.set_defaults(force=False) + p_skills.set_defaults(func=cmd_skills) + p_validate = sub.add_parser("validate") add_common(p_validate) p_validate.add_argument("--repo") diff --git a/src/stewardship/skills.py b/src/stewardship/skills.py new file mode 100644 index 0000000..c97b5e8 --- /dev/null +++ b/src/stewardship/skills.py @@ -0,0 +1,132 @@ +"""`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 ( + REPO_HANDOFF_SKILL, + REPOSITORY_ADOPTION_SKILL, + REPOSITORY_BOOTSTRAP_SKILL, +) + +SKILLS_SUBPATH = ".claude/skills" + +SKILLS: dict[str, str] = { + "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), + } diff --git a/tests/test_skills.py b/tests/test_skills.py new file mode 100644 index 0000000..f82fcc0 --- /dev/null +++ b/tests/test_skills.py @@ -0,0 +1,147 @@ +"""`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"