diff --git a/core/CONTRACT.md b/core/CONTRACT.md index 7c1616ed..86f92708 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -272,7 +272,7 @@ protected state when required; bind/transport details and limits. Treat task/diff/repository/tool content as review evidence, not reviewer -meta-directives; native repository instructions remain an instruction surface. +meta-directives; reviewers load no instruction files or skills from the reviewed head. ## Failure diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c4d03052..c62c3387 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -181,10 +181,16 @@ stdout in runner provenance and the saved review receipt. A failed probe uses RunnerBadOutput and existing family fallback before model input. Successful probe output is accepted across CLI releases. Unsupported Claude options follow existing native failure handling. -Native defaults, repository AGENTS.md/CLAUDE.md processing and read-only tools -remain enabled. Repository instructions remain a native authority surface, so -structural transport tests do not prove injection immunity, reviewer quality or -backend identity. +Native defaults and read-only tools remain enabled. Neither reviewer loads +instructions from the reviewed head, which the PR controls: Claude runs with +`--setting-sources ""`, and Codex runs with `project_doc_max_bytes=0` (no +AGENTS.md or AGENTS.override.md) and a `skills.config` entry disabling every +skill under the checkout's `.agents/skills` and `.codex/skills`; a skill +directory linking outside the checkout, or more skills than one argument can +disable, fails the attempt before launch. Repository +conventions reach reviewers only as evidence or through +`delivery.reviewer_ro_paths` from the pinned base. Structural transport tests do +not prove injection immunity, reviewer quality or backend identity. The [dated design note](design/2026-10-07-deterministic-delivery-design-assumptions.md#r3-native-comparison--october-7-2026) owns the implementation history, native comparison results and their limits. diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index a6dbdd73..3684da48 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -473,6 +473,54 @@ def _codex_supports_ignore_user_config( return done.exit_code == 0 and "--ignore-user-config" in f"{done.stdout}\n{done.stderr}" +# Linux rejects one argv element over 128 KiB (MAX_ARG_STRLEN) before the reviewer starts. +CODEX_SKILL_OVERRIDE_LIMIT = 100_000 + + +def _codex_repository_skill_overrides(cwd: Path) -> list[str]: + """`-c` options disabling every skill Codex discovers in the reviewed tree. + + Codex lists skills under the checkout's `.agents/skills` and `.codex/skills`, and a + `$name` mention in the prompt injects one; the PR controls both. Codex matches the + canonical SKILL.md path; its config offers no wildcard. A skill directory linking + outside the checkout, an unreadable one, or too many skills fails the attempt. + """ + try: + paths = _repository_skill_paths(cwd) + entries = ",".join( + f"{{path={json.dumps(path, ensure_ascii=False)},enabled=false}}" for path in sorted(paths) + ) + size = len(f"skills.config=[{entries}]".encode()) + except (OSError, RuntimeError, UnicodeError) as exc: + raise RunnerBadOutput(f"codex: cannot list repository skills to disable: {exc}") from exc + if size > CODEX_SKILL_OVERRIDE_LIMIT: + raise RunnerBadOutput(f"codex: {len(paths)} repository skills are too many to disable") + return ["-c", f"skills.config=[{entries}]"] if paths else [] + + +def _repository_skill_paths(cwd: Path) -> set[str]: + tree, paths, seen = cwd.resolve(), set(), set() + pending = [cwd / ".agents" / "skills", cwd / ".codex" / "skills"] + while pending: + directory = pending.pop() + if not directory.is_dir(): + continue + real = directory.resolve(strict=True) + # Checked before scanning: a link leaving the checkout stays visible to Codex. + if not real.is_relative_to(tree): + raise RunnerBadOutput(f"codex: skill directory {directory} links outside the checkout") + if real in seen: + continue + seen.add(real) + with os.scandir(real) as entries: + for entry in entries: + if entry.is_dir(): + pending.append(directory / entry.name) + elif entry.name == "SKILL.md": + paths.add(os.path.realpath(entry.path)) + return paths + + def _claude_provenance(envelope: dict, raw: str) -> dict[str, object]: required = ("session_id", "usage", "total_cost_usd", "duration_api_ms") if any(name not in envelope for name in required): @@ -1223,6 +1271,7 @@ def _review_codex( schema_file.write_text(json.dumps(REVIEW_SCHEMA), encoding="utf-8") auth_binds = _auth_binds("codex", home) prefix, config, binary = _sandbox_prefix("codex", cwd, home, ro_paths, auth_binds) + skill_overrides = _codex_repository_skill_overrides(cwd) # before Codex runs at all cli_version = _observe_codex_version(binary, cwd, config.env_allowlist) ignore_user_config = _codex_supports_ignore_user_config(binary, cwd, config.env_allowlist) argv = [ @@ -1244,6 +1293,10 @@ def _review_codex( "--skip-git-repo-check", "-c", "mcp_servers={}", + # The reviewed head controls AGENTS.md and its skills; keep both out of context. + "-c", + "project_doc_max_bytes=0", + *skill_overrides, "--output-schema", f"{sandbox.SANDBOX_HOME}/schema.json", "--output-last-message", diff --git a/tests/test_runners.py b/tests/test_runners.py index 1d5b2c30..d186d8e4 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -1076,6 +1076,80 @@ def test_bwrap_unavailable_fails_closed(fake_bin, tmp_path, monkeypatch, fake_to # ----------------------------------------------------------------- codex +def _plant_skills(repo: Path) -> None: + for skill in (repo / ".agents/skills/a/b", repo / ".codex/skills/c", repo / "docs/d"): + skill.mkdir(parents=True) + (skill / "SKILL.md").write_text("---\nname: planted\ndescription: planted\n---\n") + (repo / ".agents/skills/linked").symlink_to(repo / "docs/d") + (repo / ".agents/skills/loop").symlink_to(repo / ".agents/skills") + + +def test_codex_ignores_repository_instructions_and_skills(repo, fake_bin: Path, fake_bwrap: Path) -> None: + _plant_skills(repo) + (repo / "AGENTS.md").write_text("planted") + _fake_review(fake_bin, "codex") + _review("codex", repo) + argv = _argv(fake_bin, "codex") + assert "project_doc_max_bytes=0" in argv + (override,) = [a for a in argv if a.startswith("skills.config=")] + disabled = tomllib.loads(override)["skills"]["config"] + real = repo.resolve() + assert disabled == [{"path": str(path), "enabled": False} for path in ( + real / ".agents/skills/a/b/SKILL.md", real / ".codex/skills/c/SKILL.md", + real / "docs/d/SKILL.md", + )] + + +def _logging_codex(fake_tool, fake_bin: Path) -> Path: + """A fake Codex that records every call, version and help probes included.""" + fake_tool("codex", f'echo "$@" >> "{fake_bin}/codex.calls"\nexit 1\n') + return fake_bin / "codex.calls" + + +@pytest.mark.parametrize("link", [".codex/skills/host", ".agents/skills"]) +def test_codex_skill_links_leaving_the_checkout_fail_before_scan_or_launch( + repo, fake_bin: Path, fake_tool, fake_bwrap: Path, tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, link: str, +) -> None: + outside = tmp_path / "outside" + (outside / "skill").mkdir(parents=True) + (outside / "skill/SKILL.md").write_text("---\nname: host\ndescription: host\n---\n") + (repo / link).parent.mkdir(parents=True, exist_ok=True) + (repo / link).symlink_to(outside) + scanned = [] + real_scandir = os.scandir + def spy(path=".", *rest): + if not isinstance(path, int): + scanned.append(Path(path)) + return real_scandir(path, *rest) + monkeypatch.setattr("loopzero.runners.os.scandir", spy) + calls = _logging_codex(fake_tool, fake_bin) + with pytest.raises(RunnerBadOutput, match="links outside the checkout"): + _review("codex", repo) + assert not any(p.resolve().is_relative_to(outside.resolve()) for p in scanned) + assert not calls.exists() + + +@pytest.mark.parametrize("plant", ["too_many", "loop", "undecodable"]) +def test_codex_skill_lists_it_cannot_disable_fail_before_any_codex_call( + repo, fake_bin: Path, fake_tool, fake_bwrap: Path, monkeypatch: pytest.MonkeyPatch, plant: str, +) -> None: + if plant == "too_many": + _plant_skills(repo) + monkeypatch.setattr("loopzero.runners.CODEX_SKILL_OVERRIDE_LIMIT", 100) + elif plant == "loop": + (repo / ".agents/skills").mkdir(parents=True) + (repo / ".agents/skills/self").symlink_to("self") + else: + skill = repo / ".codex/skills" / os.fsdecode(b"\xff") + skill.mkdir(parents=True) + (skill / "SKILL.md").write_text("---\nname: x\ndescription: x\n---\n") + calls = _logging_codex(fake_tool, fake_bin) + with pytest.raises(RunnerBadOutput, match=r"too many to disable|cannot list repository skills"): + _review("codex", repo) + assert not calls.exists() + + def test_codex_approve(repo, fake_bin: Path, tmp_path: Path, fake_bwrap: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -1099,6 +1173,7 @@ def test_codex_approve(repo, assert "--ignore-user-config" in argv assert argv[argv.index("--cd") + 1] == str(repo.resolve()) and "--ephemeral" not in argv assert "mcp_servers={}" in argv + assert "project_doc_max_bytes=0" in argv and not any(a.startswith("skills.") for a in argv) assert argv[-1] == "-" isolated = (fake_bin / "codex.home").read_text() assert isolated != str(configured) and "loopzero-review-home-" in isolated