diff --git a/.claude/skills/repository-adoption/SKILL.md b/.claude/skills/repository-adoption/SKILL.md index ed43ed0..75a7f18 100644 --- a/.claude/skills/repository-adoption/SKILL.md +++ b/.claude/skills/repository-adoption/SKILL.md @@ -23,6 +23,8 @@ with machine output, and explains findings. It must not duplicate the runbook lo forbidden changes) before asking for approval. 5. Only after explicit approval, run `repoctl adopt --repo --mode apply --plan --approve `. + `--plan` accepts the file exactly as `--output json > plan.json` wrote it: the + result envelope is unwrapped for you, so do not strip it down to `data` by hand. 6. Run `repoctl adopt --repo --mode verify --output json` and report the `AdoptionReport`, including any `unresolvedFindings`. diff --git a/.claude/skills/repository-bootstrap/SKILL.md b/.claude/skills/repository-bootstrap/SKILL.md index f9b8a5a..84c08d7 100644 --- a/.claude/skills/repository-bootstrap/SKILL.md +++ b/.claude/skills/repository-bootstrap/SKILL.md @@ -10,14 +10,18 @@ rendering or validation here - call the CLI and explain its output. ## Procedure -1. Collect the missing decisions from the user: repository type - (`infrastructure-config` | `service-config` | `software` | `project`), `metadata.name`, - `title`, `owners`, `lifecycle`. All of these are refused rather than guessed: - `name` must match `^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`, `owners` must be non-empty, - and `lifecycle` must be one of the schema's values. - If the target directory already holds `ops/contract.yaml` or the other generated - paths, this is an existing repository: use `repository-adoption`, not `init`. -2. Run `repoctl init --repo --answers --output json` to obtain a +1. Run `repoctl init --answers-template > answers.yaml`. It names every key, its + allowed values and its default; the answers keys are not the flag names + (`--type` sets `repositoryType`). Fill it in with the user. + Answer `summary` and `namespace` too: they are cheap now and otherwise stay + as placeholders in the contract. + All values are refused rather than guessed -- `name` must match + `^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`, `owners` must be non-empty -- and before + choosing a name, look at the sibling repositories and follow their convention. + If the target already holds `ops/contract.yaml`, this is an existing + repository: use `repository-adoption`, not `init`. Skill files left by + `repoctl skills install` are not a collision. +2. Run `repoctl init --repo --answers answers.yaml --output json` to obtain a `BootstrapPlan` (this performs no writes). 3. Show the user the planned files and the `planHash`. 4. Only after explicit approval, run diff --git a/docs/repoctl.md b/docs/repoctl.md index 9973f14..bf51da2 100644 --- a/docs/repoctl.md +++ b/docs/repoctl.md @@ -119,10 +119,17 @@ repoctl context --repo . --intent domain.action --output json Двухшаговый процесс: сначала план, затем — только после ревью — применение. ```bash +# Шаг 0: получить шаблон ответов — он называет все ключи и их допустимые значения +repoctl init --answers-template > answers.yaml + # Шаг 1: построить план (ничего не пишет на диск) -repoctl init --repo ../new-repo --name new-repo --type project --owner team-name --output json > plan.json +repoctl init --repo ../new-repo --answers answers.yaml --output json > plan.json ``` +Ключи файла ответов — не имена флагов (`--type` задаёт `repositoryType`), поэтому шаблон и существует. `summary` и `namespace` стоит заполнить сразу: они дёшевы, а иначе навсегда остаются заглушками в контракте. + +Файлы скиллов, оставленные `repoctl skills install`, коллизией **не** считаются: путь, уже содержащий ровно то, что план собирался записать, — не конфликт. Файл с другим содержимым конфликтом остаётся. + Ответы проверяются до сборки плана, чтобы `init` не мог создать репозиторий, который не проходит собственный `validate`: | Код | Когда | diff --git a/src/stewardship/adoption.py b/src/stewardship/adoption.py index c99009f..1f41ba1 100644 --- a/src/stewardship/adoption.py +++ b/src/stewardship/adoption.py @@ -393,6 +393,10 @@ def _proposed_identity(root: Path) -> dict[str, str]: third answer. The remote path is something the owner chose. Two segments are kept because the last one alone ("lxd", "docker") collides across groups. """ + # `--repo .` is the ordinary way to name the current repository, and + # `Path(".").name` is the empty string: without resolving first, every such + # invocation fell through to the generic fallback name. + root = root.resolve() url = gitutil.remote_url(root) if url: path = re.sub(r"\.git$", "", url.split("#", 1)[0].rstrip("/")) diff --git a/src/stewardship/bootstrap.py b/src/stewardship/bootstrap.py index 40e121b..9f119db 100644 --- a/src/stewardship/bootstrap.py +++ b/src/stewardship/bootstrap.py @@ -64,6 +64,44 @@ SSH_RECOMMENDATION = ( ) +def answers_template() -> str: + """A commented answers file naming every key, its vocabulary and its default. + + The answers keys are not the flag names (`--type` sets `repositoryType`), + and nothing printed the mapping: the vocabularies were reachable only by + sending a wrong value on purpose and reading the refusal. `summary` and + `namespace` are listed because they are cheap to answer and otherwise stay + as generated placeholders in the contract forever. + """ + return f"""# Answers for `repoctl init --answers `. +# Command-line flags of the same meaning override these values. + +# Required. +name: my-repository # must match {ID_PATTERN} +repositoryType: project # {" | ".join(sorted(REPOSITORY_TYPES))} +owners: # at least one; a person or a team + - team-or-person + +# Optional, but answer them now: each one otherwise stays a placeholder. +title: My repository # defaults to `name` +summary: What this repository is for and what it is not +lifecycle: active # {" | ".join(sorted(LIFECYCLES))} +namespace: Services # the group this repository belongs to +access: internal # {" | ".join(sorted(ACCESS_VALUES))} +gitInit: false # run `git init` when applying + +# Optional: declare the content roots yourself instead of taking the +# defaults for `repositoryType`. Each needs id, role, path, kind, authority. +# contentRoots: +# - id: policies +# role: policies +# path: policies +# kind: directory +# authority: source +# writePolicy: managed +""" + + class BootstrapError(ValueError): """`init` refused to proceed, carrying a stable finding code. @@ -268,6 +306,22 @@ def _render_gitignore() -> str: return "ops/runs/\n.venv/\n__pycache__/\n" +def _already_holds(root: Path, file_entry: dict[str, Any]) -> bool: + """True when the repository already holds exactly what this entry would write. + + The collision check protects content the tool did not author, and identical + bytes are nothing to protect. Without this, `repoctl skills install` -- the + documented way to make the bootstrap skill reachable at all -- writes the + three skill files and thereby makes `init` refuse the very repository it was + installed to bootstrap. + """ + try: + current = (root / file_entry["path"]).read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + return False + return bool(current.strip() == str(file_entry["content"]).strip()) + + def build_bootstrap_plan(answers: BootstrapAnswers, root: Path | None = None) -> dict[str, Any]: """Build the plan, refusing up front what `apply` would refuse anyway. @@ -289,7 +343,11 @@ def build_bootstrap_plan(answers: BootstrapAnswers, root: Path | None = None) -> {"path": ".claude/skills/repo-handoff/SKILL.md", "content": REPO_HANDOFF_SKILL}, ] if root is not None: - occupied = [entry["path"] for entry in files if (root / entry["path"]).exists()] + occupied = [ + entry["path"] + for entry in files + if (root / entry["path"]).exists() and not _already_holds(root, entry) + ] if occupied: raise BootstrapError( "INIT_PATH_COLLISION", @@ -324,6 +382,7 @@ def apply_bootstrap_plan(root: Path, plan: dict[str, Any], approve_hash: str) -> # happily walks out of the repository for a relative one, so every target is # confined before anything is written -- the same boundary `adopt` applies. targets: list[tuple[str, Path, str]] = [] + already_present: list[str] = [] for file_entry in plan["files"]: rel_path = file_entry["path"] try: @@ -331,9 +390,14 @@ def apply_bootstrap_plan(root: Path, plan: dict[str, Any], approve_hash: str) -> except PathViolation as exc: raise BootstrapError("INIT_PATH_OUTSIDE_REPOSITORY", f"{rel_path}: {exc}") from exc if target.exists(): + if _already_holds(root, file_entry): + already_present.append(rel_path) + continue raise FileExistsError(f"Refusing to overwrite existing file: {rel_path}") targets.append((rel_path, target, file_entry["content"])) + # `already_present` is intentionally not written and not reported as + # written: `init` claims only the files it actually authored. written: list[str] = [] for rel_path, target, content in targets: io.write_text_atomic(target, content) diff --git a/src/stewardship/cli.py b/src/stewardship/cli.py index 035e402..a93ebc9 100644 --- a/src/stewardship/cli.py +++ b/src/stewardship/cli.py @@ -13,7 +13,7 @@ from pathlib import Path from typing import Any from . import adoption, bootstrap, config, discovery, io, skills -from .constants import CONTRACT_PATH, REPOSITORY_TYPES, RESULT_SCHEMA +from .constants import CONTRACT_PATH, LIFECYCLES, REPOSITORY_TYPES, RESULT_SCHEMA from .context import build_context from .paths import find_repository_root from .render import build_envelope, emit @@ -177,6 +177,14 @@ def cmd_context(args: argparse.Namespace) -> int: def cmd_init(args: argparse.Namespace) -> int: + if args.answers_template: + # A template is a document to save and edit, not a result to parse, so + # it is printed as the YAML file it is meant to become: + # repoctl init --answers-template > answers.yaml + print(bootstrap.answers_template(), end="") + return EXIT_SUCCESS + if not args.repo: + raise CliError("--repo is required (or use --answers-template)", EXIT_INVALID_INPUT) repo_path = Path(args.repo).expanduser() if args.apply: if not args.plan or not args.approve: @@ -389,13 +397,19 @@ def build_parser() -> argparse.ArgumentParser: p_init = sub.add_parser("init") add_common(p_init) - p_init.add_argument("--repo", required=True) + p_init.add_argument("--repo") + p_init.add_argument( + "--answers-template", + dest="answers_template", + action="store_true", + help="Print a commented answers file naming every key and its allowed values, then exit", + ) p_init.add_argument("--answers") p_init.add_argument("--name") p_init.add_argument("--type", dest="type", choices=["infrastructure-config", "service-config", "software", "project"]) p_init.add_argument("--title") p_init.add_argument("--owner", action="append") - p_init.add_argument("--lifecycle") + p_init.add_argument("--lifecycle", choices=sorted(LIFECYCLES)) p_init.add_argument("--git-init", action="store_true") p_init.add_argument("--no-git-init", dest="git_init", action="store_false") p_init.set_defaults(git_init=None) diff --git a/src/stewardship/skills_content.py b/src/stewardship/skills_content.py index 346914d..33bec5e 100644 --- a/src/stewardship/skills_content.py +++ b/src/stewardship/skills_content.py @@ -18,14 +18,18 @@ rendering or validation here - call the CLI and explain its output. ## Procedure -1. Collect the missing decisions from the user: repository type - (`infrastructure-config` | `service-config` | `software` | `project`), `metadata.name`, - `title`, `owners`, `lifecycle`. All of these are refused rather than guessed: - `name` must match `^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`, `owners` must be non-empty, - and `lifecycle` must be one of the schema's values. - If the target directory already holds `ops/contract.yaml` or the other generated - paths, this is an existing repository: use `repository-adoption`, not `init`. -2. Run `repoctl init --repo --answers --output json` to obtain a +1. Run `repoctl init --answers-template > answers.yaml`. It names every key, its + allowed values and its default; the answers keys are not the flag names + (`--type` sets `repositoryType`). Fill it in with the user. + Answer `summary` and `namespace` too: they are cheap now and otherwise stay + as placeholders in the contract. + All values are refused rather than guessed -- `name` must match + `^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`, `owners` must be non-empty -- and before + choosing a name, look at the sibling repositories and follow their convention. + If the target already holds `ops/contract.yaml`, this is an existing + repository: use `repository-adoption`, not `init`. Skill files left by + `repoctl skills install` are not a collision. +2. Run `repoctl init --repo --answers answers.yaml --output json` to obtain a `BootstrapPlan` (this performs no writes). 3. Show the user the planned files and the `planHash`. 4. Only after explicit approval, run @@ -60,6 +64,8 @@ with machine output, and explains findings. It must not duplicate the runbook lo forbidden changes) before asking for approval. 5. Only after explicit approval, run `repoctl adopt --repo --mode apply --plan --approve `. + `--plan` accepts the file exactly as `--output json > plan.json` wrote it: the + result envelope is unwrapped for you, so do not strip it down to `data` by hand. 6. Run `repoctl adopt --repo --mode verify --output json` and report the `AdoptionReport`, including any `unresolvedFindings`. diff --git a/tests/test_bootstrap_gates.py b/tests/test_bootstrap_gates.py index a9b0784..1600362 100644 --- a/tests/test_bootstrap_gates.py +++ b/tests/test_bootstrap_gates.py @@ -157,3 +157,61 @@ def test_refusals_are_envelopes_not_stderr_lines(tmp_path: Path, capsys) -> None assert exit_code != 0 assert envelope["outcome"] == "failure" assert envelope["findings"][0]["code"] == "INIT_NAME_INVALID" + + +# --- what `repoctl skills install` leaves behind is not a collision ---------- + +def test_skills_already_installed_do_not_block_init(tmp_path: Path) -> None: + """The entry point must not disable the command it exists to reach. + + `repoctl skills install` is the documented way to make the bootstrap skill + reachable at all, and it writes exactly the files `init` plans to write. + Treating those as collisions sent every skill-driven bootstrap to `adopt`. + """ + from stewardship import skills + + repo = tmp_path / "vault" + repo.mkdir() + skills.install(repo) + + answers = bootstrap.BootstrapAnswers.from_mapping(_answers()) + plan = bootstrap.build_bootstrap_plan(answers, repo) + written = bootstrap.apply_bootstrap_plan(repo, plan, plan["planHash"]) + + assert not [path for path in written if path.startswith(".claude/skills/")] + assert "ops/contract.yaml" in written + assert (repo / ".claude" / "skills" / "repository-adoption" / "SKILL.md").is_file() + + +def test_a_differing_file_is_still_a_collision(tmp_path: Path) -> None: + """Only byte-identical content is waived; edited content still protects.""" + repo = tmp_path / "vault" + (repo / ".claude" / "skills" / "repo-handoff").mkdir(parents=True) + (repo / ".claude" / "skills" / "repo-handoff" / "SKILL.md").write_text( + "# locally rewritten\n", encoding="utf-8" + ) + + answers = bootstrap.BootstrapAnswers.from_mapping(_answers()) + with pytest.raises(bootstrap.BootstrapError) as excinfo: + bootstrap.build_bootstrap_plan(answers, repo) + assert excinfo.value.code == "INIT_PATH_COLLISION" + + +# --- the answers template ---------------------------------------------------- + +def test_answers_template_is_valid_yaml_and_accepted_as_answers() -> None: + """A template nobody can feed back to the tool is documentation, not a template.""" + from stewardship.markdown import load_yaml_text + + data = load_yaml_text(bootstrap.answers_template()) + answers = bootstrap.BootstrapAnswers.from_mapping(data) + assert answers.name and answers.owners and answers.repository_type + + +def test_answers_template_names_every_vocabulary() -> None: + """The values were previously discoverable only by sending a wrong one.""" + text = bootstrap.answers_template() + for value in ("service-config", "production", "restricted"): + assert value in text + # The key that differs from its flag name, which cost a round trip to learn. + assert "repositoryType" in text