From fda19707e348d3360d240df67201223b8e53d7ef Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:58:32 +0100 Subject: [PATCH 01/10] Keep PR content from hiding changed code from the reviewer The reviewer diff now treats every file as text and ignores attributes and diff drivers the PR could set, so a PR-added -diff/binary attribute or a NUL byte no longer reduces a changed text file to "Binary files differ". A file block that is not UTF-8 is replaced by its path and size. Chunked review summarizes a file as deleted only when git's header says so, not when its added lines contain the header text. Closes #1101 Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 5 ++++- src/loopzero/runners.py | 3 ++- src/loopzero/worktree.py | 32 +++++++++++++++++++++++++++++++- tests/test_worktree.py | 37 +++++++++++++++++++++++++++++++++++++ 4 files changed, 74 insertions(+), 3 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 62aa7208..de4b3999 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -179,7 +179,10 @@ The R3 runner separates fixed reviewer policy from supplied material inside the existing runner adapters. A fixed ASCII paragraph and validated scope enter Claude's append-system-prompt or Codex's developer_instructions override; commit identity stays in the JSON material header. Explicit UTF-8 stdin carries -that header, a newline and the exact raw diff without trimming task or diff text. +that header, a newline and the raw diff without trimming task or diff text. Git +diffs every file as text, ignoring attributes and diff drivers the PR could set; +a file block that is not UTF-8 is replaced by its path and size. Chunked review +summarizes only files whose git header reports a deletion. The runner probes the selected Codex binary with `--version` and records its stdout in runner provenance and the saved review receipt. A failed probe uses RunnerBadOutput and existing family fallback before model input. Successful diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index d03855ec..989aa29f 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -1394,7 +1394,8 @@ def split_diff(diff: str, budget: int) -> list[str]: def _summarize_deleted(block: str) -> str: - if "\ndeleted file mode " not in block and "\n+++ /dev/null" not in block: + # Judge deletion from git's header only; hunk lines are the PR's own text. + if "\ndeleted file mode " not in block.partition("\n@@")[0]: return block match = re.match(r"diff --git a/(.+?) b/(.+?)\n", block) path = match.group(2) if match else "(unknown file)" diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index f4a82f3a..6a7b316e 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -2,6 +2,7 @@ from __future__ import annotations +import contextlib import errno import re import stat @@ -244,7 +245,36 @@ def is_dirty(wt: Path) -> bool: def diff_since(wt: Path, sha: str) -> str: - return _git(Path(wt), "diff", "--no-color", sha, "HEAD") + """The reviewer's diff from ``sha`` to HEAD, which the reviewed files cannot hide. + + Every file is diffed as text, whatever its attributes or NUL bytes, without diff + drivers. A file block that is not UTF-8 is replaced by its path and size. + """ + wt = Path(wt) + argv = ("git", "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--text", sha, "HEAD") + # Latin-1 keeps every byte, so each file block can be decoded strictly below. + done = run(list(argv), cwd=wt, env_allowlist=GIT_ENV, timeout=120, encoding="latin-1") + if done.exit_code != 0: + raise GitError(argv, done.stderr or done.stdout) + blocks = re.split(r"(?m)^(?=diff --git )", done.stdout.strip()) + return "".join(_decoded_block(wt, sha, block) for block in blocks) + + +def _decoded_block(wt: Path, sha: str, block: str) -> str: + raw = block.encode("latin-1") + try: + return raw.decode("utf-8") + except UnicodeDecodeError: + pass + header = raw.partition(b"\n@@")[0].decode("utf-8", "replace").splitlines() + new = next((line[6:] for line in header if line.startswith("+++ b/")), None) + old = next((line[6:] for line in header if line.startswith("--- a/")), None) + path, rev = (new, "HEAD") if new else (old, sha) + size = "size unknown" + if path: + with contextlib.suppress(GitError): + size = f"{_git(wt, 'cat-file', '-s', f'{rev}:{path}')} bytes at {rev}" + return f"{header[0]}\n{path or '(unknown path)'}: not UTF-8 text, content not shown ({size})\n" def merges_since(wt: Path, sha: str) -> list[str]: diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 2caef7c2..a0d2a9b4 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -8,6 +8,7 @@ import pytest from loopzero import worktree +from loopzero.runners import split_diff from tests.conftest import git @@ -183,6 +184,42 @@ def test_start_reports_git_failure_with_command(repo: Path) -> None: assert info.value.tail +def test_diff_since_shows_changes_the_reviewed_files_try_to_hide(git_repo: Path) -> None: + for name in ("attr.py", "nul.py"): + (git_repo / name).write_text("old = 1\n") + git(git_repo, "add", "-A") + git(git_repo, "commit", "-q", "-m", "base") + base = git(git_repo, "rev-parse", "HEAD").strip() + (git_repo / ".gitattributes").write_text("attr.py -diff\nnul.py binary\n") + (git_repo / "attr.py").write_text("new = 'attr hunk'\n") + (git_repo / "nul.py").write_bytes(b"new = 'nul hunk'\x00\n") + (git_repo / "image.png").write_bytes(b"\x89PNG\r\n\x1a\n\x00\xff\xfe") + git(git_repo, "add", "-A") + git(git_repo, "commit", "-q", "-m", "head") + + diff = worktree.diff_since(git_repo, base) + + assert "Binary files" not in diff + assert "+new = 'attr hunk'" in diff and "+new = 'nul hunk'\x00" in diff + assert "image.png: not UTF-8 text, content not shown (11 bytes at HEAD)" in diff + + +def test_split_diff_summarizes_only_files_git_reports_deleted(git_repo: Path) -> None: + for name in ("gone.py", "padded.py"): + (git_repo / name).write_text("old = 1\n") + git(git_repo, "add", "-A") + git(git_repo, "commit", "-q", "-m", "base") + base = git(git_repo, "rev-parse", "HEAD").strip() + git(git_repo, "rm", "-q", "gone.py") + (git_repo / "padded.py").write_text("new = 'padded hunk'\n++ /dev/null\n" + "x = 0\n" * 200) + git(git_repo, "commit", "-qam", "head") + + joined = "".join(split_diff(worktree.diff_since(git_repo, base), 1_000)) + + assert "+++ /dev/null" in joined and "+new = 'padded hunk'" in joined + assert "gone.py: deleted, 1 lines" in joined and "padded.py: deleted" not in joined + + def test_dirty_head_and_diff(repo: Path) -> None: wt = worktree.start(repo, "work", "main") base = worktree.base_sha(wt) From a2830cd5b5feffeba68b65232b77cf7a7fdf541b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:19:50 +0100 Subject: [PATCH 02/10] Classify reviewer files by content and parse Git output as bytes diff_since now reads Git's output as bytes, so a bare carriage return cannot fake a file boundary, keeps it untrimmed, and decides whether to show a file from its HEAD (or deleted base) blob rather than the patch. Notices and deletion summaries keep Git's own header line, and only a whole "deleted file mode" header line marks a deletion. Refs #1101 Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 4 +- src/loopzero/runners.py | 15 +++---- src/loopzero/worktree.py | 85 +++++++++++++++++++++++++++------------- tests/test_cli.py | 2 +- tests/test_runners.py | 2 +- tests/test_worktree.py | 64 +++++++++++++++++++----------- 6 files changed, 111 insertions(+), 61 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index de4b3999..21714a61 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -181,7 +181,9 @@ enter Claude's append-system-prompt or Codex's developer_instructions override; commit identity stays in the JSON material header. Explicit UTF-8 stdin carries that header, a newline and the raw diff without trimming task or diff text. Git diffs every file as text, ignoring attributes and diff drivers the PR could set; -a file block that is not UTF-8 is replaced by its path and size. Chunked review +a file whose +HEAD content (base content when deleted) is not UTF-8 keeps only Git's header +line and its size. Chunked review summarizes only files whose git header reports a deletion. The runner probes the selected Codex binary with `--version` and records its stdout in runner provenance and the saved review receipt. A failed probe uses diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 989aa29f..468e4360 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -1394,16 +1394,13 @@ def split_diff(diff: str, budget: int) -> list[str]: def _summarize_deleted(block: str) -> str: - # Judge deletion from git's header only; hunk lines are the PR's own text. - if "\ndeleted file mode " not in block.partition("\n@@")[0]: + # Judge deletion from git's header lines only; hunk lines are the PR's own text. + header, hunks = block.partition("\n@@")[::2] + if not re.search(r"(?m)^deleted file mode [0-7]{6}$", header): return block - match = re.match(r"diff --git a/(.+?) b/(.+?)\n", block) - path = match.group(2) if match else "(unknown file)" - deleted = sum( - 1 for line in block.splitlines() - if line.startswith("-") and not line.startswith("---") - ) - return f"diff --git a/{path} b/{path}\n{path}: deleted, {deleted} lines\n" + first = header.split("\n", 1)[0] + deleted = sum(1 for line in hunks.split("\n") if line.startswith("-")) + return f"{first}\ndeleted file, {deleted} lines\n" def _split_bytes(text: str, budget: int) -> list[str]: diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 6a7b316e..250ec1a1 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -2,15 +2,15 @@ from __future__ import annotations -import contextlib import errno +import subprocess import re import stat import tempfile from pathlib import Path from uuid import uuid4 -from loopzero._proc import run +from loopzero._proc import build_env, run GIT_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK") EXCLUDES = (".worktrees/", ".loopzero/") @@ -244,37 +244,68 @@ def is_dirty(wt: Path) -> bool: return bool(_git(Path(wt), "status", "--porcelain", "--untracked-files=all")) +def _git_bytes(wt: Path, *args: str, stdin: bytes | None = None) -> bytes: + """Git output as bytes: text mode would turn a bare CR into a line break.""" + argv = ("git", *args) + try: + done = subprocess.run(argv, cwd=wt, env=build_env(GIT_ENV), input=stdin, + capture_output=True, timeout=120, check=False) + except subprocess.TimeoutExpired as exc: + raise GitError(argv, "timed out") from exc + if done.returncode != 0: + raise GitError(argv, done.stderr.decode(errors="replace")) + return done.stdout + + def diff_since(wt: Path, sha: str) -> str: """The reviewer's diff from ``sha`` to HEAD, which the reviewed files cannot hide. Every file is diffed as text, whatever its attributes or NUL bytes, without diff - drivers. A file block that is not UTF-8 is replaced by its path and size. + drivers. A file whose content is not UTF-8 is replaced by its header and size. """ wt = Path(wt) - argv = ("git", "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--text", sha, "HEAD") - # Latin-1 keeps every byte, so each file block can be decoded strictly below. - done = run(list(argv), cwd=wt, env_allowlist=GIT_ENV, timeout=120, encoding="latin-1") - if done.exit_code != 0: - raise GitError(argv, done.stderr or done.stdout) - blocks = re.split(r"(?m)^(?=diff --git )", done.stdout.strip()) - return "".join(_decoded_block(wt, sha, block) for block in blocks) - - -def _decoded_block(wt: Path, sha: str, block: str) -> str: - raw = block.encode("latin-1") - try: - return raw.decode("utf-8") - except UnicodeDecodeError: - pass - header = raw.partition(b"\n@@")[0].decode("utf-8", "replace").splitlines() - new = next((line[6:] for line in header if line.startswith("+++ b/")), None) - old = next((line[6:] for line in header if line.startswith("--- a/")), None) - path, rev = (new, "HEAD") if new else (old, sha) - size = "size unknown" - if path: - with contextlib.suppress(GitError): - size = f"{_git(wt, 'cat-file', '-s', f'{rev}:{path}')} bytes at {rev}" - return f"{header[0]}\n{path or '(unknown path)'}: not UTF-8 text, content not shown ({size})\n" + patch = _git_bytes(wt, "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--text", sha, "HEAD") + blocks = [block for block in re.split(rb"(?m)^(?=diff --git )", patch) if block] + # Classify each file by its own content (HEAD, or the base when deleted), not its patch. + sides = [_content_side(block) for block in blocks] + blobs = [side[0] for side in sides if side] + sizes = _non_utf8_sizes(wt, blobs) if blobs else {} + parts = [] + for block, side in zip(blocks, sides, strict=True): + if side and side[0] in sizes: + first = block.partition(b"\n")[0].decode("utf-8", "replace") + parts.append(f"{first}\ncontent not shown: not UTF-8 text, " + f"{sizes[side[0]]} bytes at {side[1]}\n") + else: + parts.append(block.decode("utf-8", "replace")) + return "".join(parts).removesuffix("\n") # only the final newline; line content stays + + +def _content_side(block: bytes) -> tuple[str, str] | None: + index = re.search(rb"(?m)^index ([0-9a-f]+)\.\.([0-9a-f]+)", block.partition(b"\n@@")[0]) + if not index: + return None + old, new = (side.decode() for side in index.groups()) + return (old, "the reviewed base") if not new.strip("0") else (new, "HEAD") + + +def _non_utf8_sizes(wt: Path, blobs: list[str]) -> dict[str, int]: + """Sizes of the given blobs whose content is not UTF-8, read in one Git call.""" + out = _git_bytes(wt, "cat-file", "--batch", stdin="".join(f"{b}\n" for b in blobs).encode()) + sizes, offset = {}, 0 + for blob in blobs: + start = out.index(b"\n", offset) + 1 + fields = out[offset:start].split() + if len(fields) != 3 or fields[1] != b"blob": # missing, or a submodule commit + offset = start + continue + size = int(fields[2]) + try: + out[start:start + size].decode("utf-8") + except UnicodeDecodeError: + sizes[blob] = size + offset = start + size + 1 + return sizes def merges_since(wt: Path, sha: str) -> list[str]: diff --git a/tests/test_cli.py b/tests/test_cli.py index f04c0a5c..e8cb17b8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1076,7 +1076,7 @@ def test_review_primary_posts_marker(wt: Path, gh: FakeGh, fake_bin: Path, capsy expected_diff = git(wt, "diff", "--no-color", "origin/main", head).strip().encode("utf-8") git_calls.clear() code, out, err = run(capsys, "review") - assert_git_cost(git_calls, 15, 2) + assert_git_cost(git_calls, 16, 2) # one batched blob read classifies every file assert (code, err) == (5, "") # request_changes: the exit code is the verdict assert out.splitlines()[0].startswith("reviewer paths pinned to origin/main@") assert out.splitlines()[-1] + "\n" == ( diff --git a/tests/test_runners.py b/tests/test_runners.py index 9e07d096..5286e021 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -1185,7 +1185,7 @@ def test_split_diff_respects_budget_and_summarizes_deleted_file() -> None: added = "diff --git a/new.py b/new.py\n" + "+x\n" * 60 chunks = split_diff(deleted + added, 100) assert all(len(chunk.encode()) <= 100 for chunk in chunks) - assert any("gone.py: deleted, 3 lines" in chunk for chunk in chunks) + assert any("diff --git a/gone.py b/gone.py\ndeleted file, 3 lines" in chunk for chunk in chunks) # ----------------------------------------------------------------- family detection diff --git a/tests/test_worktree.py b/tests/test_worktree.py index a0d2a9b4..df0966f5 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -184,40 +184,60 @@ def test_start_reports_git_failure_with_command(repo: Path) -> None: assert info.value.tail +def _commit_files(repo: Path, files: dict[str, bytes | None]) -> str: + for name, content in files.items(): + if content is None: + git(repo, "rm", "-q", name) + else: + (repo / name).write_bytes(content) + git(repo, "add", name) + git(repo, "commit", "-q", "-m", "change") + return git(repo, "rev-parse", "HEAD").strip() + + def test_diff_since_shows_changes_the_reviewed_files_try_to_hide(git_repo: Path) -> None: - for name in ("attr.py", "nul.py"): - (git_repo / name).write_text("old = 1\n") - git(git_repo, "add", "-A") - git(git_repo, "commit", "-q", "-m", "base") - base = git(git_repo, "rev-parse", "HEAD").strip() - (git_repo / ".gitattributes").write_text("attr.py -diff\nnul.py binary\n") - (git_repo / "attr.py").write_text("new = 'attr hunk'\n") - (git_repo / "nul.py").write_bytes(b"new = 'nul hunk'\x00\n") - (git_repo / "image.png").write_bytes(b"\x89PNG\r\n\x1a\n\x00\xff\xfe") - git(git_repo, "add", "-A") - git(git_repo, "commit", "-q", "-m", "head") + base = _commit_files(git_repo, { + "attr.py": b"old = 1\n", "nul.py": b"old = 1\n", "was_latin1.txt": b"caf\xe9\n", + "far.bin": b"\xff" + b"line\n" * 40, + }) + _commit_files(git_repo, { + ".gitattributes": b"attr.py -diff\nnul.py binary\n", + "attr.py": b"new = 'attr hunk'\n", + "nul.py": b"new = 'nul hunk'\x00\n", + "image.png": b"\x89PNG\r\n\x1a\n\x00\xff\xfe", + "was_latin1.txt": "café \u00a0\n".encode(), + "far.bin": b"\xff" + b"line\n" * 39 + b"changed\n", + "deleted file mode 100644": b"\xff\xfe", + "r\u00e9sum\u00e9.bin": b"\xff", + }) diff = worktree.diff_since(git_repo, base) assert "Binary files" not in diff assert "+new = 'attr hunk'" in diff and "+new = 'nul hunk'\x00" in diff - assert "image.png: not UTF-8 text, content not shown (11 bytes at HEAD)" in diff + assert "+café \u00a0" in diff.split("\n"), "UTF-8 additions survive a non-UTF-8 old side, untrimmed" + for header, size in (("a/image.png b/image.png", 11), ("a/far.bin b/far.bin", 204), + ('"a/r\\303\\251sum\\303\\251.bin" "b/r\\303\\251sum\\303\\251.bin"', 1)): + assert f"diff --git {header}\ncontent not shown: not UTF-8 text, {size} bytes at HEAD\n" in diff + chunks = split_diff(diff, 400) + assert "diff --git a/deleted file mode 100644 b/deleted file mode 100644\ncontent not shown" in "".join(chunks) def test_split_diff_summarizes_only_files_git_reports_deleted(git_repo: Path) -> None: - for name in ("gone.py", "padded.py"): - (git_repo / name).write_text("old = 1\n") - git(git_repo, "add", "-A") - git(git_repo, "commit", "-q", "-m", "base") - base = git(git_repo, "rev-parse", "HEAD").strip() - git(git_repo, "rm", "-q", "gone.py") - (git_repo / "padded.py").write_text("new = 'padded hunk'\n++ /dev/null\n" + "x = 0\n" * 200) - git(git_repo, "commit", "-qam", "head") + base = _commit_files(git_repo, {"gone.py": b"old = 1\n", "padded.py": b"old = 1\n", + "carriage.py": b"old = 1\n"}) + _commit_files(git_repo, { + "gone.py": None, + "padded.py": b"new = 'padded hunk'\n++ /dev/null\n" + b"x = 0\n" * 200, + "carriage.py": b"new = 1 \rdiff --git a/carriage.py b/carriage.py\rdeleted file mode 100644\r" + + b"y = 0\n" * 200, + }) joined = "".join(split_diff(worktree.diff_since(git_repo, base), 1_000)) - assert "+++ /dev/null" in joined and "+new = 'padded hunk'" in joined - assert "gone.py: deleted, 1 lines" in joined and "padded.py: deleted" not in joined + assert "+++ /dev/null" in joined and "+new = 'padded hunk'" in joined and "+new = 1 \r" in joined + assert "diff --git a/gone.py b/gone.py\ndeleted file, 1 lines" in joined + assert joined.count("deleted file, ") == 1 def test_dirty_head_and_diff(repo: Path) -> None: From 3054d0b983e7be89f287b7fde5fd610ec56bcc6b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:11:25 +0100 Subject: [PATCH 03/10] Classify reviewer files by full object ID with bounded reads The reviewer diff now carries full object IDs, so classification cannot resolve an abbreviated ID as a ref name. The single cat-file batch reads each object once, consumes every payload (submodule commits included) and validates UTF-8 in bounded chunks instead of buffering whole files. Refs #1101 Co-Authored-By: Claude Opus 5.5 --- src/loopzero/worktree.py | 58 +++++++++++++++++++++++++---------- tests/test_cli.py | 4 +-- tests/test_codex_transport.py | 2 +- tests/test_worktree.py | 12 ++++++++ 4 files changed, 56 insertions(+), 20 deletions(-) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 250ec1a1..eeb59377 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -2,6 +2,7 @@ from __future__ import annotations +import codecs import errno import subprocess import re @@ -264,7 +265,8 @@ def diff_since(wt: Path, sha: str) -> str: drivers. A file whose content is not UTF-8 is replaced by its header and size. """ wt = Path(wt) - patch = _git_bytes(wt, "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--text", sha, "HEAD") + patch = _git_bytes(wt, "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--text", + "--full-index", sha, "HEAD") blocks = [block for block in re.split(rb"(?m)^(?=diff --git )", patch) if block] # Classify each file by its own content (HEAD, or the base when deleted), not its patch. sides = [_content_side(block) for block in blocks] @@ -282,32 +284,54 @@ def diff_since(wt: Path, sha: str) -> str: def _content_side(block: bytes) -> tuple[str, str] | None: - index = re.search(rb"(?m)^index ([0-9a-f]+)\.\.([0-9a-f]+)", block.partition(b"\n@@")[0]) + # Full object IDs: an abbreviated one could resolve as a ref name instead. + index = re.search(rb"(?m)^index ([0-9a-f]{40}|[0-9a-f]{64})\.\.([0-9a-f]{40}|[0-9a-f]{64})", + block.partition(b"\n@@")[0]) if not index: - return None + return None # rename or mode change only: no content changed old, new = (side.decode() for side in index.groups()) return (old, "the reviewed base") if not new.strip("0") else (new, "HEAD") def _non_utf8_sizes(wt: Path, blobs: list[str]) -> dict[str, int]: - """Sizes of the given blobs whose content is not UTF-8, read in one Git call.""" - out = _git_bytes(wt, "cat-file", "--batch", stdin="".join(f"{b}\n" for b in blobs).encode()) - sizes, offset = {}, 0 - for blob in blobs: - start = out.index(b"\n", offset) + 1 - fields = out[offset:start].split() - if len(fields) != 3 or fields[1] != b"blob": # missing, or a submodule commit - offset = start - continue - size = int(fields[2]) + """Sizes of the given blobs whose content is not UTF-8: one Git call, bounded reads.""" + argv = ("git", "cat-file", "--batch") + sizes = {} + with subprocess.Popen(argv, cwd=wt, env=build_env(GIT_ENV), stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as proc: try: - out[start:start + size].decode("utf-8") - except UnicodeDecodeError: - sizes[blob] = size - offset = start + size + 1 + for blob in dict.fromkeys(blobs): + proc.stdin.write(f"{blob}\n".encode()) + proc.stdin.flush() + fields = proc.stdout.readline().split() + if len(fields) != 3: # missing or ambiguous: no payload follows + continue + size = int(fields[2]) + utf8 = _stream_is_utf8(proc.stdout, size, argv) + proc.stdout.read(1) # each payload ends with a newline, whatever its type + if fields[1] == b"blob" and not utf8: + sizes[blob] = size + finally: + proc.stdin.close() + proc.kill() return sizes +def _stream_is_utf8(stream, size: int, argv: tuple[str, ...]) -> bool: + decoder, valid = codecs.getincrementaldecoder("utf-8")(), True + while size: + chunk = stream.read(min(size, 1 << 16)) + if not chunk: + raise GitError(argv, "object content ended early") + size -= len(chunk) + try: + decoder.decode(chunk, final=not size) + except UnicodeDecodeError: + valid = False + decoder = codecs.getincrementaldecoder("latin-1")() # keep draining, stop checking + return valid + + def merges_since(wt: Path, sha: str) -> list[str]: """First-parent merges between ``sha`` and HEAD, oldest first.""" return _git(Path(wt), "rev-list", "--first-parent", "--reverse", "--merges", f"{sha}..HEAD").split() diff --git a/tests/test_cli.py b/tests/test_cli.py index e8cb17b8..36049eda 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1073,7 +1073,7 @@ def test_review_primary_posts_marker(wt: Path, gh: FakeGh, fake_bin: Path, capsy git(wt, "branch", "-m", branch) head = prepare_review(wt, gh, fake_bin, payload=CHANGES, branch=branch) task = (wt / ".loopzero/task.md").read_text() - expected_diff = git(wt, "diff", "--no-color", "origin/main", head).strip().encode("utf-8") + expected_diff = git(wt, "diff", "--no-color", "--full-index", "origin/main", head).strip().encode("utf-8") git_calls.clear() code, out, err = run(capsys, "review") assert_git_cost(git_calls, 16, 2) # one batched blob read classifies every file @@ -1529,7 +1529,7 @@ def test_review_delta_diffs_since_primary(wt: Path, gh: FakeGh, fake_bin: Path, head = prepare_review(wt, gh, fake_bin, post_id=2, history=[ rev(first, "primary", state="CHANGES_REQUESTED", verdict="request_changes")]) task = (wt / ".loopzero/task.md").read_text() - expected_diff = git(wt, "diff", "--no-color", first, head).strip().encode("utf-8") + expected_diff = git(wt, "diff", "--no-color", "--full-index", first, head).strip().encode("utf-8") code, out, _ = run(capsys, "review") assert code == 0 and out.splitlines()[-1].startswith(f"delta review by claude on {head[:12]}: approve") header, diff = (fake_bin / "claude.stdin").read_bytes().split(b"\n", 1) diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.py index de241158..291176b2 100644 --- a/tests/test_codex_transport.py +++ b/tests/test_codex_transport.py @@ -376,7 +376,7 @@ def test_large_publication_confirmation_and_hosted_agreement(native, gh, tmp_pat publication=(repo, 7, "bot")) proof = runners.codex_evidence(result) assert proof["kind"] == "delta" and proof["calls"][0]["base"] == reviewed != merge_base - delta_diff = git(native[2], "diff", "--no-color", reviewed, head).strip().encode() + delta_diff = git(native[2], "diff", "--no-color", "--full-index", reviewed, head).strip().encode() assert proof["calls"][0]["diff_sha256"] == hashlib.sha256(delta_diff).hexdigest() head = result.head prefix = ( diff --git a/tests/test_worktree.py b/tests/test_worktree.py index df0966f5..1c26b050 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -223,6 +223,18 @@ def test_diff_since_shows_changes_the_reviewed_files_try_to_hide(git_repo: Path) assert "diff --git a/deleted file mode 100644 b/deleted file mode 100644\ncontent not shown" in "".join(chunks) +def test_diff_since_reads_past_submodule_commits_to_classify_later_files(git_repo: Path) -> None: + base = _commit_files(git_repo, {"z.bin": b"old\n"}) + # A gitlink whose commit is in the object database returns a commit payload. + git(git_repo, "update-index", "--add", "--cacheinfo", f"160000,{base},a-sub") + _commit_files(git_repo, {"z.bin": b"\xff\xfe" * 3}) + + diff = worktree.diff_since(git_repo, base) + + assert f"+Subproject commit {base}" in diff + assert "diff --git a/z.bin b/z.bin\ncontent not shown: not UTF-8 text, 6 bytes at HEAD" in diff + + def test_split_diff_summarizes_only_files_git_reports_deleted(git_repo: Path) -> None: base = _commit_files(git_repo, {"gone.py": b"old = 1\n", "padded.py": b"old = 1\n", "carriage.py": b"old = 1\n"}) From 03267eac62741a9ef20177ccfbe5765a3bcbd42a Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:47:40 +0100 Subject: [PATCH 04/10] Compact reviewer diff integrity tests Folds the submodule case into the main diff test and tightens fixtures so the test suite stays under its line cap after merging main. Refs #1101 Co-Authored-By: Claude Opus 5.5 --- tests/test_worktree.py | 66 +++++++++++++----------------------------- 1 file changed, 20 insertions(+), 46 deletions(-) diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 42c8edef..fe0b0bba 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -202,68 +202,42 @@ def _commit_files(repo: Path, files: dict[str, bytes | None]) -> str: for name, content in files.items(): if content is None: git(repo, "rm", "-q", name) - else: - (repo / name).write_bytes(content) - git(repo, "add", name) + continue + (repo / name).write_bytes(content) + git(repo, "add", name) git(repo, "commit", "-q", "-m", "change") return git(repo, "rev-parse", "HEAD").strip() def test_diff_since_shows_changes_the_reviewed_files_try_to_hide(git_repo: Path) -> None: - base = _commit_files(git_repo, { - "attr.py": b"old = 1\n", "nul.py": b"old = 1\n", "was_latin1.txt": b"caf\xe9\n", - "far.bin": b"\xff" + b"line\n" * 40, - }) + base = _commit_files(git_repo, {"attr.py": b"old\n", "nul.py": b"old\n", "was_latin1.txt": b"caf\xe9\n", + "far.bin": b"\xff" + b"line\n" * 40}) + # A gitlink whose commit is in the object database returns a commit payload first. + git(git_repo, "update-index", "--add", "--cacheinfo", f"160000,{base},a-sub") _commit_files(git_repo, { - ".gitattributes": b"attr.py -diff\nnul.py binary\n", - "attr.py": b"new = 'attr hunk'\n", - "nul.py": b"new = 'nul hunk'\x00\n", - "image.png": b"\x89PNG\r\n\x1a\n\x00\xff\xfe", - "was_latin1.txt": "café \u00a0\n".encode(), - "far.bin": b"\xff" + b"line\n" * 39 + b"changed\n", - "deleted file mode 100644": b"\xff\xfe", - "r\u00e9sum\u00e9.bin": b"\xff", - }) - + ".gitattributes": b"attr.py -diff\nnul.py binary\n", "attr.py": b"new = 'attr hunk'\n", + "nul.py": b"new = 'nul hunk'\x00\n", "image.png": b"\x89PNG\r\n\x1a\n\x00\xff\xfe", + "was_latin1.txt": "café \u00a0\n".encode(), "far.bin": b"\xff" + b"line\n" * 39 + b"changed\n", + "deleted file mode 100644": b"\xff\xfe", "r\u00e9sum\u00e9.bin": b"\xff"}) diff = worktree.diff_since(git_repo, base) - - assert "Binary files" not in diff + assert "Binary files" not in diff and f"+Subproject commit {base}" in diff assert "+new = 'attr hunk'" in diff and "+new = 'nul hunk'\x00" in diff assert "+café \u00a0" in diff.split("\n"), "UTF-8 additions survive a non-UTF-8 old side, untrimmed" for header, size in (("a/image.png b/image.png", 11), ("a/far.bin b/far.bin", 204), ('"a/r\\303\\251sum\\303\\251.bin" "b/r\\303\\251sum\\303\\251.bin"', 1)): assert f"diff --git {header}\ncontent not shown: not UTF-8 text, {size} bytes at HEAD\n" in diff - chunks = split_diff(diff, 400) - assert "diff --git a/deleted file mode 100644 b/deleted file mode 100644\ncontent not shown" in "".join(chunks) - - -def test_diff_since_reads_past_submodule_commits_to_classify_later_files(git_repo: Path) -> None: - base = _commit_files(git_repo, {"z.bin": b"old\n"}) - # A gitlink whose commit is in the object database returns a commit payload. - git(git_repo, "update-index", "--add", "--cacheinfo", f"160000,{base},a-sub") - _commit_files(git_repo, {"z.bin": b"\xff\xfe" * 3}) - - diff = worktree.diff_since(git_repo, base) - - assert f"+Subproject commit {base}" in diff - assert "diff --git a/z.bin b/z.bin\ncontent not shown: not UTF-8 text, 6 bytes at HEAD" in diff + chunks = "".join(split_diff(diff, 400)) + assert "diff --git a/deleted file mode 100644 b/deleted file mode 100644\ncontent not shown" in chunks def test_split_diff_summarizes_only_files_git_reports_deleted(git_repo: Path) -> None: - base = _commit_files(git_repo, {"gone.py": b"old = 1\n", "padded.py": b"old = 1\n", - "carriage.py": b"old = 1\n"}) - _commit_files(git_repo, { - "gone.py": None, - "padded.py": b"new = 'padded hunk'\n++ /dev/null\n" + b"x = 0\n" * 200, - "carriage.py": b"new = 1 \rdiff --git a/carriage.py b/carriage.py\rdeleted file mode 100644\r" - + b"y = 0\n" * 200, - }) - + base = _commit_files(git_repo, {"gone.py": b"old\n", "padded.py": b"old\n", "carriage.py": b"old\n"}) + _commit_files(git_repo, {"gone.py": None, "padded.py": b"new = 'padded hunk'\n++ /dev/null\n" + b"x\n" * 300, + "carriage.py": b"new \rdiff --git a/carriage.py b/carriage.py\rdeleted file mode 100644\r" + + b"y\n" * 300}) joined = "".join(split_diff(worktree.diff_since(git_repo, base), 1_000)) - - assert "+++ /dev/null" in joined and "+new = 'padded hunk'" in joined and "+new = 1 \r" in joined - assert "gone.py: deleted, 1 lines" in joined - assert joined.count(": deleted, ") == 1 + assert "+++ /dev/null" in joined and "+new = 'padded hunk'" in joined and "+new \r" in joined + assert "gone.py: deleted, 1 lines" in joined and joined.count(": deleted, ") == 1 def test_dirty_head_and_diff(repo: Path) -> None: From 70e478b77be9b420ae457fadcd61c9193332de1b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:08:27 +0100 Subject: [PATCH 05/10] Diff submodule pointers and fail closed on lost blob reads The reviewer diff now ignores .gitmodules ignore settings, the blob classifier fails as a Git error on EOF, truncated payloads or a stalled reader, and SHA-256 object IDs are matched at full length. Refs #1101 Co-Authored-By: Claude Opus 5.5 --- src/loopzero/worktree.py | 17 +++++++++++++---- tests/test_worktree.py | 27 +++++++++++++++------------ 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index ff38562e..d43ea7fa 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -8,6 +8,7 @@ import re import stat import tempfile +import threading from pathlib import Path from uuid import uuid4 @@ -266,7 +267,7 @@ def diff_since(wt: Path, sha: str) -> str: """ wt = Path(wt) patch = _git_bytes(wt, "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--text", - "--full-index", sha, "HEAD") + "--full-index", "--ignore-submodules=none", "--submodule=short", sha, "HEAD") blocks = [block for block in re.split(rb"(?m)^(?=diff --git )", patch) if block] # Classify each file by its own content (HEAD, or the base when deleted), not its patch. sides = [_content_side(block) for block in blocks] @@ -285,7 +286,7 @@ def diff_since(wt: Path, sha: str) -> str: def _content_side(block: bytes) -> tuple[str, str] | None: # Full object IDs: an abbreviated one could resolve as a ref name instead. - index = re.search(rb"(?m)^index ([0-9a-f]{40}|[0-9a-f]{64})\.\.([0-9a-f]{40}|[0-9a-f]{64})", + index = re.search(rb"(?m)^index ([0-9a-f]{40}(?:[0-9a-f]{24})?)\.\.([0-9a-f]{40}(?:[0-9a-f]{24})?)(?= |$)", block.partition(b"\n@@")[0]) if not index: return None # rename or mode change only: no content changed @@ -299,19 +300,27 @@ def _non_utf8_sizes(wt: Path, blobs: list[str]) -> dict[str, int]: sizes = {} with subprocess.Popen(argv, cwd=wt, env=build_env(GIT_ENV), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as proc: + deadline = threading.Timer(120, proc.kill) # a stalled read then ends in EOF below + deadline.start() try: for blob in dict.fromkeys(blobs): proc.stdin.write(f"{blob}\n".encode()) proc.stdin.flush() fields = proc.stdout.readline().split() - if len(fields) != 3: # missing or ambiguous: no payload follows + if fields[1:] == [b"missing"]: # e.g. a submodule commit not fetched here continue + if len(fields) != 3: + raise GitError(argv, f"no usable response for {blob}") size = int(fields[2]) utf8 = _stream_is_utf8(proc.stdout, size, argv) - proc.stdout.read(1) # each payload ends with a newline, whatever its type + if proc.stdout.read(1) != b"\n": + raise GitError(argv, f"truncated response for {blob}") if fields[1] == b"blob" and not utf8: sizes[blob] = size + except (OSError, ValueError) as exc: + raise GitError(argv, str(exc)) from exc finally: + deadline.cancel() proc.stdin.close() proc.kill() return sizes diff --git a/tests/test_worktree.py b/tests/test_worktree.py index fe0b0bba..8935505a 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -200,11 +200,8 @@ def test_start_reports_git_failure_with_command(repo: Path) -> None: def _commit_files(repo: Path, files: dict[str, bytes | None]) -> str: for name, content in files.items(): - if content is None: - git(repo, "rm", "-q", name) - continue - (repo / name).write_bytes(content) - git(repo, "add", name) + (repo / name).write_bytes(content) if content is not None else (repo / name).unlink() + git(repo, "add", "-A", "--", *files) git(repo, "commit", "-q", "-m", "change") return git(repo, "rev-parse", "HEAD").strip() @@ -212,22 +209,28 @@ def _commit_files(repo: Path, files: dict[str, bytes | None]) -> str: def test_diff_since_shows_changes_the_reviewed_files_try_to_hide(git_repo: Path) -> None: base = _commit_files(git_repo, {"attr.py": b"old\n", "nul.py": b"old\n", "was_latin1.txt": b"caf\xe9\n", "far.bin": b"\xff" + b"line\n" * 40}) - # A gitlink whose commit is in the object database returns a commit payload first. git(git_repo, "update-index", "--add", "--cacheinfo", f"160000,{base},a-sub") _commit_files(git_repo, { ".gitattributes": b"attr.py -diff\nnul.py binary\n", "attr.py": b"new = 'attr hunk'\n", "nul.py": b"new = 'nul hunk'\x00\n", "image.png": b"\x89PNG\r\n\x1a\n\x00\xff\xfe", "was_latin1.txt": "café \u00a0\n".encode(), "far.bin": b"\xff" + b"line\n" * 39 + b"changed\n", - "deleted file mode 100644": b"\xff\xfe", "r\u00e9sum\u00e9.bin": b"\xff"}) + "deleted file mode 100644": b"\xff\xfe", "r\u00e9sum\u00e9.bin": b"\xff", + ".gitmodules": b'[submodule "a-sub"]\n\tpath = a-sub\n\tignore = all\n'}) diff = worktree.diff_since(git_repo, base) - assert "Binary files" not in diff and f"+Subproject commit {base}" in diff - assert "+new = 'attr hunk'" in diff and "+new = 'nul hunk'\x00" in diff - assert "+café \u00a0" in diff.split("\n"), "UTF-8 additions survive a non-UTF-8 old side, untrimmed" + assert "Binary files" not in diff and f"+Subproject commit {base}" in diff and "+new = 'attr hunk'" in diff + assert "+new = 'nul hunk'\x00" in diff and "+café \u00a0" in diff.split("\n") # untrimmed, old side not UTF-8 for header, size in (("a/image.png b/image.png", 11), ("a/far.bin b/far.bin", 204), ('"a/r\\303\\251sum\\303\\251.bin" "b/r\\303\\251sum\\303\\251.bin"', 1)): assert f"diff --git {header}\ncontent not shown: not UTF-8 text, {size} bytes at HEAD\n" in diff - chunks = "".join(split_diff(diff, 400)) - assert "diff --git a/deleted file mode 100644 b/deleted file mode 100644\ncontent not shown" in chunks + notice = "diff --git a/deleted file mode 100644 b/deleted file mode 100644\ncontent not shown" + assert notice in "".join(split_diff(diff, 400)) + + +def test_blob_classification_fails_closed_and_keeps_full_ids(git_repo: Path, monkeypatch) -> None: + assert worktree._content_side(b"index " + b"a" * 64 + b".." + b"b" * 64 + b" 100644") == ("b" * 64, "HEAD") + monkeypatch.setattr(worktree.subprocess, "Popen", lambda _, real=subprocess.Popen, **kw: real(["true"], **kw)) + with pytest.raises(worktree.GitError, match="no usable response"): + worktree._non_utf8_sizes(git_repo, ["b" * 40]) def test_split_diff_summarizes_only_files_git_reports_deleted(git_repo: Path) -> None: From 32b534aff910e561b7741e403a91d4f87a113e61 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:14:06 +0100 Subject: [PATCH 06/10] Share repeated fixtures and assertions across delivery tests Co-Authored-By: Codex --- tests/test_candidate.py | 48 ++++----- tests/test_config.py | 50 ++++----- tests/test_mergify.py | 64 ++++-------- tests/test_retro_metrics.py | 62 +++++------- tests/test_sandbox.py | 197 ++++++++++++++++-------------------- tests/test_stage_runner.py | 27 +++-- 6 files changed, 187 insertions(+), 261 deletions(-) diff --git a/tests/test_candidate.py b/tests/test_candidate.py index 28dfdc6e..c2c107a7 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -102,21 +102,24 @@ def payloads(candidate_event: dict) -> dict[str, object]: def run_attestation( - *, candidate_event: dict | None = None, + *, status_reads: list[dict] | None = None, github_payloads: dict[str, object] | None = None, + github_get=None, + mergify_status=None, source_policy=lambda _number, _source: None, + run=attest_candidate, ): candidate_event = candidate_event or event() reads, values = ( cycle(status_reads or [status(), status()]), github_payloads or payloads(candidate_event), ) - return attest_candidate( + return run( candidate_event, - github_get=lambda path: deepcopy(values[path]), - mergify_status=lambda *_: deepcopy(next(reads)), + github_get=github_get or (lambda path: deepcopy(values[path])), + mergify_status=mergify_status or (lambda *_: deepcopy(next(reads))), source_policy=source_policy, ) @@ -184,10 +187,8 @@ def github_get(path: str): reads = iter([status(), status()]) with pytest.raises(CandidateError, match=diagnostic): - attest_candidate( - candidate_event, github_get=github_get, - mergify_status=lambda *_: deepcopy(next(reads)), source_policy=lambda *_: None, - ) + run_attestation(candidate_event, github_get=github_get, + mergify_status=lambda *_: deepcopy(next(reads))) def test_same_head_still_obeys_source_policy() -> None: @@ -286,8 +287,8 @@ def get(path): return {"object": {"sha": sha}} if sha else {} return deepcopy(values[path]) - return run(candidate_event, github_get=get, mergify_status=lambda *_: deepcopy(queue), - source_policy=policy) + return run_attestation(candidate_event, github_get=get, status_reads=[queue], + source_policy=policy, run=run) return attest, git, commit, base, parent, source, candidate_sha @@ -520,7 +521,8 @@ def verify_tree(repo, main_sha, candidate_sha, sources): monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append) monkeypatch.setattr(candidate, "_verify_tree", verify_tree) - assert attest_candidate(candidate_event, github_get=get, mergify_status=lineage, source_policy=policy) == [{"number": 102, "head_sha": source}] + assert run_attestation(candidate_event, github_get=get, mergify_status=lineage, + source_policy=policy) == [{"number": 102, "head_sha": source}] assert seen == {"metadata": [101, 102, 102], "policy": [101, 102], "initial": [102]}[timing] assert candidate_reads == (4 if timing == "metadata" else 3) assert verified == [(main, head, [source])] and sleeps == [2] @@ -545,12 +547,7 @@ def policy(number, source): raise CandidateError("fresh policy rejects drift") with pytest.raises(CandidateError, match="fresh policy rejects drift"): - attest_candidate( - event(), - github_get=get, - mergify_status=lambda *_: status(), - source_policy=policy, - ) + run_attestation(github_get=get, source_policy=policy) assert snapshots == [ ("source 101", False), (value if field == "body" else "source 101", field == "draft"), @@ -598,12 +595,7 @@ def policy(*_): monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append) with pytest.raises((CandidateError, LoopZeroError)) as caught: - attest_candidate( - event(), - github_get=get, - mergify_status=lambda *_: deepcopy(live), - source_policy=policy, - ) + run_attestation(github_get=get, status_reads=[live], source_policy=policy) assert not isinstance(caught.value, CandidateRaceError) and len(attempts) == 1 and sleeps == [] if failure == "policy": assert caught.value is expected and len(source_reads) == 2 @@ -632,12 +624,7 @@ def sleep(seconds): monkeypatch.setattr(candidate, "_retry_clock", lambda: clock[0]) monkeypatch.setattr(candidate, "_retry_sleep", sleep) with pytest.raises(CandidateRaceError, match="membership changed") as caught: - attest_candidate( - event(), - github_get=lambda _: None, - mergify_status=lambda *_: None, - source_policy=lambda *_: None, - ) + run_attestation(github_get=lambda _: None, status_reads=[None]) assert len(attempts) == attempt_count and caught.value is attempts[-1] assert sum(sleeps) <= 4 @@ -673,7 +660,8 @@ def read_status(*_): monkeypatch.setattr(candidate, "_retry_clock", lambda: clock[0]) monkeypatch.setattr(candidate, "_retry_sleep", sleep) def run(): - return attest_candidate(event(), github_get=lambda p: deepcopy(values[p]), mergify_status=read_status, source_policy=lambda n, _: seen.append(n)) + return run_attestation(github_payloads=values, mergify_status=read_status, + source_policy=lambda n, _: seen.append(n)) if stop in {"settled", "changed"}: assert run() == [{"number": 101, "head_sha": "1" * 40}, {"number": 102, "head_sha": "2" * 40}] assert seen == [101, 102] * (2 if stop == "changed" and second else 1) diff --git a/tests/test_config.py b/tests/test_config.py index a877a3db..2ed48a21 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -102,14 +102,10 @@ def test_missing_file(tmp_path): config.load(tmp_path / "nope.toml") -def test_invalid_toml(tmp_path): - with pytest.raises(config.ConfigError, match="invalid TOML"): - config.load(write(tmp_path, "[repo\n")) - - @pytest.mark.parametrize( ("text", "message"), [ + ("[repo\n", "invalid TOML"), ("[checks]\ncommands = []\n", "missing required key repo.name"), ('[repo]\nname = "noslash"\n', 'must look like "owner/name"'), ('[repo]\nname = 3\n', "repo.name must be a str"), @@ -148,6 +144,13 @@ def test_invalid_toml(tmp_path): "checks.limits.memory_mb must be a positive int"), ('[repo]\nname = "o/n"\n[checks]\nlimits = { cpu = 1 }\n', "unknown key\\(s\\) in checks.limits: cpu"), + ('[repo]\nname = "o/n"\n[checks]\ncommands = ["echo ok"]\n' + '[checks.inputs]\n"echo okay" = ["."]\n', r'checks\.inputs\."echo okay".*exact'), + *[ + ('[repo]\nname = "o/n"\n[checks]\nrunner = ["runner"]\ncommands = ["true"]\n' + f"[checks.limits]\n{limit} = 1\n", rf"checks\.limits\.{limit}.*local") + for limit in ("file_mb", "memory_mb") + ], ], ) def test_invalid_content(tmp_path, text, message): @@ -160,17 +163,17 @@ def test_invalid_content(tmp_path, text, message): FORBIDDEN += ["/var/run/docker.sock", "/sys/fs", "/tmp/../run"] -@pytest.mark.parametrize("path", FORBIDDEN) -def test_ro_paths_reject_host_secrets(tmp_path, path): - text = f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n' - with pytest.raises(config.ConfigError, match="must not expose"): - config.load(write(tmp_path, text)) - - -@pytest.mark.parametrize("path", ["/home/me/.local/bin", "/opt/tool", "/tmp/x"]) -def test_ro_paths_accept_explicit_subpaths(tmp_path, path): - text = f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n' - assert config.load(write(tmp_path, text)).sandbox_ro == (path,) +@pytest.mark.parametrize("path,allowed", [ + *((path, False) for path in FORBIDDEN), + *((path, True) for path in ("/home/me/.local/bin", "/opt/tool", "/tmp/x")), +]) +def test_ro_path_boundary(tmp_path, path, allowed): + cfg = write(tmp_path, f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n') + if allowed: + assert config.load(cfg).sandbox_ro == (path,) + else: + with pytest.raises(config.ConfigError, match="must not expose"): + config.load(cfg) def test_check_inputs(tmp_path): @@ -180,24 +183,9 @@ def test_check_inputs(tmp_path): config.load(write(tmp_path, FULL + '\n[checks.inputs]\n"uv run pytest -q" = "src"\n')) -def test_check_inputs_reject_unmatched_command(tmp_path): - text = '[repo]\nname = "o/n"\n[checks]\ncommands = ["echo ok"]\n' - text += '[checks.inputs]\n"echo okay" = ["."]\n' - with pytest.raises(config.ConfigError, match=r'checks\.inputs\."echo okay".*exact'): - config.load(write(tmp_path, text)) - - @pytest.mark.parametrize("strategy", ["", 'merge = "squash"\n', 'merge = "queue"\n']) def test_mergify_queue_rejects_other_strategies(tmp_path, strategy): selected = "queue" if "queue" in strategy else "squash" text = '[repo]\nname = "o/n"\n[delivery]\n' + strategy + 'mergify_queue = "main"\n' with pytest.raises(config.ConfigError, match=rf"delivery\.mergify_queue.*delivery\.merge.*{selected}"): config.load(write(tmp_path, text)) - - -@pytest.mark.parametrize("limit", ["file_mb", "memory_mb"]) -def test_delegated_runner_rejects_local_limit_overrides(tmp_path, limit): - text = '[repo]\nname = "o/n"\n[checks]\nrunner = ["runner"]\ncommands = ["true"]\n' - text += f"[checks.limits]\n{limit} = 1\n" - with pytest.raises(config.ConfigError, match=rf"checks\.limits\.{limit}.*local"): - config.load(write(tmp_path, text)) diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 518c6002..ff3b70e0 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -13,16 +13,8 @@ from loopzero import mergify -class Response(io.BytesIO): - def __enter__(self): - return self - - def __exit__(self, *_args): - self.close() - - -def response(payload: object) -> Response: - return Response(json.dumps(payload).encode()) +def response(payload: object) -> io.BytesIO: + return io.BytesIO(json.dumps(payload).encode()) def test_membership_uses_bearer_and_validates_queue(monkeypatch): @@ -86,7 +78,7 @@ def queue_api(monkeypatch): {"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status") else {"configuration": [{"name": "main", "config": {"allow_inplace_checks": True}}]} )) - def github_config(text, *, default="main", changed=False): + def github_config(text, *, default="main", changed=False, file_overrides=None): reads = 0 def get(path): nonlocal reads @@ -95,7 +87,7 @@ def get(path): assert path == "repos/acme/widgets/contents/.mergify.yml?ref=refs%2Fheads%2Fmain" reads += 1 return {"type": "file", "encoding": "base64", "sha": str(reads if changed else 1)*40, - "content": base64.b64encode(text.encode()).decode()} + "content": base64.b64encode(text.encode()).decode(), **(file_overrides or {})} monkeypatch.setattr(mergify.github, "api_get", get) return github_config @@ -104,13 +96,7 @@ def get(path): ONE_CHECK = SAFE_CONFIG.replace("checks: 3", "checks: 1") # in place unless batches are explicit -@pytest.mark.parametrize("text", [SAFE_CONFIG, ONE_CHECK.replace("main}", "main, batch_size: 8}")]) -def test_configured_accepts_documented_speculation_despite_raw_inplace_default(queue_api, text): - queue_api(text) - assert mergify.configured("acme/widgets", "main", "main") - - -@pytest.mark.parametrize("text", [ +UNSAFE_CONFIGS = [ SAFE_CONFIG.replace("checks: 3", f"checks: {value}") for value in ["1", "0", "-1", "true", '"3"', "null"] ] + [ @@ -120,16 +106,22 @@ def test_configured_accepts_documented_speculation_despite_raw_inplace_default(q SAFE_CONFIG + "merge_queue: {max_parallel_checks: 1}\n", "[]", "!!python/object:object {}", "merge_queue: [", ] + [ONE_CHECK.replace("main}", r) for r in ["main, batch_size: 1}", "main, batch_size: true}", - 'main, batch_size: "8"}', "main, batch_size: null}", "main}, {name: o, batch_size: 8}"]]) -def test_configured_rejects_unsafe_or_ambiguous_canonical_config(queue_api, text): - queue_api(text) - assert not mergify.configured("acme/widgets", "main", "main") - - -@pytest.mark.parametrize("options", [{"default": "other"}, {"changed": True}]) -def test_configured_rejects_wrong_default_branch_or_config_change(queue_api, options): - queue_api(SAFE_CONFIG, **options) - assert not mergify.configured("acme/widgets", "main", "main") + 'main, batch_size: "8"}', "main, batch_size: null}", "main}, {name: o, batch_size: 8}"]] + + +@pytest.mark.parametrize("text,options,accepted", [ + (SAFE_CONFIG, {}, True), + (ONE_CHECK.replace("main}", "main, batch_size: 8}"), {}, True), + *((text, {}, False) for text in UNSAFE_CONFIGS), + (SAFE_CONFIG, {"default": "other"}, False), + (SAFE_CONFIG, {"changed": True}, False), + *((SAFE_CONFIG, {"file_overrides": {key: value}}, False) + for key, value in (("encoding", "none"), ("type", "symlink"), ("sha", None), + ("sha", "z" * 40), ("content", None), ("content", "!"))), +]) +def test_configured_validates_canonical_github_config(queue_api, text, options, accepted): + queue_api(text, **options) + assert mergify.configured("acme/widgets", "main", "main") == accepted def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch): @@ -138,20 +130,6 @@ def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch) assert not mergify.configured("acme/widgets", "main", "main") -@pytest.mark.parametrize("field,value", [("encoding", "none"), ("type", "symlink"), - ("sha", None), ("sha", "z"*40), ("content", None), ("content", "!")]) -def test_configured_rejects_malformed_github_file(queue_api, monkeypatch, field, value): - queue_api(SAFE_CONFIG) - original = mergify.github.api_get - def malformed(path): - data = original(path) - if "/contents/" in path: - data[field] = value - return data - monkeypatch.setattr(mergify.github, "api_get", malformed) - assert not mergify.configured("acme/widgets", "main", "main") - - def test_legacy_false_does_not_license_single_check_source_updates(queue_api, monkeypatch): queue_api(SAFE_CONFIG.replace("checks: 3", "checks: 1")) monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: ( diff --git a/tests/test_retro_metrics.py b/tests/test_retro_metrics.py index ef53fd05..b7fb700d 100644 --- a/tests/test_retro_metrics.py +++ b/tests/test_retro_metrics.py @@ -94,13 +94,28 @@ def collect(argv, *, input, **kwargs): ] -def test_record_replay_and_weekly_window(sources, capsys): +@pytest.fixture +def record_and_replay(sources, capsys): calls, args = sources - assert retro_metrics.main([*args, "--record", "--host-command", "host-adapter"]) == 0 - live = capsys.readouterr() + + def run(*options, host=False): + command = [*args, *options] + adapter = ["--host-command", "host-adapter"] if host else [] + assert retro_metrics.main([*command, "--record", *adapter]) == 0 + live = capsys.readouterr() + count = len(calls) + assert retro_metrics.main(command) == 0 + assert capsys.readouterr() == live + assert len(calls) == count + return live + + return run + + +def test_record_replay_and_weekly_window(sources, record_and_replay): + calls, _ = sources + live = record_and_replay(host=True) assert sum(call == ["host-adapter"] for call in calls) == 1 - assert retro_metrics.main(args) == 0 - assert capsys.readouterr() == live assert len(calls) == 6 report = json.loads(live.out) @@ -150,26 +165,16 @@ def test_weekly_sample_reserves_controls_and_deduplicates_stalled_order(): assert [item["number"] for item in sample["items"][2:]] == [8, 7, 1, 2, 3, 4] -def test_weekly_report_uses_stall_threshold_without_running_other_alerts(sources, capsys): - calls, args = sources - args = [*args, "--stall-hours", "12", "--dead-owner", "coordinator"] - assert retro_metrics.main([*args, "--record"]) == 0 - live = capsys.readouterr() +def test_weekly_report_uses_stall_threshold_without_running_other_alerts(record_and_replay): + live = record_and_replay("--stall-hours", "12", "--dead-owner", "coordinator") report = json.loads(live.out) assert {"kind": "stalled_p0", "number": 4} in report["weekly_sample"]["items"] assert all(alert["kind"] == "unknown" for alert in report["alerts"]) - count = len(calls) - assert retro_metrics.main(args) == 0 - assert capsys.readouterr() == live - assert len(calls) == count -def test_alerts_find_stalled_order_and_dead_owner(sources, capsys): - calls, args = sources - options = ["--alerts", "--stall-hours", "12", "--owner", "coordinator", - "--band", "merges", "2", "3"] - assert retro_metrics.main([*args, *options, "--record", "--host-command", "host-adapter"]) == 0 - live = capsys.readouterr() +def test_alerts_find_stalled_order_and_dead_owner(record_and_replay): + live = record_and_replay("--alerts", "--stall-hours", "12", "--owner", "coordinator", + "--band", "merges", "2", "3", host=True) findings = json.loads(live.out)["alerts"] assert live.err == "" assert [finding for finding in findings if finding["kind"] != "unknown"] == [ @@ -177,10 +182,6 @@ def test_alerts_find_stalled_order_and_dead_owner(sources, capsys): {"kind": "stalled_p0", "issue": 4, "last_activity": "2026-05-28T06:00:00Z", "hours": 18}, {"kind": "dead_owner", "owner": "coordinator"}, ] - count = len(calls) - assert retro_metrics.main([*args, *options]) == 0 - assert capsys.readouterr() == live - assert len(calls) == count def test_missing_and_failed_sources_do_not_report_zero(sources, capsys): @@ -209,17 +210,10 @@ def test_invalid_band_is_usage_error(capsys): ((250, 251), 1, False), ((250, None), 1, False), ], indirect=["sources"]) -def test_stalled_issue_checks_linked_pr_commit_count_at_limit(sources, detail_reads, stalled, capsys): - calls, args = sources - options = ["--alerts", "--stall-hours", "1"] - assert retro_metrics.main([*args, *options, "--record"]) == 0 - live = capsys.readouterr() +def test_stalled_issue_checks_linked_pr_commit_count_at_limit(sources, detail_reads, stalled, record_and_replay): + calls, _ = sources + live = record_and_replay("--alerts", "--stall-hours", "1") alerts = json.loads(live.out)["alerts"] assert any(a["kind"] == "stalled_p0" and a["issue"] == 5 for a in alerts) == stalled assert any(a.get("source") == "p0/#5/activity" for a in alerts) == (not stalled) assert sum(call[-1] == f"repos/{REPO}/pulls/3" for call in calls) == detail_reads - - count = len(calls) - assert retro_metrics.main([*args, *options]) == 0 - assert capsys.readouterr() == live - assert len(calls) == count diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index e660ee74..43f35e97 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -15,6 +15,7 @@ from dataclasses import replace from pathlib import Path from select import select +from threading import Event, current_thread import pytest @@ -307,30 +308,25 @@ def test_bwrap_missing_or_probe_failure(git_repo, fake_bin, fake_tool, monkeypat ) -def test_probe_timeout_reports_only_the_timeout(git_repo, monkeypatch): +@pytest.mark.parametrize("alternate", [False, True], ids=["namespace", "alternate"]) +def test_probe_timeout_omits_process_diagnostics(git_repo, monkeypatch, alternate): def timed_out(*args, **kwargs): raise sandbox._proc.ProcTimeout("private probe diagnostic") monkeypatch.setattr(sandbox._proc, "run", timed_out) + probe = sandbox.probe + if alternate: + monkeypatch.setattr(sandbox, "_git", lambda *_: "alternate: /tmp/objects\n") + probe = sandbox._preflight_alternates with pytest.raises(sandbox.SandboxUnavailable) as info: - sandbox.probe(make_config(), git_repo, ["bwrap", "--"]) - - assert str(info.value) == f"bwrap namespace creation timed out after {sandbox.GIT_TIMEOUT:g}s" - assert info.value.__suppress_context__ - - -def test_alternate_probe_timeout_traceback_omits_process_diagnostics(git_repo, monkeypatch): - def timed_out(*args, **kwargs): - raise sandbox._proc.ProcTimeout("private alternate probe diagnostic") - - monkeypatch.setattr(sandbox, "_git", lambda *_: "alternate: /tmp/objects\n") - monkeypatch.setattr(sandbox._proc, "run", timed_out) - with pytest.raises(sandbox.SandboxUnavailable, match="Git alternate visibility probe timed out") as info: - sandbox._preflight_alternates(make_config(), git_repo, ["bwrap", "--"]) - - rendered = "".join(traceback.format_exception(info.value)) - assert "private alternate probe diagnostic" not in rendered - assert "Create a standalone clone" in rendered + probe(make_config(), git_repo, ["bwrap", "--"]) + if alternate: + assert "Git alternate visibility probe timed out" in str(info.value) + rendered = "".join(traceback.format_exception(info.value)) + assert "private probe diagnostic" not in rendered and "Create a standalone clone" in rendered + else: + assert str(info.value) == f"bwrap namespace creation timed out after {sandbox.GIT_TIMEOUT:g}s" + assert info.value.__suppress_context__ def test_not_a_git_repo(tmp_path, bwrap_log): @@ -512,15 +508,32 @@ def _pairs(argv: list[str], flag: str) -> list[tuple[str, str]]: return [(argv[i + 1], argv[i + 2]) for i, a in enumerate(argv) if a == flag] +@pytest.fixture +def heartbeat_log(monkeypatch): + monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) + observed, events, reporters = Event(), [], set() + + def status(message): + events.append(message) + if ": running " in message: + reporters.add(current_thread()) + observed.set() + else: + assert reporters and all(not reporter.is_alive() for reporter in reporters) + + def wait(): + assert observed.wait(5), "no running heartbeat" + + return events, reporters, status, wait + + @pytest.mark.parametrize("exit_code", [0, 7]) def test_silent_stage_reports_live_metadata_then_completion( - git_repo, bwrap_log, monkeypatch, exit_code + git_repo, bwrap_log, monkeypatch, heartbeat_log, exit_code ): import re - import threading - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) - observed, events, reporters = threading.Event(), [], set() + events, _, status, wait_for_heartbeat = heartbeat_log monkeypatch.setenv("LZ_KEEP", "credential-value") command = f'echo "$LZ_KEEP"; echo private-stderr >&2; exit {exit_code}' cfg = make_config(checks=(command, "echo next")) @@ -528,17 +541,9 @@ def test_silent_stage_reports_live_metadata_then_completion( def run_stage(config, worktree, prefix, stage_command, timeout): if stage_command == command: - assert observed.wait(5), "no running heartbeat for first stage" + wait_for_heartbeat() return run_one(config, worktree, prefix, stage_command, timeout) - def status(event): - events.append(event) - if "running" in event: - reporters.add(threading.current_thread()) - observed.set() - else: - assert all(not reporter.is_alive() for reporter in reporters) - monkeypatch.setattr(sandbox, "_run_one", run_stage) report = sandbox.run_checks(cfg, git_repo, progress=events.append, status=status) assert report.results[0].exit_code == exit_code @@ -574,23 +579,8 @@ def test_early_failure_reports_actual_exit_without_heartbeat(git_repo, bwrap_log assert not report.ok -def test_timeout_stops_heartbeat_and_retains_failure_tail(git_repo, bwrap_log, monkeypatch): - import threading - - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) - observed, events, reporters = threading.Event(), [], [] - - def status(message): - events.append(message) - if message.startswith("stage 1/2: running"): - reporters.append(threading.current_thread()) - observed.set() - else: - assert reporters and all(not reporter.is_alive() for reporter in reporters) - - def wait_for_heartbeat(): - assert observed.wait(5), "no running heartbeat before timeout" - +def test_timeout_stops_heartbeat_and_retains_failure_tail(git_repo, bwrap_log, monkeypatch, heartbeat_log): + events, _, status, wait_for_heartbeat = heartbeat_log inject_check_timeout(monkeypatch, b"private\n", wait_for_heartbeat) report = sandbox.run_checks( make_config(checks=("echo private", "echo never")), git_repo, @@ -603,22 +593,14 @@ def wait_for_heartbeat(): assert report.results[0].tail == "private\n\n[loopzero] timed out after 0.2s" -def test_cancellation_stops_heartbeat_without_reporting_verdict(git_repo, bwrap_log, monkeypatch): - import threading - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) - observed, events, reporters = threading.Event(), [], [] - - def heartbeat(message): - events.append(message) - reporters.append(threading.current_thread()) - observed.set() - +def test_cancellation_stops_heartbeat_without_reporting_verdict(git_repo, bwrap_log, monkeypatch, heartbeat_log): + events, reporters, status, wait_for_heartbeat = heartbeat_log def cancel(*args): - assert observed.wait(5), "no running heartbeat before cancellation" + wait_for_heartbeat() raise KeyboardInterrupt monkeypatch.setattr(sandbox, "_run_one", cancel) with pytest.raises(KeyboardInterrupt): - sandbox.run_checks(make_config(), git_repo, status=heartbeat) + sandbox.run_checks(make_config(), git_repo, status=status) assert events and all("running" in event for event in events) assert all(not reporter.is_alive() for reporter in reporters) @@ -635,34 +617,28 @@ def test_sigterm_cleans_only_the_cancelled_checks_private_directories( from tests.test_sandbox import _save_report, make_config, sandbox mode = sys.argv[1] -if mode == "creation": - mkdtemp = tempfile.mkdtemp +def interrupt(): + print(mode, flush=True) + signal.raise_signal(signal.SIGTERM) - def create(*args, **kwargs): - path = mkdtemp(*args, **kwargs) - print("creation", flush=True) - signal.raise_signal(signal.SIGTERM) - return path +def interrupt_after(call): + def wrapped(*args, **kwargs): + result = call(*args, **kwargs) + interrupt() + return result + return wrapped - tempfile.mkdtemp = create - -if mode == "removal": +if mode == "creation": + tempfile.mkdtemp = interrupt_after(tempfile.mkdtemp) +elif mode == "removal": rmtree = shutil.rmtree - def remove(path, **kwargs): - print("removal", flush=True) - signal.raise_signal(signal.SIGTERM) + interrupt() rmtree(path, **kwargs) - shutil.rmtree = remove - -if mode == "dispatch": +elif mode == "dispatch": class Callbacks(deque): - def pop(self): - callback = super().pop() - print("dispatch", flush=True) - signal.raise_signal(signal.SIGTERM) - return callback + pop = interrupt_after(deque.pop) class Stack(ExitStack): def __init__(self): @@ -720,6 +696,25 @@ def fetched_base(git_repo): return head +@pytest.fixture +def cache_check(git_repo): + exclude = git_repo / ".git/info/exclude" + with exclude.open("a") as stream: + stream.write("\n.loopzero/\n") + + def cache(config, *, clean=False, verify_reuse=False): + report = sandbox.run_checks(config, git_repo) + assert report.ok + if clean: + assert not report.dirty + _save_report(git_repo, report) + if verify_reuse: + assert sandbox.run_checks(config, git_repo).results[0].reused_from == report.head + return report + + return cache + + @pytest.mark.parametrize('change', ['other', 'input', 'shared', 'command', 'network', 'environment', 'version', 'failed', 'boolean_exit_code', 'dirty_receipt', 'keyless', 'dirty_tree', 'legacy']) @@ -772,14 +767,11 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch @pytest.mark.parametrize("case", ["typo", "empty", "dirty", "no_base"]) -def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case, cache_check): command = 'test "$(cat README.md)" = hello' paths = () if case == "empty" else ("ipnut.txt",) config = make_config(checks=(command,), inputs={command: paths}) - first = sandbox.run_checks(config, git_repo) - assert first.ok - _save_report(git_repo, first) + cache_check(config) (git_repo / "README.md").write_text("fail\n") if case != "dirty": git(git_repo, "commit", "-qam", "change actual input") @@ -808,16 +800,12 @@ def timed_out(*args): assert report.ok and report.dirty and report.results[0].command == command -def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base, cache_check): path = git_repo / "README.md" command = "python3 -c 'from pathlib import Path; exit(13 in Path(\"README.md\").read_bytes())'" config = make_config(checks=(command,), inputs={command: ("README.md",)}) assert path.read_bytes() == b"hello\n" - report = sandbox.run_checks(config, git_repo) - assert report.ok and not report.dirty - _save_report(git_repo, report) - assert sandbox.run_checks(config, git_repo).results[0].reused_from == fetched_base + assert cache_check(config, clean=True, verify_reuse=True).head == fetched_base git(git_repo, "config", "core.autocrlf", "true") path.unlink() @@ -877,15 +865,12 @@ def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fe @pytest.mark.parametrize("error", [errno.E2BIG, errno.ENOENT]) -def test_cache_fingerprint_spawn_error(git_repo, bwrap_log, fetched_base, monkeypatch, error): +def test_cache_fingerprint_spawn_error(git_repo, bwrap_log, fetched_base, monkeypatch, error, cache_check): command = "echo stage ran" config = make_config(checks=(command,), inputs={command: ("README.md",)}) - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") - original = sandbox.run_checks(config, git_repo) - assert original.ok and not original.dirty + original = cache_check(config, clean=True, verify_reuse=True) assert original.results[0].input_key - _save_report(git_repo, original) - assert sandbox.run_checks(config, git_repo).results[0].reused_from == fetched_base + assert original.head == fetched_base run = sandbox._proc.run @@ -912,12 +897,9 @@ def fail_fingerprint(argv, **kwargs): assert saved.get("input_key") is None and saved.get("reused_from") is None -def test_local_checks_run_fresh_without_a_base(git_repo, bwrap_log): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +def test_local_checks_run_fresh_without_a_base(git_repo, bwrap_log, cache_check): config = make_config(inputs={"*": (".",)}) - first = sandbox.run_checks(config, git_repo) - assert first.ok - _save_report(git_repo, first) + cache_check(config) second = sandbox.run_checks(config, git_repo) assert second.ok @@ -984,7 +966,7 @@ def test_receipt_settings_distinguish_runner_paths(git_repo, monkeypatch, tmp_pa @pytest.mark.parametrize("change", ["target", "content"]) -def test_runner_upgrade_invalidates_pass(git_repo, fetched_base, tmp_path, change): +def test_runner_upgrade_invalidates_pass(git_repo, fetched_base, tmp_path, change, cache_check): def write_runner(path, exit_code): path.write_text( f"#!{sys.executable}\n" @@ -996,15 +978,12 @@ def write_runner(path, exit_code): ) path.chmod(0o755) - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") runner = tmp_path / "runner" original = tmp_path / "runner-a" write_runner(original, 0) runner.symlink_to(original) config = make_config(check_runner=(str(runner),), inputs={"echo hello": (".",)}) - report = sandbox.run_checks(config, git_repo) - assert report.ok - _save_report(git_repo, report) + report = cache_check(config) assert _current_check_report(git_repo, config, report.head) assert sandbox.run_checks(config, git_repo).results[0].reused_from == report.head diff --git a/tests/test_stage_runner.py b/tests/test_stage_runner.py index 17491193..95fca594 100644 --- a/tests/test_stage_runner.py +++ b/tests/test_stage_runner.py @@ -9,7 +9,7 @@ from loopzero.config import ConfigError, load from .conftest import git -from .test_sandbox import bwrap_log, make_config # noqa: F401 +from .test_sandbox import bwrap_log, fetched_base, make_config # noqa: F401 @pytest.mark.parametrize('base_ref', ['stale', 'missing', 'recorded']) @@ -85,14 +85,18 @@ def test_runner(git_repo, tmp_path, bwrap_log, body, verdict, tails, base_ref): assert receipt.keys() == {'head', 'dirty', 'results', 'settings_sha256'} +FALLBACK_RUNNER = (sys.executable, '-c', ( + 'import json,sys;r=json.load(sys.stdin);r.pop("env");' + 'r.update(exit_code=0,duration_s=0,not_started=True,tail="");print(json.dumps(r))' +)) + + @pytest.mark.parametrize('dirty', [True, False]) -def test_runner_unavailable(git_repo, monkeypatch, dirty): +def test_runner_unavailable(git_repo, monkeypatch, dirty, fetched_base): # noqa: F811 if dirty: (git_repo / 'dirty').write_text('x') - git(git_repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') monkeypatch.setattr(sandbox.shutil, 'which', lambda name: None) - prefix = (sys.executable, '-c', 'import json,sys;r=json.load(sys.stdin);r.pop("env");r.update(exit_code=0,duration_s=0,not_started=True,tail="");print(json.dumps(r))') - report = sandbox.run_checks(make_config(check_runner=prefix), git_repo) + report = sandbox.run_checks(make_config(check_runner=FALLBACK_RUNNER), git_repo) assert not report.ok and report.dirty is dirty assert ('bwrap binary missing' in report.results[0].tail) is not dirty @@ -147,8 +151,7 @@ def test_runner_preserves_executable_symlink(git_repo, tmp_path, monkeypatch, ba assert report.ok, report.results[0].tail -def test_runner_timeout(git_repo, monkeypatch): - git(git_repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') +def test_runner_timeout(git_repo, monkeypatch, fetched_base): # noqa: F811 original = sandbox._proc.run def run(argv, **kwargs): if argv[0] == sys.executable: @@ -163,21 +166,17 @@ def run(argv, **kwargs): @pytest.mark.parametrize('change', ['fallback', 'base']) -def test_runner_reuse_binds_execution_context(git_repo, bwrap_log, change): # noqa: F811 +def test_runner_reuse_binds_execution_context(git_repo, bwrap_log, fetched_base, change): # noqa: F811 from dataclasses import replace (git_repo / '.git/info/exclude').write_text('.loopzero/\n') - base = git(git_repo, 'rev-parse', 'HEAD').strip() - git(git_repo, 'update-ref', 'refs/remotes/origin/main', base) command = 'echo stage-ran; exit 7' if change == 'fallback' else 'echo one' cfg = make_config(checks=(command,), inputs={command: ('README.md',)}) - body = ('import json,sys;r=json.load(sys.stdin);r.pop("env");' - 'r.update(exit_code=0,duration_s=0,not_started=True,tail="");print(json.dumps(r))') - runner = (sys.executable, '-c', body) + runner = FALLBACK_RUNNER if change == 'fallback': passing = sandbox.run_checks(replace(cfg, checks=('echo seed',)), git_repo) result = replace(passing.results[0], command=command, - input_key=sandbox._input_key(cfg, git_repo, command, base)) + input_key=sandbox._input_key(cfg, git_repo, command, fetched_base)) _save_report(git_repo, replace(passing, results=(result,))) else: cfg = replace(cfg, check_runner=runner) From 44fa248898d0606505eb099f036166764878930e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:18:49 +0100 Subject: [PATCH 07/10] Bound Mergify candidate conditions in timeout output Architecture-Review: unchanged; the timeout diagnostic keeps the same queue state, candidate link and verdict. Co-Authored-By: Codex --- src/loopzero/cli.py | 7 ++++++- tests/test_cli.py | 26 +++++++++++++------------- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 48a64159..dbc55661 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1442,7 +1442,12 @@ def _mergify_timeout_detail( ) detail = f"still queued in {queue}. {location}" if state.unmet_conditions: - detail += ". Unmet candidate conditions: " + "; ".join(state.unmet_conditions) + labels = [label.encode() for label in state.unmet_conditions[:4]] + shown = [label[:160].decode(errors="ignore") + ("…" if len(label) > 160 else "") + for label in labels] + detail += ". Unmet candidate conditions: " + "; ".join(shown) + if omitted := len(state.unmet_conditions) - len(shown): + detail += f"; {omitted} more" return detail diff --git a/tests/test_cli.py b/tests/test_cli.py index c09d043c..4a6725b5 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4583,23 +4583,23 @@ def test_mergify_reports_current_queue_attempt(wt, gh, capsys, monkeypatch, conf assert (f"{URL}#issuecomment-43" in out) is (kind == "current") -@pytest.mark.parametrize("result", ["blocking", "neutral", "skipped", None]) -def test_mergify_timeout_reports_evaluated_candidate_conditions(wt, gh, capsys, monkeypatch, result): +@pytest.mark.parametrize(("result", "extra"), [("blocking", 0), ("neutral", 0), ("skipped", 0), (None, 0), ("blocking", 1), ("blocking", 30)]) +def test_mergify_timeout_reports_evaluated_candidate_conditions(wt, gh, capsys, monkeypatch, result, extra): commit_mergify_configuration(wt) - head = head_of(wt) - arm_approved_ready_pr(gh, head, wt, isDraft=False) + arm_approved_ready_pr(gh, head_of(wt), wt, isDraft=False) monkeypatch.setattr(mergify, "configured", lambda *_: True) - monkeypatch.setattr(mergify, "markers", lambda *_: (True, False)) - monkeypatch.setattr(mergify, "mark_confirmed", lambda *_: None) - responses = iter([None, MERGIFY_QUEUE_FIXTURE["candidate_responses"][result or "missing"]]) - monkeypatch.setattr(mergify, "api_get", lambda *_: next(responses)) - + monkeypatch.setattr(mergify, "markers", lambda *_: (True, True)) + payload = MERGIFY_QUEUE_FIXTURE["candidate_responses"][result or "missing"] + if extra: + conditions = payload["mergeability_check"]["conditions_evaluation"] + label = {"match": False, "label": "界" * 3000} + monkeypatch.setitem(conditions, "subconditions", conditions["subconditions"] + [label] * extra) + monkeypatch.setattr(mergify, "api_get", lambda *_: payload) code, out, err = run(capsys, "merge", "--wait=0") - - assert (code, err) == (3, "") - assert f"https://github.com/{REPO}/pull/42" in out - assert (MERGIFY_QUEUE_FIXTURE["candidate_condition"] in out) is (result == "blocking") + assert (code, err) == (3, "") and f"https://github.com/{REPO}/pull/42" in out + assert (MERGIFY_QUEUE_FIXTURE["candidate_condition"] in out) == (result == "blocking") assert "failed" not in out and "check-success = checks" not in out + assert len(out.encode()) < 2048 and ("27 more" in out) == (extra == 30) @pytest.mark.parametrize("queue_state", ["unsafe", "error", "safe", "becomes_unsafe"]) From b0b358b03181f1b51e0dde529b3ed0414091820f Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:27:53 +0100 Subject: [PATCH 08/10] Accept the reviewer patch options in native inspection evidence A reviewer that reruns the exact patch command with --text, --ignore-submodules=none and --submodule=short is now recorded as a verified inspection, and ARCHITECTURE.md states the narrower guarantee. Refs #1101 Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 5 +++-- src/loopzero/runners.py | 3 ++- tests/test_runners.py | 6 ++++++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0fbb8a3f..bf8ae655 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -185,8 +185,9 @@ commit identity stays in the JSON material header. Explicit UTF-8 stdin carries that header, a newline and the Git patch, including carriage returns and the final newline. UTF-8 patches are supplied verbatim. For other patches, the prompt escapes invalid bytes and literal backslashes so the changes stay -visible. The native inspection digest always binds the original Git bytes. Git diffs -every file as text, ignoring attributes and diff drivers the PR could set. +visible. The native inspection digest always binds the original Git bytes. Git forces +text hunks for every file (overriding `-diff`, `binary` and NUL detection) and +runs no external diff command or text conversion, so changed lines stay visible. Chunked review summarizes only files whose Git header reports a deletion. The runner probes the selected Codex binary with `--version` and records its stdout in runner provenance and the saved review receipt. A failed probe uses diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index f23227ca..340948c5 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -799,7 +799,8 @@ def _inspection_commands(command, cwd): args = [ part for part in group[1:] - if part not in {"--no-color", "--no-ext-diff", "--no-textconv"} + if part not in {"--no-color", "--no-ext-diff", "--no-textconv", "--text", + "--ignore-submodules=none", "--submodule=short"} ] if len(args) != 2 or not all(_hex(part, 40) for part in args): return [] diff --git a/tests/test_runners.py b/tests/test_runners.py index 6b864ba9..efbe346f 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -1186,6 +1186,12 @@ def timeout(*args, **kwargs): assert len(detail.splitlines()[-1]) <= runners.TAIL_CHARS and "waiting for proxy" not in fallback +def test_inspection_accepts_the_reviewer_patch_command() -> None: + command = (f"git -C /repo diff --no-color --no-ext-diff --no-textconv --text " + f"--ignore-submodules=none --submodule=short {'a' * 40} {'b' * 40}") + assert runners._inspection_commands(command, "/repo") == [("diff", "a" * 40, "b" * 40)] + + def test_split_diff_respects_budget_and_summarizes_deleted_file() -> None: deleted = ( "diff --git a/gone.py b/gone.py\n" From b36d5a7c71802ff4ab375bfaf23227a77ac0185d Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:37:34 +0100 Subject: [PATCH 09/10] Keep the existing Mergify fixture setup mergeable Co-Authored-By: Codex --- tests/test_cli.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 4a6725b5..7256c245 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4583,21 +4583,21 @@ def test_mergify_reports_current_queue_attempt(wt, gh, capsys, monkeypatch, conf assert (f"{URL}#issuecomment-43" in out) is (kind == "current") -@pytest.mark.parametrize(("result", "extra"), [("blocking", 0), ("neutral", 0), ("skipped", 0), (None, 0), ("blocking", 1), ("blocking", 30)]) -def test_mergify_timeout_reports_evaluated_candidate_conditions(wt, gh, capsys, monkeypatch, result, extra): +@pytest.mark.parametrize("result", ["blocking", "neutral", "skipped", None, "long", "many"]) +def test_mergify_timeout_reports_evaluated_candidate_conditions(wt, gh, capsys, monkeypatch, result): commit_mergify_configuration(wt) - arm_approved_ready_pr(gh, head_of(wt), wt, isDraft=False) + head = head_of(wt) + arm_approved_ready_pr(gh, head, wt, isDraft=False) monkeypatch.setattr(mergify, "configured", lambda *_: True) monkeypatch.setattr(mergify, "markers", lambda *_: (True, True)) - payload = MERGIFY_QUEUE_FIXTURE["candidate_responses"][result or "missing"] - if extra: + payload = MERGIFY_QUEUE_FIXTURE["candidate_responses"]["blocking" if result in {"long", "many"} else result or "missing"] + if extra := {"long": 1, "many": 30}.get(result, 0): conditions = payload["mergeability_check"]["conditions_evaluation"] - label = {"match": False, "label": "界" * 3000} - monkeypatch.setitem(conditions, "subconditions", conditions["subconditions"] + [label] * extra) + monkeypatch.setitem(conditions, "subconditions", conditions["subconditions"] + [{"match": False, "label": "界" * 3000}] * extra) monkeypatch.setattr(mergify, "api_get", lambda *_: payload) code, out, err = run(capsys, "merge", "--wait=0") assert (code, err) == (3, "") and f"https://github.com/{REPO}/pull/42" in out - assert (MERGIFY_QUEUE_FIXTURE["candidate_condition"] in out) == (result == "blocking") + assert (MERGIFY_QUEUE_FIXTURE["candidate_condition"] in out) == (result in {"blocking", "long", "many"}) assert "failed" not in out and "check-success = checks" not in out assert len(out.encode()) < 2048 and ("27 more" in out) == (extra == 30) From ac76ad772bb958de524481815a3fcf0af31c821f Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:46:44 +0100 Subject: [PATCH 10/10] Keep the reviewer diff tests out of the shared import block Moves the two runner imports into the test that uses them, so this branch merges cleanly with main's concurrent import change. Refs #1101 Co-Authored-By: Claude Opus 5.5 --- tests/test_worktree.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 1a25a33a..409267fd 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -7,8 +7,7 @@ import pytest -from loopzero import runners, worktree -from loopzero.runners import split_diff +from loopzero import worktree from tests.conftest import git @@ -227,11 +226,12 @@ def test_diff_since_shows_changes_the_reviewed_files_try_to_hide(git_repo: Path) def test_split_diff_summarizes_only_files_git_reports_deleted(git_repo: Path) -> None: + from loopzero.runners import render_patch, split_diff # keeps the shared import block untouched base = _commit_files(git_repo, {"gone.py": b"old\n", "padded.py": b"old\n", "carriage.py": b"old\n"}) _commit_files(git_repo, {"gone.py": None, "padded.py": b"new = 'padded hunk'\n++ /dev/null\n" + b"x\n" * 300, "carriage.py": b"new \rdiff --git a/carriage.py b/carriage.py\rdeleted file mode 100644\r" + b"y\n" * 300}) - joined = "".join(split_diff(runners.render_patch(worktree.diff_since(git_repo, base)), 1_000)) + joined = "".join(split_diff(render_patch(worktree.diff_since(git_repo, base)), 1_000)) assert "+++ /dev/null" in joined and "+new = 'padded hunk'" in joined and "+new \r" in joined assert "gone.py: deleted, 1 lines" in joined and joined.count(": deleted, ") == 1