"""What `init` must refuse before it writes a repository. `init` is the one path where the tool controls every byte of the result, so a repository it creates must pass `repoctl validate` by construction. Each case here produced a `success` envelope before the fix: an invalid contract, an unconfirmed owner, a plan that could never be applied, or a write outside the repository from a hand-edited plan. """ from __future__ import annotations import json from pathlib import Path import pytest from stewardship import bootstrap, io from stewardship.validate import validate_repository VALID = { "name": "services-mail", "title": "Corporate mail service", "owners": ["it-infrastructure"], "repositoryType": "service-config", "lifecycle": "production", } def _answers(**overrides): data = dict(VALID) data.update(overrides) return data # --- answers that would produce an invalid repository ------------------------ @pytest.mark.parametrize( ("overrides", "code"), [ ({"name": "Services/Mail"}, "INIT_NAME_INVALID"), ({"name": "Services Mail"}, "INIT_NAME_INVALID"), ({"name": "MAIL"}, "INIT_NAME_INVALID"), ({"name": "-leading-dash"}, "INIT_NAME_INVALID"), ({"repositoryType": "mail-server"}, "INIT_TYPE_UNKNOWN"), ({"lifecycle": "bogus"}, "INIT_LIFECYCLE_UNKNOWN"), ({"access": "semi-public"}, "INIT_ACCESS_UNKNOWN"), ({"owners": []}, "INIT_OWNER_UNKNOWN"), ({"name": ""}, "INIT_ANSWERS_INCOMPLETE"), ], ) def test_answers_that_break_the_schema_are_refused(overrides, code) -> None: with pytest.raises(bootstrap.BootstrapError) as excinfo: bootstrap.BootstrapAnswers.from_mapping(_answers(**overrides)) assert excinfo.value.code == code def test_a_rejected_name_comes_with_a_usable_suggestion() -> None: """An error that only says "invalid" makes the owner guess the rule.""" with pytest.raises(bootstrap.BootstrapError) as excinfo: bootstrap.BootstrapAnswers.from_mapping(_answers(name="Services/Mail")) assert "'services-mail'" in str(excinfo.value) def test_owner_refusal_names_both_ways_to_answer() -> None: """An error that only says "refused" leaves the reader guessing the flag.""" with pytest.raises(bootstrap.BootstrapError) as excinfo: bootstrap.BootstrapAnswers.from_mapping(_answers(owners=[])) message = str(excinfo.value) assert "--owner" in message and "owners:" in message # --- the created repository must validate ------------------------------------ def test_a_freshly_created_repository_validates(tmp_path: Path) -> None: repo = tmp_path / "mail" repo.mkdir() answers = bootstrap.BootstrapAnswers.from_mapping(_answers()) plan = bootstrap.build_bootstrap_plan(answers, repo) bootstrap.apply_bootstrap_plan(repo, plan, plan["planHash"]) (repo / ".git").mkdir() report = validate_repository(repo) assert not [f for f in report.findings if f.severity == "error"] # Content-root directories are deliberately not created (bootstrap docstring: # no placeholder directories), so those warnings are expected, not failures. assert {f.code for f in report.findings} <= {"CONTENT_ROOT_PATH_MISSING"} # --- collisions belong to plan, not to apply --------------------------------- def test_plan_refuses_a_directory_that_is_already_a_repository(tmp_path: Path) -> None: repo = tmp_path / "existing" (repo / "ops").mkdir(parents=True) (repo / "ops" / "contract.yaml").write_text("existing: true\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" assert "adopt" in str(excinfo.value) def test_planning_without_a_target_still_works(tmp_path: Path) -> None: """`root` is optional; omitting it plans without the collision check.""" answers = bootstrap.BootstrapAnswers.from_mapping(_answers()) assert bootstrap.build_bootstrap_plan(answers)["planHash"].startswith("sha256:") # --- a plan is an editable file, so apply confines every path ---------------- @pytest.mark.parametrize( "escape", ["../ESCAPED.md", "../../ESCAPED.md", "ops/../../ESCAPED.md", "/etc/passwd", "C:/Windows/x"], ) def test_apply_refuses_to_write_outside_the_repository(tmp_path: Path, escape: str) -> None: repo = tmp_path / "inner" repo.mkdir() answers = bootstrap.BootstrapAnswers.from_mapping(_answers()) plan = bootstrap.build_bootstrap_plan(answers, repo) plan["files"] = [{"path": escape, "content": "escaped\n"}] plan.pop("planHash") plan["planHash"] = io.sha256(plan) with pytest.raises(bootstrap.BootstrapError) as excinfo: bootstrap.apply_bootstrap_plan(repo, plan, plan["planHash"]) assert excinfo.value.code == "INIT_PATH_OUTSIDE_REPOSITORY" assert not list(tmp_path.glob("ESCAPED.md")) assert not list(tmp_path.parent.glob("ESCAPED.md")) def test_a_refused_escape_writes_nothing_at_all(tmp_path: Path) -> None: """Confinement runs over every entry before the first byte is written.""" repo = tmp_path / "inner" repo.mkdir() answers = bootstrap.BootstrapAnswers.from_mapping(_answers()) plan = bootstrap.build_bootstrap_plan(answers, repo) plan["files"].append({"path": "../ESCAPED.md", "content": "escaped\n"}) plan.pop("planHash") plan["planHash"] = io.sha256(plan) with pytest.raises(bootstrap.BootstrapError): bootstrap.apply_bootstrap_plan(repo, plan, plan["planHash"]) assert not (repo / "ops" / "contract.yaml").exists() # --- refusals stay machine-readable ------------------------------------------ def test_refusals_are_envelopes_not_stderr_lines(tmp_path: Path, capsys) -> None: from stewardship.cli import main repo = tmp_path / "mail" repo.mkdir() exit_code = main( ["init", "--repo", str(repo), "--name", "Services/Mail", "--type", "service-config", "--owner", "x", "--output", "json"] ) envelope = json.loads(capsys.readouterr().out) 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