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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,12 @@ 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 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
RunnerBadOutput and existing family fallback before model input. Successful
Expand Down
14 changes: 6 additions & 8 deletions src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -1394,15 +1394,13 @@ 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 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]:
Expand Down
89 changes: 87 additions & 2 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@

from __future__ import annotations

import codecs
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/")
Expand Down Expand Up @@ -243,8 +245,91 @@ 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:
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 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",
"--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]
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:
# 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:
Comment thread
eowca marked this conversation as resolved.
Resolved
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: 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:
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]:
Expand Down
6 changes: 3 additions & 3 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1229,10 +1229,10 @@ 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)
assert_git_cost(git_calls, 17, 2) # includes one batched blob read classifying 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" == (
Expand Down Expand Up @@ -1704,7 +1704,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)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_codex_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand Down
2 changes: 1 addition & 1 deletion tests/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
69 changes: 69 additions & 0 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import pytest

from loopzero import worktree
from loopzero.runners import split_diff
from tests.conftest import git


Expand Down Expand Up @@ -197,6 +198,74 @@ 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:
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 "+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


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,
})

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 "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:
wt = worktree.start(repo, "work", "main")
base = worktree.base_sha(wt)
Expand Down