Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
14 changes: 10 additions & 4 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,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.

Expand Down
56 changes: 56 additions & 0 deletions src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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 = [
Expand All @@ -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",
Expand Down
58 changes: 29 additions & 29 deletions tests/test_candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,18 @@
import base64
import subprocess
from copy import deepcopy
from functools import partial
from importlib import import_module
from itertools import cycle
from os import environ
from shutil import copytree

import pytest

from loopzero import candidate
from loopzero.candidate import CandidateError, CandidateRaceError, attest_candidate
from loopzero.types import LoopZeroError
from tests.conftest import commit_file, git as isolated_git


@pytest.fixture(autouse=True)
Expand Down Expand Up @@ -205,38 +208,36 @@ def block(number: int, _source: dict) -> None:
run_attestation(github_payloads=values, source_policy=block)


@pytest.fixture(scope="session")
def candidate_seed(tmp_path_factory):
remote = tmp_path_factory.mktemp("candidate-seed")
git = partial(isolated_git, remote)
git("init", "-b", "main")
commit_file(remote, "base", "base\n", "base")
for branch, content in (("parent", "H1\n"), ("source", "reviewed\n")):
git("checkout", "-b", branch, "main")
commit_file(remote, branch, content, branch)
git("checkout", "-b", "candidate", "main")
git("merge", "--no-ff", "parent", "-m", "parent integration")
git("merge", "--no-ff", "source", "-m", "source integration")
git("checkout", "main")
git("merge", "--squash", "parent")
git("commit", "-m", "squashed parent")
return remote, *git("rev-parse", "source^", "parent", "source", "candidate", "main").split()


@pytest.fixture
def tree_candidate(tmp_path, monkeypatch):
remote = tmp_path / "remote"
remote.mkdir()
def tree_candidate(candidate_seed, tmp_path, monkeypatch):
seed, base, parent, source, candidate_sha, main = candidate_seed
remote = copytree(seed, tmp_path / "remote")

def git(*args):
return subprocess.run(["git", *args], cwd=remote, check=True, capture_output=True,
text=True).stdout.strip()

git("init", "-b", "main")
git("config", "user.name", "Test")
git("config", "user.email", "test@example.org")
return isolated_git(remote, *args).strip()

def commit(name, content):
(remote / name).write_text(content)
git("add", ".")
git("commit", "-m", name)
commit_file(remote, name, content, name)
return git("rev-parse", "HEAD")

base = commit("base", "base\n")
git("checkout", "-b", "parent")
parent = commit("parent", "H1\n")
git("checkout", "-b", "source", base)
source = commit("source", "reviewed\n")
git("checkout", "-b", "candidate", base)
git("merge", "--no-ff", parent, "-m", "parent integration")
git("merge", "--no-ff", source, "-m", "source integration")
candidate_sha = git("rev-parse", "HEAD")
git("checkout", "main")
git("merge", "--squash", parent)
git("commit", "-m", "squashed parent")
main = git("rev-parse", "HEAD")
popen = subprocess.Popen

def isolated_fetch(argv, **kwargs):
Expand Down Expand Up @@ -281,10 +282,9 @@ def attest(
reads = cycle([main_head, main_after or main_head])

def get(path):
if path.endswith("/git/ref/heads/main"):
sha = next(reads)
return {"object": {"sha": sha}} if sha else {}
return deepcopy(values[path])
if not path.endswith("/git/ref/heads/main"):
return deepcopy(values[path])
return {"object": {"sha": sha}} if (sha := next(reads)) else {}

return run(candidate_event, github_get=get, mergify_status=lambda *_: deepcopy(queue),
source_policy=policy)
Expand Down
8 changes: 4 additions & 4 deletions tests/test_codex_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
fake_bwrap = test_runners.fake_bwrap
gh = test_cli.gh
APPROVE = test_runners.APPROVE
BYTE_LIMIT_REVIEW = test_runners._native_codex_result("a" * 40)


@pytest.fixture
Expand Down Expand Up @@ -595,14 +596,13 @@ def test_entire_leading_block_budget_includes_adjudication(native, monkeypatch):
["\n", "\r\n", "\r", "\v", "\f", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029"],
)
@pytest.mark.parametrize("overflow", [0, 1, 2])
def test_raw_leading_utf8_span_at_limit_and_overflow(native, separator, overflow):
result = native[0]()
def test_raw_leading_utf8_span_at_limit_and_overflow(separator, overflow):
result = BYTE_LIMIT_REVIEW
marker = cli.review_marker(result.head, result.kind)
header = runners.encode_codex_evidence(runners.codex_evidence(result))
adjudication = "<!-- loopzero:adjudication v=1 replaces=1 target=" + result.head + " -->"
span = separator.join((marker, header, adjudication))
padding = 8192 + overflow - len(span.encode("utf-8"))
padded = marker[:-3] + " " * padding + marker[-3:]
padded = marker[:-3] + " " * (8192 + overflow - len(span.encode("utf-8"))) + marker[-3:]
span = separator.join((padded, header, adjudication))
assert len(span.encode("utf-8")) == 8192 + overflow
rendered = span + separator + "**approve**"
Expand Down
80 changes: 80 additions & 0 deletions tests/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand Down
Loading