diff --git a/core/CONTRACT.md b/core/CONTRACT.md index 01f99ca4..c9d164e7 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -277,7 +277,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 1d67cb81..2e93a996 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -64,7 +64,8 @@ a new persistent store. ## Delivery and feedback -The [CLI](../src/loopzero/cli.py) implements the contract's +The [console entry point](../src/loopzero/_cli_entry.py) parses arguments before +loading the delivery [commands](../src/loopzero/cli.py), which implement the contract's [six steps](../core/CONTRACT.md#the-six-steps): 1. `start` creates an isolated worktree and task branch from the configured base. @@ -192,10 +193,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/pyproject.toml b/pyproject.toml index 31b6268a..9dd9780b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ version = "2.0.0a0" dependencies = ["PyYAML==6.0.3"] [project.scripts] -loopzero = "loopzero.cli:main" +loopzero = "loopzero._cli_entry:main" [build-system] requires = ["hatchling==1.33.0"] diff --git a/scripts/check_architecture_docs.py b/scripts/check_architecture_docs.py index c7147cb0..6d78847d 100644 --- a/scripts/check_architecture_docs.py +++ b/scripts/check_architecture_docs.py @@ -16,7 +16,7 @@ } # Compare selected owning interfaces rather than requiring doc churn for every bug fix. INTERFACES = { - "src/loopzero/cli.py": {"build_parser"}, + "src/loopzero/_cli_args.py": {"build_parser", "WAIT_TIMEOUT"}, "src/loopzero/config.py": {"_SECTIONS", "MERGE_STRATEGIES", "REVIEWER_FAMILIES"}, "src/loopzero/types.py": {"Config", "ResourceLimits", "ReviewConfig"}, } diff --git a/src/loopzero/_cli_args.py b/src/loopzero/_cli_args.py new file mode 100644 index 00000000..ce9af047 --- /dev/null +++ b/src/loopzero/_cli_args.py @@ -0,0 +1,103 @@ +"""Argument parsing shared by the console script and CLI module.""" + +from __future__ import annotations + +import argparse +import io +import sys + +WAIT_TIMEOUT = 1800.0 + + +def _wait_seconds(value: str) -> float: + from math import isfinite + + try: + seconds = float(value) + if isfinite(seconds) and seconds >= 0: + return seconds + except ValueError: + pass + raise argparse.ArgumentTypeError("expected a finite, nonnegative number of seconds") + + +def _config_path(value: str): + from pathlib import Path + + return Path(value) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="loopzero", description="One task, one branch, one draft PR, one review, one merge." + ) + parser.add_argument( + "--config", type=_config_path, default=None, help="path to workflow.toml (default: repo root)" + ) + parser.add_argument("--version", action=_VersionAction, nargs=0, help="show program's version number and exit") + sub = parser.add_subparsers(dest="command", required=True) + start = sub.add_parser("start", help="create an owned worktree and branch for ") + start.add_argument("slug") + sub.add_parser("check", help="run the configured checks in the sandbox") + sub.add_parser("pr", help="push and open or refresh the draft PR") + review = sub.add_parser("review", help="run native review and post one canonical review") + review.add_argument( + "--repost", action="store_true", help="post the saved review for HEAD without a model" + ) + review.add_argument("--model", help="reviewer model override for a fresh review") + review.add_argument("--effort", help="reviewer effort override for a fresh review") + ready = sub.add_parser( + "ready", help="compute readiness and mark the PR ready; --wait polls required checks" + ) + merge = sub.add_parser( + "merge", help="recheck readiness, merge and clean up; --wait waits for checks and landing" + ) + for waiter, what in ((ready, "required checks on this head"), (merge, "required checks and the landed merge")): + waiter.add_argument( + "--wait", nargs="?", const=WAIT_TIMEOUT, type=_wait_seconds, metavar="SECONDS", + help=f"wait for {what} (default {WAIT_TIMEOUT:.0f}s); exit 3 on timeout", + ) + merge.add_argument( + "--cancel", action="store_true", help="request removal from the configured Mergify queue" + ) + resolve = sub.add_parser( + "resolve", usage='%(prog)s [ ""]', + help="list open findings, or reply to one and resolve it", + ) + resolve.add_argument("finding", nargs="?", help="finding id from the list (8 hex digits)") + resolve.add_argument("reply", nargs="?", default="", help="what changed, e.g. the fix commit") + sub.add_parser("status", help="show where this branch is in the sequence") + return parser + + +def _version() -> str: + """Package version plus the pinned source revision when installed from Git.""" + import json + from importlib.metadata import distribution + + dist = distribution("loopzero") + try: + commit = json.loads(dist.read_text("direct_url.json") or "{}")["vcs_info"]["commit_id"] + except (KeyError, TypeError, json.JSONDecodeError): + commit = "unknown revision (not installed from a Git URL)" + return f"loopzero {dist.version} {commit}" + + +class _VersionAction(argparse.Action): + def __call__(self, parser, _namespace, _values, _option_string=None): + print(_version()) + parser.exit() + + +def parse_args(parser: argparse.ArgumentParser, argv: list[str] | None) -> argparse.Namespace: + # Progress lines must precede the stderr verdict when both go to one file. + if isinstance(sys.stdout, io.TextIOWrapper): + sys.stdout.reconfigure(line_buffering=True) + args = parser.parse_args(argv) + if args.command == "resolve" and args.finding is not None and not args.reply.strip(): + parser.error('expected resolve [ ""] with a nonblank reply for a finding') + if args.command == "review" and args.repost: + conflicts = [f"--{name}" for name in ("model", "effort") if getattr(args, name) is not None] + if conflicts: + parser.error(f"review --repost cannot be combined with {' or '.join(conflicts)}") + return args diff --git a/src/loopzero/_cli_entry.py b/src/loopzero/_cli_entry.py new file mode 100644 index 00000000..b7df2391 --- /dev/null +++ b/src/loopzero/_cli_entry.py @@ -0,0 +1,10 @@ +"""Console entry point. Load delivery commands only after parsing.""" + +from loopzero._cli_args import build_parser, parse_args + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(build_parser(), argv) + from loopzero.cli import _run + + return _run(args) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index b4c64c5f..5581821d 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -2,14 +2,17 @@ from __future__ import annotations +from loopzero._cli_args import build_parser, parse_args + +# Module execution parses help and version before loading delivery code. +if __name__ == "__main__": + _module_args = parse_args(build_parser(), None) + import argparse import dataclasses import fcntl import hashlib -import importlib.metadata -import io import json -import math import os import shlex import random @@ -37,7 +40,7 @@ # --wait: poll interval, default timeout, and how long a required check may stay # missing before GitHub is assumed to have dropped the event for this head. # Each poll costs several GitHub API calls from a quota shared by every session. -WAIT_INTERVAL, WAIT_TIMEOUT, MISSING_RUN_GRACE = 30.0, 1800.0, 120.0 +WAIT_INTERVAL, MISSING_RUN_GRACE = 30.0, 120.0 STALE_VERDICT_GRACE, MAX_REVIEW_CLOCK_SKEW = 900.0, 30.0 PUSH_TIMEOUT = 600.0 # consumer pre-push hooks (lint, tests) routinely exceed GIT_TIMEOUT NEXT_WAIT = "next: loopzero ready --wait" # named at the moment of need; agents hand-roll polls otherwise @@ -1746,92 +1749,14 @@ def _print_mergify_status(config: Config, pr: github.PR, readiness: github.Readi # --------------------------------------------------------------------------- entry point -def _wait_seconds(value: str) -> float: - try: - seconds = float(value) - if math.isfinite(seconds) and seconds >= 0: - return seconds - except ValueError: - pass - raise argparse.ArgumentTypeError("expected a finite, nonnegative number of seconds") - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - prog="loopzero", description="One task, one branch, one draft PR, one review, one merge." - ) - parser.add_argument( - "--config", type=Path, default=None, help="path to workflow.toml (default: repo root)" - ) - parser.add_argument("--version", action="version", version=_version()) - sub = parser.add_subparsers(dest="command", required=True) - start = sub.add_parser("start", help="create an owned worktree and branch for ") - start.add_argument("slug") - start.set_defaults(func=cmd_start) - sub.add_parser("check", help="run the configured checks in the sandbox").set_defaults( - func=cmd_check - ) - sub.add_parser("pr", help="push and open or refresh the draft PR").set_defaults(func=cmd_pr) - review = sub.add_parser("review", help="run native review and post one canonical review") - review.add_argument( - "--repost", action="store_true", help="post the saved review for HEAD without a model" - ) - review.add_argument("--model", help="reviewer model override for a fresh review") - review.add_argument("--effort", help="reviewer effort override for a fresh review") - review.set_defaults(func=cmd_review) - ready = sub.add_parser( - "ready", help="compute readiness and mark the PR ready; --wait polls required checks" - ) - merge = sub.add_parser( - "merge", help="recheck readiness, merge and clean up; --wait waits for checks and landing" - ) - for waiter, what in ((ready, "required checks on this head"), (merge, "required checks and the landed merge")): - waiter.add_argument( - "--wait", nargs="?", const=WAIT_TIMEOUT, type=_wait_seconds, metavar="SECONDS", - help=f"wait for {what} (default {WAIT_TIMEOUT:.0f}s); exit 3 on timeout", - ) - merge.add_argument( - "--cancel", action="store_true", help="request removal from the configured Mergify queue" - ) - ready.set_defaults(func=cmd_ready) - merge.set_defaults(func=cmd_merge) - resolve = sub.add_parser( - "resolve", usage='%(prog)s [ ""]', - help="list open findings, or reply to one and resolve it", - ) - resolve.add_argument("finding", nargs="?", help="finding id from the list (8 hex digits)") - resolve.add_argument("reply", nargs="?", default="", help="what changed, e.g. the fix commit") - resolve.set_defaults(func=cmd_resolve) - status = sub.add_parser("status", help="show where this branch is in the sequence") - status.set_defaults(func=cmd_status) - return parser - - -def _version() -> str: - """Package version plus the pinned source revision when installed from Git.""" - dist = importlib.metadata.distribution("loopzero") - try: - commit = json.loads(dist.read_text("direct_url.json") or "{}")["vcs_info"]["commit_id"] - except (KeyError, TypeError, json.JSONDecodeError): - commit = "unknown revision (not installed from a Git URL)" - return f"loopzero {dist.version} {commit}" +def main(argv: list[str] | None = None) -> int: + return _run(parse_args(build_parser(), argv)) -def main(argv: list[str] | None = None) -> int: - # Progress lines must precede the stderr verdict when both go to one file. - if isinstance(sys.stdout, io.TextIOWrapper): - sys.stdout.reconfigure(line_buffering=True) - parser = build_parser() - args = parser.parse_args(argv) - if args.command == "resolve" and args.finding is not None and not args.reply.strip(): - parser.error('expected resolve [ ""] with a nonblank reply for a finding') - if args.command == "review" and args.repost: - conflicts = [f"--{name}" for name in ("model", "effort") if getattr(args, name) is not None] - if conflicts: - parser.error(f"review --repost cannot be combined with {' or '.join(conflicts)}") +def _run(args: argparse.Namespace) -> int: try: with _proc.unwind_on_sigterm(): - return args.func(args) + return globals()[f"cmd_{args.command}"](args) except IndependentReviewerUnavailable as exc: print(f"loopzero {args.command}: {exc}", file=sys.stderr) return 4 @@ -1852,4 +1777,4 @@ def _one_line(exc: BaseException) -> str: if __name__ == "__main__": - sys.exit(main()) + sys.exit(_run(_module_args)) diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 821a9965..0e384789 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -488,6 +488,57 @@ 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( + # TOML basic strings forbid a literal DEL, which JSON leaves unescaped. + f"{{path={json.dumps(path, ensure_ascii=False).replace(chr(127), '\\u007f')},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: + path = pending.pop() + if not os.path.lexists(path): + continue + # Strict: a looping or dangling link fails closed; Codex might resolve it elsewhere. + real = path.resolve(strict=True) + if not real.is_relative_to(tree): + raise RunnerBadOutput(f"codex: skill directory {path} links outside the checkout") + if not real.is_dir(): + if path.name == "SKILL.md": + paths.add(str(real)) + continue + if real in seen: + continue + seen.add(real) + with os.scandir(real) as entries: + pending.extend(path / entry.name for entry in entries + if entry.is_symlink() or entry.is_dir() or entry.name == "SKILL.md") + 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): @@ -1228,6 +1279,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 = [ @@ -1249,6 +1301,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/tach.toml b/tach.toml index 442c5302..58b5df60 100644 --- a/tach.toml +++ b/tach.toml @@ -69,6 +69,7 @@ depends_on = [ [[modules]] path = "loopzero.cli" depends_on = [ + "loopzero._cli_args", "loopzero._proc", "loopzero.config", "loopzero.eligibility", @@ -79,3 +80,11 @@ depends_on = [ "loopzero.types", "loopzero.worktree", ] + +[[modules]] +path = "loopzero._cli_args" +depends_on = [] + +[[modules]] +path = "loopzero._cli_entry" +depends_on = ["loopzero._cli_args", "loopzero.cli"] diff --git a/tests/test_architecture_docs.py b/tests/test_architecture_docs.py index 5be3231f..25410cee 100644 --- a/tests/test_architecture_docs.py +++ b/tests/test_architecture_docs.py @@ -81,7 +81,7 @@ def test_broken_local_link_fails_even_with_guide_update(git_repo, target): def test_private_code_fix_needs_no_pointless_documentation_edit(git_repo): base = prepare(git_repo) - path = git_repo / "src/loopzero/cli.py" + path = git_repo / "src/loopzero/_cli_args.py" path.parent.mkdir(parents=True) path.write_text("def build_parser():\n return 'public'\n\ndef _fix():\n return 1\n") git(git_repo, "add", ".") diff --git a/tests/test_cli.py b/tests/test_cli.py index fda149c0..055d1a74 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1123,10 +1123,9 @@ def test_pr_accepts_angle_brackets_and_sublists_as_filled_text(wt: Path) -> None def test_progress_output_precedes_the_stderr_verdict_in_one_file(tmp_path: Path) -> None: - script = ("import argparse, sys\nfrom loopzero import cli\np = argparse.ArgumentParser()\n" - "def wait(args):\n print('waiting')\n raise cli.CliError('dequeued')\n" - "p.set_defaults(func=wait, command='merge')\ncli.build_parser = lambda: p\n" - "sys.exit(cli.main([]))\n") + script = ("import sys\nfrom loopzero import cli\ndef wait(args):\n" + " print('waiting')\n raise cli.CliError('dequeued')\n" + "cli.cmd_merge = wait\nsys.exit(cli.main(['merge']))\n") with (tmp_path / "log").open("w") as log: subprocess.run([sys.executable, "-c", script], stdout=log, stderr=subprocess.STDOUT, check=False) assert (tmp_path / "log").read_text().splitlines() == ["waiting", "loopzero merge: dequeued"] @@ -1259,11 +1258,12 @@ def test_pr_refuses_to_overwrite_a_pr_head_it_has_never_seen( assert git(origin, "rev-parse", "refs/heads/lz/t1").strip() == pushed -def test_version_names_the_installed_revision(capsys) -> None: - with pytest.raises(SystemExit) as stop: - cli.main(["--version"]) - out = capsys.readouterr().out - assert stop.value.code == 0 and re.fullmatch(r"loopzero \S+ .+\n", out), out +@pytest.mark.parametrize("flag, pattern", [("--version", r"loopzero \S+ .+\n\Z"), ("--help", r"usage: loopzero ")]) +def test_cli_info_leaves_delivery_backends_unloaded(flag, pattern): + for entry in (("-m", "loopzero.cli"), ("-c", "from loopzero._cli_entry import main; main()")): + done = subprocess.run([sys.executable, "-X", "importtime", *entry, flag], capture_output=True, text=True) + assert done.returncode == 0 and re.match(pattern, done.stdout), done + assert not re.search(r"loopzero\.(github|mergify|runners|sandbox)\b", done.stderr) def test_pr_refuses_dirty(wt: Path, gh: FakeGh, capsys) -> None: @@ -2736,7 +2736,7 @@ def advance(seconds): @pytest.mark.parametrize("after", ["pending", "late_success", "head_move", "blocker", "cancelled"]) -def test_ready_transition_preserves_deadline_and_gates(wt, gh, capsys, monkeypatch, head, after): +def test_ready_transition_preserves_deadline_and_gates(wt, gh, capsys, monkeypatch, head, after, replay_gh): arm_approved_pr_with_check_result(gh, head, wt, "pending") gh.respond("pr ready", "") clock, sleeps, transitioned = [0.0], [], [False] @@ -2817,14 +2817,13 @@ def advance(seconds): @pytest.mark.parametrize("wait,draft", [(True, True), (False, True), (True, False)]) -def test_ready_transition_immediate_green_is_best_effort(wt, gh, capsys, head, wait, draft): +def test_ready_transition_immediate_green_is_best_effort(wt, gh, capsys, head, wait, draft, replay_gh): arm_approved_ready_pr(gh, head, wt, isDraft=draft) gh.respond("pr ready", "") code, out, err = run(capsys, "ready", *(["--wait"] if wait else [])) - out = without_accepted_receipt(out) - assert (code, out, err) == (0, f"ready: {URL}\n", "") + assert (code, without_accepted_receipt(out), err) == (0, f"ready: {URL}\n", "") assert sum(c["argv"][:2] == ["pr", "ready"] for c in gh.calls) == int(draft) observations = sum(c["argv"][:2] == ["api", f"repos/{REPO}/commits/{head}/check-runs"] for c in gh.calls) @@ -2865,7 +2864,7 @@ def test_ready_wait_review_failure_freshness( wait, expected, waited, - head, + head, replay_gh, ) -> None: (wt / "workflow.toml").write_text(WORKFLOW.replace('["checks"]', json.dumps([name]))) arm_approved_pr_with_check_result( diff --git a/tests/test_review_recovery.py b/tests/test_review_recovery.py index 0518066e..47202ff5 100644 --- a/tests/test_review_recovery.py +++ b/tests/test_review_recovery.py @@ -21,6 +21,7 @@ ) gh, git_seed, repo, wt = support.gh, support.git_seed, support.repo, support.wt +replay_gh = support.replay_gh REVIEW_COMMENTS = f"api repos/{REPO}/pulls/7/reviews/17/comments?per_page=100&page=1" @@ -88,7 +89,7 @@ def assert_single_publication(gh, fake_bin): @pytest.mark.parametrize("verdict", [0, 5]) @pytest.mark.parametrize("interrupted", [False, True, "timeout"]) def test_accepted_publication_recovers_saved_verdict( - wt, gh, fake_bin, monkeypatch, capsys, kind, verdict, interrupted, + wt, gh, fake_bin, monkeypatch, capsys, kind, verdict, interrupted, replay_gh, ): lost_reply(wt, gh, fake_bin, monkeypatch, kind=kind, verdict=verdict, interrupted=interrupted is True, timeout=interrupted == "timeout") @@ -113,7 +114,7 @@ def test_accepted_publication_recovers_saved_verdict( "head", "comment_page", "kind", "wrong_head"]) @pytest.mark.parametrize("interrupted", [False, True]) def test_recovery_requires_exact_live_publication( - wt, gh, fake_bin, monkeypatch, capsys, change, interrupted, + wt, gh, fake_bin, monkeypatch, capsys, change, interrupted, replay_gh, ): def mutate(rows, comments): if change == "body": @@ -247,7 +248,7 @@ def request(argv, **kwargs): ("null", "single"), ("empty", "single"), ("malformed", "single"), ]) def test_historical_publication_recovery_is_exact_and_legacy_only( - interrupted_receipt, gh, fake_bin, capsys, metadata, source, shape, + replay_gh, interrupted_receipt, gh, fake_bin, capsys, metadata, source, shape, ): head, path, saved, _ = interrupted_receipt envelope = json.loads(saved["raw"]) diff --git a/tests/test_runners.py b/tests/test_runners.py index dfec1550..2cfa34e8 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -1104,6 +1104,85 @@ 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 / ".agents/skills/e\x7f", 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 / ".agents/skills/e\x7f/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", "dangling", "root_loop:.agents/skills", "root_loop:.codex/skills"]) +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 in ("loop", "dangling"): + (repo / ".agents/skills").mkdir(parents=True) + (repo / ".agents/skills/x").symlink_to("x" if plant == "loop" else "/nonexistent/skills") + elif plant.startswith("root_loop:"): + root = repo / plant.partition(":")[2] + root.parent.mkdir(parents=True) + root.symlink_to(root.name) + 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: @@ -1127,6 +1206,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