From c3d060d8995fc41bbb6fcb442f7066a8cca3fac4 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:55:20 +0100 Subject: [PATCH 01/11] Keep the reviewed head's instruction files and skills from Codex reviewers The Codex reviewer now launches with project_doc_max_bytes=0, so the reviewed head's AGENTS.md and AGENTS.override.md are not loaded, and with a skills.config entry disabling every skill under the checkout's .agents/skills and .codex/skills. The PR controls both surfaces; they now reach the reviewer only as evidence. ARCHITECTURE.md and CONTRACT.md state which instruction surfaces each reviewer loads. Closes #1107 Co-Authored-By: Claude Opus 5.5 --- core/CONTRACT.md | 2 +- docs/ARCHITECTURE.md | 12 ++++++++---- src/loopzero/runners.py | 31 +++++++++++++++++++++++++++++++ tests/test_runners.py | 25 +++++++++++++++++++++++++ 4 files changed, 65 insertions(+), 5 deletions(-) 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..e5c198d1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -181,10 +181,14 @@ 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`. 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..3287eb53 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -473,6 +473,33 @@ def _codex_supports_ignore_user_config( return done.exit_code == 0 and "--ignore-user-config" in f"{done.stdout}\n{done.stderr}" +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. + """ + tree, paths = cwd.resolve(), set() + for root in (cwd / ".agents" / "skills", cwd / ".codex" / "skills"): + seen: set[Path] = set() + for directory, dirs, files in os.walk(root, followlinks=True): + real = Path(directory).resolve() + # Links leaving the checkout point at host files, not PR content. + if real in seen or not real.is_relative_to(tree): + dirs[:] = [] + continue + seen.add(real) + if "SKILL.md" in files: + paths.add(os.path.realpath(os.path.join(directory, "SKILL.md"))) + if not paths: + return [] + entries = ",".join( + f"{{path={json.dumps(path, ensure_ascii=False)},enabled=false}}" for path in sorted(paths) + ) + return ["-c", f"skills.config=[{entries}]"] + + 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): @@ -1244,6 +1271,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", + *_codex_repository_skill_overrides(cwd), "--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..480a9944 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -1076,6 +1076,30 @@ def test_bwrap_unavailable_fails_closed(fake_bin, tmp_path, monkeypatch, fake_to # ----------------------------------------------------------------- codex +def test_codex_ignores_repository_instructions_and_skills( + repo, fake_bin: Path, tmp_path: Path, fake_bwrap: Path, +) -> None: + outside = tmp_path / "outside" + for skill in (repo / ".agents/skills/a/b", repo / ".codex/skills/c", repo / "docs/d", outside): + skill.mkdir(parents=True) + (skill / "SKILL.md").write_text("---\nname: planted\ndescription: planted\n---\n") + (repo / "AGENTS.md").write_text("planted") + (repo / ".agents/skills/linked").symlink_to(repo / "docs/d") + (repo / ".agents/skills/loop").symlink_to(repo / ".agents/skills") + (repo / ".codex/skills/host").symlink_to(outside) + _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 test_codex_approve(repo, fake_bin: Path, tmp_path: Path, fake_bwrap: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -1099,6 +1123,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 From 6b8e883296ce764aa7c7f4061e52ae7d1df0740e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:16:24 +0100 Subject: [PATCH 02/11] Fail closed on external or oversized Codex skill lists A skill directory under the reviewed checkout that links outside it is now rejected before anything behind the link is scanned, and a disable list too large for one process argument fails as a runner error, so neither can leave a PR-selected skill enabled or crash the launch. Refs #1107 Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 4 +++- src/loopzero/runners.py | 48 ++++++++++++++++++++++++++++++----------- tests/test_runners.py | 48 +++++++++++++++++++++++++++++++++++------ 3 files changed, 79 insertions(+), 21 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e5c198d1..c62c3387 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -185,7 +185,9 @@ 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`. Repository +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. diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 3287eb53..8bb372da 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -473,31 +473,53 @@ 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. + canonical SKILL.md path; its config offers no wildcard. A skill directory linking + outside the checkout, or too many skills to disable, fails the attempt. """ - tree, paths = cwd.resolve(), set() - for root in (cwd / ".agents" / "skills", cwd / ".codex" / "skills"): - seen: set[Path] = set() - for directory, dirs, files in os.walk(root, followlinks=True): - real = Path(directory).resolve() - # Links leaving the checkout point at host files, not PR content. - if real in seen or not real.is_relative_to(tree): - dirs[:] = [] + tree, paths, seen = cwd.resolve(), set(), set() + pending = [cwd / ".agents" / "skills", cwd / ".codex" / "skills"] + while pending: + directory = pending.pop() + try: + if not directory.is_dir(): continue - seen.add(real) - if "SKILL.md" in files: - paths.add(os.path.realpath(os.path.join(directory, "SKILL.md"))) + real = directory.resolve(strict=True) + except (OSError, RuntimeError) as exc: + raise RunnerBadOutput(f"codex: unreadable skill directory {directory}") from exc + # 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 _codex_disabled_skills(paths) + + +def _codex_disabled_skills(paths: set[str]) -> list[str]: if not paths: return [] entries = ",".join( f"{{path={json.dumps(path, ensure_ascii=False)},enabled=false}}" for path in sorted(paths) ) - return ["-c", f"skills.config=[{entries}]"] + override = f"skills.config=[{entries}]" + if len(override.encode()) > CODEX_SKILL_OVERRIDE_LIMIT: + raise RunnerBadOutput(f"codex: {len(paths)} repository skills are too many to disable") + return ["-c", override] def _claude_provenance(envelope: dict, raw: str) -> dict[str, object]: diff --git a/tests/test_runners.py b/tests/test_runners.py index 480a9944..74e19a65 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -1076,17 +1076,17 @@ def test_bwrap_unavailable_fails_closed(fake_bin, tmp_path, monkeypatch, fake_to # ----------------------------------------------------------------- codex -def test_codex_ignores_repository_instructions_and_skills( - repo, fake_bin: Path, tmp_path: Path, fake_bwrap: Path, -) -> None: - outside = tmp_path / "outside" - for skill in (repo / ".agents/skills/a/b", repo / ".codex/skills/c", repo / "docs/d", outside): +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.md").write_text("planted") (repo / ".agents/skills/linked").symlink_to(repo / "docs/d") (repo / ".agents/skills/loop").symlink_to(repo / ".agents/skills") - (repo / ".codex/skills/host").symlink_to(outside) + + +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") @@ -1100,6 +1100,40 @@ def test_codex_ignores_repository_instructions_and_skills( )] +@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_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) + _fake_review(fake_bin, "codex") + 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 (fake_bin / "codex.stdin").exists() + + +def test_codex_too_many_skills_to_disable_fails_before_launch( + repo, fake_bin: Path, fake_bwrap: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + _plant_skills(repo) + monkeypatch.setattr("loopzero.runners.CODEX_SKILL_OVERRIDE_LIMIT", 100) + _fake_review(fake_bin, "codex") + with pytest.raises(RunnerBadOutput, match="3 repository skills are too many to disable"): + _review("codex", repo) + assert not (fake_bin / "codex.stdin").exists() + + def test_codex_approve(repo, fake_bin: Path, tmp_path: Path, fake_bwrap: Path, monkeypatch: pytest.MonkeyPatch ) -> None: From dcffe163a90aa6d2ca5d889033ac1f03fc422f36 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:04:55 +0100 Subject: [PATCH 03/11] Check Codex skill policy before any Codex call and on every scan error The repository skill list is now computed before the Codex version and help probes run, and any error while listing skills, including symlink loops and paths that cannot be encoded as UTF-8, fails the attempt as a runner error so the next reviewer family is tried. Refs #1107 Co-Authored-By: Claude Opus 5.5 --- src/loopzero/runners.py | 42 ++++++++++++++++++++--------------------- tests/test_runners.py | 36 +++++++++++++++++++++++++---------- 2 files changed, 47 insertions(+), 31 deletions(-) diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 8bb372da..3684da48 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -483,18 +483,29 @@ def _codex_repository_skill_overrides(cwd: Path) -> list[str]: 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, or too many skills to disable, fails the attempt. + 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() - try: - if not directory.is_dir(): - continue - real = directory.resolve(strict=True) - except (OSError, RuntimeError) as exc: - raise RunnerBadOutput(f"codex: unreadable skill directory {directory}") from exc + 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") @@ -507,19 +518,7 @@ def _codex_repository_skill_overrides(cwd: Path) -> list[str]: pending.append(directory / entry.name) elif entry.name == "SKILL.md": paths.add(os.path.realpath(entry.path)) - return _codex_disabled_skills(paths) - - -def _codex_disabled_skills(paths: set[str]) -> list[str]: - if not paths: - return [] - entries = ",".join( - f"{{path={json.dumps(path, ensure_ascii=False)},enabled=false}}" for path in sorted(paths) - ) - override = f"skills.config=[{entries}]" - if len(override.encode()) > CODEX_SKILL_OVERRIDE_LIMIT: - raise RunnerBadOutput(f"codex: {len(paths)} repository skills are too many to disable") - return ["-c", override] + return paths def _claude_provenance(envelope: dict, raw: str) -> dict[str, object]: @@ -1272,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 = [ @@ -1296,7 +1296,7 @@ def _review_codex( # The reviewed head controls AGENTS.md and its skills; keep both out of context. "-c", "project_doc_max_bytes=0", - *_codex_repository_skill_overrides(cwd), + *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 74e19a65..d186d8e4 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -1100,9 +1100,16 @@ def test_codex_ignores_repository_instructions_and_skills(repo, fake_bin: Path, )] +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_bwrap: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, link: str, + 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) @@ -1116,22 +1123,31 @@ def spy(path=".", *rest): scanned.append(Path(path)) return real_scandir(path, *rest) monkeypatch.setattr("loopzero.runners.os.scandir", spy) - _fake_review(fake_bin, "codex") + 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 (fake_bin / "codex.stdin").exists() + assert not calls.exists() -def test_codex_too_many_skills_to_disable_fails_before_launch( - repo, fake_bin: Path, fake_bwrap: Path, monkeypatch: pytest.MonkeyPatch, +@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: - _plant_skills(repo) - monkeypatch.setattr("loopzero.runners.CODEX_SKILL_OVERRIDE_LIMIT", 100) - _fake_review(fake_bin, "codex") - with pytest.raises(RunnerBadOutput, match="3 repository skills are too many to disable"): + 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 (fake_bin / "codex.stdin").exists() + assert not calls.exists() def test_codex_approve(repo, From 15469fa011cbc136e64b16392ce0e1e1d0f90c41 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:58:32 +0100 Subject: [PATCH 04/11] Resolve every Codex skill link strictly and escape DEL for TOML A looping or dangling link at or under either skill root now fails the Codex attempt instead of being skipped, a symlinked SKILL.md is disabled by its target, and a DEL character in a skill path is escaped so the skills.config override stays valid TOML. Refs #1107 Co-Authored-By: Claude Opus 5.5 --- src/loopzero/runners.py | 25 ++++++++++++++----------- tests/test_runners.py | 15 ++++++++++----- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 01536457..b5994f67 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -501,7 +501,9 @@ def _codex_repository_skill_overrides(cwd: Path) -> list[str]: try: paths = _repository_skill_paths(cwd) entries = ",".join( - f"{{path={json.dumps(path, ensure_ascii=False)},enabled=false}}" for path in sorted(paths) + # 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: @@ -515,22 +517,23 @@ 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(): + path = pending.pop() + if not os.path.lexists(path): continue - real = directory.resolve(strict=True) - # Checked before scanning: a link leaving the checkout stays visible to Codex. + # 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 {directory} links outside the checkout") + 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: - 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)) + pending.extend(path / entry.name for entry in entries + if entry.is_symlink() or entry.is_dir() or entry.name == "SKILL.md") return paths diff --git a/tests/test_runners.py b/tests/test_runners.py index 02d320ea..44e25bd2 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -1092,7 +1092,7 @@ def test_bwrap_unavailable_fails_closed(fake_bin, tmp_path, monkeypatch, fake_to def _plant_skills(repo: Path) -> None: - for skill in (repo / ".agents/skills/a/b", repo / ".codex/skills/c", repo / "docs/d"): + 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") @@ -1110,7 +1110,7 @@ def test_codex_ignores_repository_instructions_and_skills(repo, fake_bin: Path, 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 / ".agents/skills/a/b/SKILL.md", real / ".agents/skills/e\x7f/SKILL.md", real / ".codex/skills/c/SKILL.md", real / "docs/d/SKILL.md", )] @@ -1145,16 +1145,21 @@ def spy(path=".", *rest): assert not calls.exists() -@pytest.mark.parametrize("plant", ["too_many", "loop", "undecodable"]) +@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 == "loop": + elif plant in ("loop", "dangling"): (repo / ".agents/skills").mkdir(parents=True) - (repo / ".agents/skills/self").symlink_to("self") + (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) From 66e67b236e601a3967512a7fff5d85be3580dfa4 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:38:37 +0100 Subject: [PATCH 05/11] Validate repository skill parent paths before descending Architecture-Review: unchanged; the existing pre-launch checkout containment rule now also covers the parent directories. Co-Authored-By: Codex --- src/loopzero/runners.py | 10 ++++++++-- tests/test_runners.py | 15 +++++++-------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index b5994f67..fe1a29d8 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -515,10 +515,13 @@ def _codex_repository_skill_overrides(cwd: Path) -> list[str]: def _repository_skill_paths(cwd: Path) -> set[str]: tree, paths, seen = cwd.resolve(), set(), set() - pending = [cwd / ".agents" / "skills", cwd / ".codex" / "skills"] + roots = (cwd / ".agents", cwd / ".codex") + pending = list(roots) while pending: path = pending.pop() - if not os.path.lexists(path): + try: + path.lstat() + except FileNotFoundError: continue # Strict: a looping or dangling link fails closed; Codex might resolve it elsewhere. real = path.resolve(strict=True) @@ -528,6 +531,9 @@ def _repository_skill_paths(cwd: Path) -> set[str]: if path.name == "SKILL.md": paths.add(str(real)) continue + if path in roots: + pending.append(path / "skills") + continue if real in seen: continue seen.add(real) diff --git a/tests/test_runners.py b/tests/test_runners.py index cbc78109..74ad5a70 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -1159,20 +1159,19 @@ def spy(path=".", *rest): @pytest.mark.parametrize("plant", [ - "too_many", "loop", "undecodable", "dangling", "root_loop:.agents/skills", "root_loop:.codex/skills"]) + "too_many", "loop", "undecodable", "dangling", "loop:.agents/skills", "loop:.codex/skills", + "loop:.agents", "loop:.codex", "dangling:.agents", "dangling:.codex"]) 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) + elif plant != "undecodable": + kind, _, name = plant.partition(":") + link = repo / (name or ".agents/skills/x") + link.parent.mkdir(parents=True, exist_ok=True) + link.symlink_to(link.name if kind == "loop" else "missing") else: skill = repo / ".codex/skills" / os.fsdecode(b"\xff") skill.mkdir(parents=True) From 1aae039df95b20418eeb4d7984dad4f761a9fb78 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:30:32 +0100 Subject: [PATCH 06/11] Keep hosted eligibility pending during GitHub outages Architecture-Review: unchanged; remains fail-closed while trusted evidence is unavailable, with the same status context and publisher. Co-Authored-By: Codex --- src/loopzero/eligibility.py | 2 ++ src/loopzero/github.py | 38 ++++++++++++++++++------- src/loopzero/hosted.py | 10 +++++-- tests/test_hosted.py | 56 ++++++++++++++++++------------------- 4 files changed, 65 insertions(+), 41 deletions(-) diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 41de7f3c..274703a1 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -121,6 +121,8 @@ def _clean_base_merges(repo: str, number: int, reviewed: str, head: str, base_br return False cursor = first return cursor == reviewed + except github.GhUnavailable: + raise except (candidate.CandidateError, github.GhError, KeyError, OSError, TypeError, ValueError): return False diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 171efcb9..458bcf57 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -68,7 +68,11 @@ def __init__(self, command: tuple[str, ...], tail: str, *, super().__init__(f"{command_text} failed: {self.tail.strip()[-600:]}") -class ReadDeadline(GhError): +class GhUnavailable(GhError): + """GitHub could not supply a result because of a transient fault or limit.""" + + +class ReadDeadline(GhUnavailable): """A shared GitHub read deadline elapsed.""" @@ -305,12 +309,26 @@ def _select_token(token: str | None, scope: tuple[float, str | None, bool] | Non return selected if selected is not None else (app_token() if read_only else "") -def _transient_error(tail: str, retry_idempotent: bool) -> bool: - return bool(TRANSIENT_RE.search(tail)) or ( +def _transient_error(tail: str, retry_idempotent: bool, status: str | None = None) -> bool: + return (status or "").startswith("5") or bool(TRANSIENT_RE.search(tail)) or ( retry_idempotent and "something went wrong while executing your query" in tail.lower() ) +def _request_error(transient: bool) -> type[GhError]: + return GhUnavailable if transient else GhError + + +def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> bool: + return (status == "429" + or (status == "403" and (headers.get("x-ratelimit-remaining") == "0" or "retry-after" in headers)) + or bool(re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE))) + + +def _retry_delays(scope: tuple[float, str | None, bool] | None, diagnostic: bool) -> tuple: + return (None,) if scope and not scope[2] else (*(RETRY_DELAYS[:1] if diagnostic else RETRY_DELAYS), None) + + def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str: if (using_app and len(args) > 1 and args[0] == "api" and re.fullmatch(r"repos/[^/]+/[^/]+/pulls\?.+", args[1]) @@ -332,7 +350,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, read_only = _read_only(args) retryable = read_only or retry_idempotent scope = _read_scope.get() if read_only else None - delays = (None,) if scope and not scope[2] else (*RETRY_DELAYS, None) + delays = _retry_delays(scope, diagnostic_api) for delay in delays: selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token try: @@ -355,16 +373,16 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, status, headers, body = (_included_response(done.stdout) if rest_api or diagnostic_api else (None, {}, done.stdout)) tail = "\n".join(part for part in (done.stderr, body if rest_api else done.stdout) if part) - if done.exit_code and ((rest_api and status == "429") - or re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE)): + if done.exit_code and _rate_limited(status, headers, tail): guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api else _graphql_reset(args, tail, cwd, selected) + RATE_LIMIT_GUIDANCE) if diagnostic_api or patch_error: detail = _api_error_detail(args, done.stdout if diagnostic_api else "", done.stderr, selected, message_tail=None if diagnostic_api else tail) - raise GhError(("GitHub API request",), detail, token=selected, guidance=guidance) - raise GhError(argv, tail, token=selected, guidance=guidance) - if done.exit_code == 0 or delay is None or not retryable or not _transient_error(tail, retry_idempotent): + raise GhUnavailable(("GitHub API request",), detail, token=selected, guidance=guidance) + raise GhUnavailable(argv, tail, token=selected, guidance=guidance) + transient = _transient_error(tail, retry_idempotent, status) + if done.exit_code == 0 or delay is None or not retryable or not transient: break _retry_sleep(_read_timeout(delay) if scope else delay) if done.exit_code != 0: @@ -375,7 +393,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, if "gh auth login" in tail or "not logged in" in tail.lower(): raise GhAuth(error_command, error_tail.rstrip(), token=selected, guidance=f"\n{GH_AUTH_REMEDY}") guidance = _pr_list_error_guidance(args, done.stderr, bool(read_only and selected and token is None)) - raise GhError(error_command, error_tail, token=selected, guidance=guidance) + raise _request_error(transient)(error_command, error_tail, token=selected, guidance=guidance) return body diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 3b963850..e257ae5b 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -36,8 +36,12 @@ def main() -> int: except config.ConfigError as exc: print(exc, file=sys.stderr) return 1 - with github.api_error_diagnostics(): - return _run(cfg) + try: + with github.api_error_diagnostics(): + return _run(cfg) + except (github.GhUnavailable, github.ProcTimeout) as exc: + print(f"Eligibility unconfirmed: GitHub evidence unavailable ({exc})", file=sys.stderr) + return 0 def _run(cfg: Config) -> int: @@ -111,7 +115,7 @@ def _publish_verdict(repo: str, head: str, state: str, description: str) -> None def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None: - if not isinstance(exc, github.StatusLimitReached): + if not isinstance(exc, (github.GhUnavailable, github.ProcTimeout, github.StatusLimitReached)): with suppress(Exception): publish("failure", "Eligibility refresh failed; inspect workflow logs") diff --git a/tests/test_hosted.py b/tests/test_hosted.py index f9295795..1b0d5306 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -53,8 +53,7 @@ def test_event_selection(event, number): def publisher(tmp_path, fake_bin, monkeypatch): monkeypatch.chdir(tmp_path) monkeypatch.setenv("GITHUB_REPOSITORY", REPO) - event = tmp_path / "event.json" - event.write_text(json.dumps({"pull_request": {"number": 7}})) + (event := tmp_path / "event.json").write_text(json.dumps({"pull_request": {"number": 7}})) monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) Path("workflow.toml").write_text(f'[repo]\nname="{REPO}"\nbase="main"\n[delivery]\nreview_publishers=["trusted-publisher"]\n') gh = FakeGh(fake_bin, tmp_path) @@ -64,6 +63,7 @@ def publisher(tmp_path, fake_bin, monkeypatch): gh.respond_pr_view(pr_json()) gh.respond("api graphql", threads_json()) gh.respond(f"api repos/{REPO}/statuses/{HEAD}", {}) + gh.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", []) return gh @@ -143,28 +143,29 @@ def lose_reply(repo, head, context, value, description): assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == ["pending", state] -@pytest.mark.parametrize("error", ["api", "head", "publication", "config"]) -def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, error): - monkeypatch.setattr(github, "_retry_sleep", lambda _: None) - publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", []) - if error == "api": - publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", - {"stdout": "HTTP/2.0 503 Service Unavailable\r\nX-GitHub-Request-Id: GHREQ-8774\r\n\r\n{\"message\":\"Service unavailable github_pat_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\"}", "stderr": "gh: Service unavailable (HTTP 503)", "exit": 1}) +@pytest.mark.parametrize("error", ["api", "recover", "head", "publication", "config"]) +def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, capsys, error): + sleeps = [] + monkeypatch.setattr(github, "_retry_sleep", sleeps.append) + reviews = f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1" + if error in {"api", "recover"}: + fault = {"stdout": "HTTP/2.0 503 Service Unavailable\r\nX-GitHub-Request-Id: GHREQ-8774\r\n\r\n{\"message\":\"Service unavailable github_pat_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\"}", "exit": 1} + publisher.respond(reviews, fault, [{"state": "APPROVED", "commit_id": HEAD, "user": {"login": "trusted-publisher"}, "body": f"\nreview: **approve**"}] if error == "recover" else fault) elif error == "head": publisher.respond_pr_view(pr_json(), pr_json(headRefOid="b" * 40)) elif error == "publication": - publisher.respond(f"api repos/{REPO}/statuses/{HEAD}", {}, - {"stdout": "", "exit": 1, "stderr": "invalid description (HTTP 422)"}) + publisher.respond(f"api repos/{REPO}/statuses/{HEAD}", {}, {"stdout": "", "exit": 1, "stderr": "invalid description (HTTP 422)"}) publisher.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", [{"context": "other"}]) else: monkeypatch.setenv("GITHUB_REPOSITORY", "other/repo") - with pytest.raises((github.GhError, hosted.LoopZeroError), match=(r"method=GET endpoint=/repos/acme/widgets/pulls/7/reviews status=503 request_id=GHREQ-8774 message=Service unavailable \[REDACTED\]" if error == "api" else None)) as raised: - hosted.main() - if error == "publication": - assert "invalid description (HTTP 422)" in str(raised.value) - statuses = [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] - assert statuses == ([] if error == "config" else ["pending", "pending"] - if error == "publication" else ["pending", "failure"]) + if error in {"api", "recover"}: + assert hosted.main() == 0 and sleeps == [5] + assert ("method=GET endpoint=/repos/acme/widgets/pulls/7/reviews status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error == "api") + else: + with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): + hosted.main() + states = {"config": [], "head": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} + assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == states.get(error, ["pending", "pending"]) @pytest.mark.parametrize("case,error,message", [ @@ -174,15 +175,15 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, er ("race", CandidateRaceError, "metadata changed"), ("malformed", CandidateError, "invalid payload"), ("head", hosted.LoopZeroError, "head changed"), ("publisher", CandidateError, "not open"), - ("interrupt", KeyboardInterrupt, ""), + ("interrupt", KeyboardInterrupt, ""), ("api", None, ""), ("manual", hosted.LoopZeroError, "pull_request_target creation"), ("metadata", None, ""), ("stale", hosted.LoopZeroError, "head is no longer current"), ("untrusted", CandidateError, "head event was not sent"), ]) def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatch, case, error, message): event = candidate_event() - event["action"] = "edited" if case == "metadata" else event["action"] - event["sender"]["id"] = 1 if case == "untrusted" else event["sender"]["id"] + event["action"], event["sender"]["id"] = ( + "edited" if case == "metadata" else event["action"], 1 if case == "untrusted" else event["sender"]["id"]) values = candidate_payloads(event) if case in {"valid", "hold"}: gh = FakeGh(fake_bin, tmp_path) @@ -201,11 +202,11 @@ def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatc values["/repos/owner/repo/pulls/900"]["head"]["sha"] = "d" * 40 if case == "malformed": values["/repos/owner/repo/pulls/101"] = [] - (event_path := tmp_path / "event.json").write_text(json.dumps(event)) + (tmp_path / "event.json").write_text(json.dumps(event)) (tmp_path / "workflow.toml").write_text('[repo]\nname="owner/repo"\nbase="main"\n[delivery]\nreview_publishers=["trusted-publisher"]\n') monkeypatch.chdir(tmp_path) monkeypatch.setenv("GITHUB_REPOSITORY", "owner/repo") - monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path)) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(tmp_path / "event.json")) attempts, sleeps = [], [] def api_get(path): @@ -227,15 +228,14 @@ def publish(*args): if args[3] == "failure" and case == "publisher": raise RuntimeError("publication details must not replace attestation error") monkeypatch.setattr(github, "commit_status", publish) - evaluated = [] - real_evaluate = hosted.eligibility.evaluate + evaluated, real_evaluate = [], hosted.eligibility.evaluate def evaluate(repo, number, head, base, publishers): evaluated.append((repo, number, head, base, publishers)) if case in {"valid", "hold"}: return real_evaluate(repo, number, head, base, publishers) - if case == "interrupt": - raise KeyboardInterrupt() + if fault := {"interrupt": KeyboardInterrupt(), "api": github.GhUnavailable(("gh",), "HTTP 503")}.get(case): + raise fault reasons = (github.MISSING_REVIEW_REASON,) if case == "policy" else () return github.Readiness(not reasons, reasons) if case not in {"valid", "hold"}: @@ -248,7 +248,7 @@ def evaluate(repo, number, head, base, publishers): hosted.main() else: assert hosted.main() == 0 - terminal = [] if case in {"manual", "metadata", "stale", "interrupt"} else ["failure"] + terminal = [] if case in {"manual", "metadata", "stale", "interrupt", "api"} else ["failure"] expected = [] if case in {"manual", "metadata", "stale"} else ["pending", *terminal] assert case != "race" or (len(attempts) == 3 and sleeps == [2, 2] and len(evaluated) == 6) if case == "valid": From 0c68daf89197460d9cc4a772712714ca7a716bc5 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:41:38 +0100 Subject: [PATCH 07/11] Keep hosted refresh failures observable before pending publication Architecture-Review: unchanged; evidence and publication failures remain distinguishable within the existing hosted trust boundary. Co-Authored-By: Codex --- src/loopzero/candidate.py | 15 ++++++++++++--- src/loopzero/github.py | 6 +----- src/loopzero/hosted.py | 38 +++++++++++++++++++++++--------------- tests/test_hosted.py | 16 ++++++++-------- 4 files changed, 44 insertions(+), 31 deletions(-) diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index 8edf4afc..673842e0 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -289,6 +289,15 @@ def _attest_source( return source_sha +def _require_git_exit(operation: str, returncode: int) -> None: + if operation == "fetch" and returncode: + from loopzero import github + + raise github.GhUnavailable(("git", "fetch"), "GitHub objects unavailable") + _require(returncode == 0, f"git {operation} exited {returncode}: objects unavailable, " + "resource bound hit, or integration conflict") + + @contextlib.contextmanager def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: """Run bounded Git commands on fetched objects in an isolated bare repository.""" @@ -298,6 +307,8 @@ def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: if not token: try: token = github.auth_token() + except github.GhUnavailable: + raise except github.GhError: raise CandidateError("GitHub fetch authentication unavailable") from None _require(bool(token), "GitHub fetch authentication unavailable") @@ -341,9 +352,7 @@ def store_size() -> int: # Git renames temporaries: skip files that vanish _require(time.monotonic() < deadline, "Git time bound exceeded") with contextlib.suppress(subprocess.TimeoutExpired): process.wait(timeout=0.02) - _require(process.returncode == 0, - f"git {args[0]} exited {process.returncode}: objects unavailable, " - "resource bound hit, or integration conflict") + _require_git_exit(args[0], process.returncode) _require(store_size() <= _TREE_BYTES, "Git object/size bound exceeded") output.seek(0) result = output.read(_TREE_OUTPUT + 1) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 458bcf57..70b7f128 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -325,10 +325,6 @@ def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> boo or bool(re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE))) -def _retry_delays(scope: tuple[float, str | None, bool] | None, diagnostic: bool) -> tuple: - return (None,) if scope and not scope[2] else (*(RETRY_DELAYS[:1] if diagnostic else RETRY_DELAYS), None) - - def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str: if (using_app and len(args) > 1 and args[0] == "api" and re.fullmatch(r"repos/[^/]+/[^/]+/pulls\?.+", args[1]) @@ -350,7 +346,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, read_only = _read_only(args) retryable = read_only or retry_idempotent scope = _read_scope.get() if read_only else None - delays = _retry_delays(scope, diagnostic_api) + delays = ((RETRY_DELAYS[0], None) if scope[2] else (None,)) if scope else (*RETRY_DELAYS, None) for delay in delays: selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token try: diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index e257ae5b..0f39becf 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -37,11 +37,25 @@ def main() -> int: print(exc, file=sys.stderr) return 1 try: - with github.api_error_diagnostics(): + with github.api_error_diagnostics(), github.bounded_reads(float("inf"), token=None, retry=True): return _run(cfg) except (github.GhUnavailable, github.ProcTimeout) as exc: - print(f"Eligibility unconfirmed: GitHub evidence unavailable ({exc})", file=sys.stderr) - return 0 + print(f"Eligibility unconfirmed before pending status publication: {exc}", file=sys.stderr) + return 1 + + +def _candidate_event(event: dict, head: str) -> bool: + event_pr = event.get("pull_request") + if not isinstance(event_pr, dict): + raise LoopZeroError("candidate eligibility requires a pull_request_target " + "creation or head-update event") + if event.get("action") not in {"opened", "synchronize"}: + print("ignored candidate metadata event") + return False + event_head = event_pr.get("head") + if not isinstance(event_head, dict) or event_head.get("sha") != head: + raise LoopZeroError("candidate event head is no longer current") + return True def _run(cfg: Config) -> int: @@ -55,17 +69,8 @@ def _run(cfg: Config) -> int: or pr["user"]["login"] == "mergify[bot]") if not candidate and pr.get("merged") is True: return 0 # A landed source needs no new verdict; a late refresh must not turn it red. - if candidate: - event_pr = event.get("pull_request") - if not isinstance(event_pr, dict): - raise LoopZeroError("candidate eligibility requires a pull_request_target " - "creation or head-update event") - if event.get("action") not in {"opened", "synchronize"}: - print("ignored candidate metadata event") - return 0 - event_head = event_pr.get("head") - if not isinstance(event_head, dict) or event_head.get("sha") != head: - raise LoopZeroError("candidate event head is no longer current") + if candidate and not _candidate_event(event, head): + return 0 def publish(state: str, message: str) -> None: github.commit_status(cfg.repo, head, eligibility.CONTEXT, state, message[:140]) publish("pending", "Refreshing live source review evidence") @@ -93,6 +98,9 @@ def policy(source_number: int, source: dict) -> None: if not candidate and not ready and result.reasons == (github.MISSING_REVIEW_REASON,): message = "Awaiting trusted review of current source head" state = "pending" + except (github.GhUnavailable, github.ProcTimeout) as exc: + print(f"Eligibility pending: evidence unavailable ({exc})", file=sys.stderr) + return 0 except Exception as exc: _mark_refresh_failed(publish, exc) raise @@ -115,7 +123,7 @@ def _publish_verdict(repo: str, head: str, state: str, description: str) -> None def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None: - if not isinstance(exc, (github.GhUnavailable, github.ProcTimeout, github.StatusLimitReached)): + if not isinstance(exc, github.StatusLimitReached): with suppress(Exception): publish("failure", "Eligibility refresh failed; inspect workflow logs") diff --git a/tests/test_hosted.py b/tests/test_hosted.py index 1b0d5306..e781cfdc 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -143,14 +143,14 @@ def lose_reply(repo, head, context, value, description): assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == ["pending", state] -@pytest.mark.parametrize("error", ["api", "recover", "head", "publication", "config"]) +@pytest.mark.parametrize("error", ["api", "recover", "head", "publication", "config", "before"]) def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, capsys, error): sleeps = [] monkeypatch.setattr(github, "_retry_sleep", sleeps.append) - reviews = f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1" - if error in {"api", "recover"}: + endpoint = f"api repos/{REPO}/pulls/7" + ("" if error == "before" else "/reviews?per_page=100&page=1") + if error in {"api", "recover", "before"}: fault = {"stdout": "HTTP/2.0 503 Service Unavailable\r\nX-GitHub-Request-Id: GHREQ-8774\r\n\r\n{\"message\":\"Service unavailable github_pat_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\"}", "exit": 1} - publisher.respond(reviews, fault, [{"state": "APPROVED", "commit_id": HEAD, "user": {"login": "trusted-publisher"}, "body": f"\nreview: **approve**"}] if error == "recover" else fault) + publisher.respond(endpoint, fault, [{"state": "APPROVED", "commit_id": HEAD, "user": {"login": "trusted-publisher"}, "body": f"\nreview: **approve**"}] if error == "recover" else fault) elif error == "head": publisher.respond_pr_view(pr_json(), pr_json(headRefOid="b" * 40)) elif error == "publication": @@ -158,13 +158,13 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, ca publisher.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", [{"context": "other"}]) else: monkeypatch.setenv("GITHUB_REPOSITORY", "other/repo") - if error in {"api", "recover"}: - assert hosted.main() == 0 and sleeps == [5] - assert ("method=GET endpoint=/repos/acme/widgets/pulls/7/reviews status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error == "api") + if error in {"api", "recover", "before"}: + assert hosted.main() == (1 if error == "before" else 0) and sleeps == [5] + assert ("status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error != "recover") else: with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): hosted.main() - states = {"config": [], "head": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} + states = {"before": [], "config": [], "head": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == states.get(error, ["pending", "pending"]) From b945542e6081be09088d2a35f8df6a7031cc840d Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:43:54 +0100 Subject: [PATCH 08/11] Preserve genuine missing-object failures during candidate fetch Architecture-Review: unchanged; transient fetch diagnostics remain inside the existing isolated checkout. Co-Authored-By: Codex --- src/loopzero/candidate.py | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index 673842e0..ed75999b 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -18,7 +18,7 @@ import time from collections.abc import Callable, Iterator from pathlib import Path -from typing import Any +from typing import Any, BinaryIO MERGIFY_APP_ID = 10562 MERGIFY_APP_OWNER = "Mergifyio" @@ -289,18 +289,18 @@ def _attest_source( return source_sha -def _require_git_exit(operation: str, returncode: int) -> None: +def _require_git_exit(operation: str, returncode: int, output: BinaryIO) -> None: if operation == "fetch" and returncode: from loopzero import github - raise github.GhUnavailable(("git", "fetch"), "GitHub objects unavailable") + output.seek(0) + if github._transient_error(output.read(_TREE_OUTPUT).decode(errors="replace"), False): + raise github.GhUnavailable(("git", "fetch"), "GitHub objects temporarily unavailable") _require(returncode == 0, f"git {operation} exited {returncode}: objects unavailable, " "resource bound hit, or integration conflict") -@contextlib.contextmanager -def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: - """Run bounded Git commands on fetched objects in an isolated bare repository.""" +def _fetch_token() -> str: from loopzero import github token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") @@ -312,6 +312,13 @@ def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: except github.GhError: raise CandidateError("GitHub fetch authentication unavailable") from None _require(bool(token), "GitHub fetch authentication unavailable") + return token + + +@contextlib.contextmanager +def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: + """Run bounded Git commands on fetched objects in an isolated bare repository.""" + token = _fetch_token() with tempfile.TemporaryDirectory(prefix="loopzero-candidate-") as directory: root = Path(directory) env = { @@ -335,7 +342,8 @@ def git(*args: str, command_env: dict[str, str] = env) -> str: [sys.executable, "-I", "-S", "-c", _LIMITED_GIT, str(_TREE_BYTES), "git", "-c", "core.hooksPath=/dev/null", "-c", "gc.auto=0", "-c", "maintenance.auto=false", *args], cwd=root, env=command_env, - stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.DEVNULL, + stdin=subprocess.DEVNULL, stdout=output, + stderr=output if args[0] == "fetch" else subprocess.DEVNULL, start_new_session=True, ) def store_size() -> int: # Git renames temporaries: skip files that vanish @@ -352,7 +360,7 @@ def store_size() -> int: # Git renames temporaries: skip files that vanish _require(time.monotonic() < deadline, "Git time bound exceeded") with contextlib.suppress(subprocess.TimeoutExpired): process.wait(timeout=0.02) - _require_git_exit(args[0], process.returncode) + _require_git_exit(args[0], process.returncode, output) _require(store_size() <= _TREE_BYTES, "Git object/size bound exceeded") output.seek(0) result = output.read(_TREE_OUTPUT + 1) From db8a6950b5cdb7ffa9e3c77aae44198d3d1e0280 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:50:05 +0100 Subject: [PATCH 09/11] Recognize HTTP outages in Git fetch diagnostics Architecture-Review: unchanged; hosted eligibility still requires verified Git objects before accepting inherited evidence. Co-Authored-By: Codex --- src/loopzero/candidate.py | 3 ++- tests/test_candidate.py | 30 +++++++++++++++--------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index ed75999b..e202c0fc 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -294,7 +294,8 @@ def _require_git_exit(operation: str, returncode: int, output: BinaryIO) -> None from loopzero import github output.seek(0) - if github._transient_error(output.read(_TREE_OUTPUT).decode(errors="replace"), False): + diagnostic = output.read(_TREE_OUTPUT).decode(errors="replace") + if github._transient_error(diagnostic, False) or re.search(r"returned error: (?:429|5\d\d)", diagnostic): raise github.GhUnavailable(("git", "fetch"), "GitHub objects temporarily unavailable") _require(returncode == 0, f"git {operation} exited {returncode}: objects unavailable, " "resource bound hit, or integration conflict") diff --git a/tests/test_candidate.py b/tests/test_candidate.py index 28dfdc6e..b630962b 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -9,6 +9,7 @@ from __future__ import annotations import base64 +from contextlib import nullcontext import subprocess from copy import deepcopy from importlib import import_module @@ -17,7 +18,7 @@ import pytest -from loopzero import candidate +from loopzero import candidate, github from loopzero.candidate import CandidateError, CandidateRaceError, attest_candidate from loopzero.types import LoopZeroError @@ -684,18 +685,16 @@ def run(): assert clock[0] == {"closed": 2, "ambiguous": 90, "slow": 100 * (1 + second), "oversleep": 100}[stop] -@pytest.mark.parametrize("exceeds_bound", [False, True]) -def test_fetched_git_waits_for_exit_or_resumes_size_checks(monkeypatch, exceeds_bound): - waits = [] - killed = [] - +@pytest.mark.parametrize("outcome", ["normal", "bound", "fetch"]) +def test_fetched_git_waits_for_exit_or_resumes_size_checks(monkeypatch, outcome): + waits, killed = [], [] class Child: pid = 123 - returncode = 0 - def __init__(self, argv, cwd, **kwargs): - self.root = cwd - self.running = "test-command" in argv + self.root, self.running = cwd, "test-command" in argv + self.returncode = 128 if outcome == "fetch" and "fetch" in argv else 0 + if self.returncode: + kwargs["stderr"].write(b"fatal: The requested URL returned error: 503") def poll(self): return None if self.running else self.returncode @@ -703,7 +702,7 @@ def poll(self): def wait(self, timeout=None): if self.running: waits.append(timeout) - if timeout is not None and exceeds_bound: + if timeout is not None and outcome == "bound": (self.root / "oversized").write_bytes(b"x" * 65) raise subprocess.TimeoutExpired("test-command", timeout) self.running = False @@ -715,12 +714,13 @@ def wait(self, timeout=None): monkeypatch.setattr(candidate.os, "killpg", lambda pid, sig: killed.append((pid, sig))) monkeypatch.setattr(candidate.time, "sleep", lambda _: pytest.fail("used a fixed delay")) - with candidate.fetched_git("owner/repo", []) as git: - if exceeds_bound: + error = pytest.raises(github.GhUnavailable, match="temporarily unavailable") if outcome == "fetch" else nullcontext() + with error, candidate.fetched_git("owner/repo", []) as git: + if outcome == "bound": with pytest.raises(CandidateError, match="Git object/size bound exceeded"): git("test-command") else: assert git("test-command") == "" - assert waits == ([0.02, None] if exceeds_bound else [0.02]) - assert killed == ([(123, candidate.signal.SIGKILL)] if exceeds_bound else []) + assert waits == {"bound": [0.02, None], "normal": [0.02], "fetch": []}[outcome] + assert killed == ([(123, candidate.signal.SIGKILL)] if outcome == "bound" else []) From df0ca9b396ea6fe333dfea31428c5cf0ad0d09ca Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:56:56 +0100 Subject: [PATCH 10/11] Remove redundant subprocess option handling Architecture-Review: unchanged; subprocess I/O and environment semantics stay the same. Co-Authored-By: Codex --- src/loopzero/_proc.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index 3bfaf9a0..8ac581fa 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -100,8 +100,7 @@ def build_env( ) -> dict[str, str]: """Copy only allowlisted variables from the current environment, then apply extras.""" env = {key: os.environ[key] for key in env_allowlist if key in os.environ} - if extra_env: - env.update(extra_env) + env.update(extra_env or {}) return env @@ -138,7 +137,6 @@ def run( stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT if merge_output else subprocess.PIPE, - text=not preserve_newlines, encoding=None if preserve_newlines else encoding, errors=None if preserve_newlines else "replace", start_new_session=os.name == "posix", From 6c65b6aac76e71321dda5f9286ee963b4c18d510 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:00:14 +0100 Subject: [PATCH 11/11] Keep retry timing scoped to its follow-up change Architecture-Review: unchanged; the evidence outcome changes while the existing retry and wait behavior remains in force until #1502. Co-Authored-By: Codex --- src/loopzero/github.py | 2 +- src/loopzero/hosted.py | 2 +- tests/test_hosted.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 70b7f128..7d90c5a4 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -346,7 +346,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, read_only = _read_only(args) retryable = read_only or retry_idempotent scope = _read_scope.get() if read_only else None - delays = ((RETRY_DELAYS[0], None) if scope[2] else (None,)) if scope else (*RETRY_DELAYS, None) + delays = (None,) if scope and not scope[2] else (*RETRY_DELAYS, None) for delay in delays: selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token try: diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 0f39becf..2f723a65 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -37,7 +37,7 @@ def main() -> int: print(exc, file=sys.stderr) return 1 try: - with github.api_error_diagnostics(), github.bounded_reads(float("inf"), token=None, retry=True): + with github.api_error_diagnostics(): return _run(cfg) except (github.GhUnavailable, github.ProcTimeout) as exc: print(f"Eligibility unconfirmed before pending status publication: {exc}", file=sys.stderr) diff --git a/tests/test_hosted.py b/tests/test_hosted.py index e781cfdc..ec23f866 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -159,7 +159,7 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, ca else: monkeypatch.setenv("GITHUB_REPOSITORY", "other/repo") if error in {"api", "recover", "before"}: - assert hosted.main() == (1 if error == "before" else 0) and sleeps == [5] + assert hosted.main() == (1 if error == "before" else 0) and sleeps == ([5] if error == "recover" else list(github.RETRY_DELAYS)) assert ("status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error != "recover") else: with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None):