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/3] 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/3] 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/3] 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"})