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 1/7] 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 2/7] 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 3/7] 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 4/7] 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 5/7] 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 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 6/7] 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 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 7/7] 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