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
3 changes: 2 additions & 1 deletion src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -1395,7 +1395,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 lines only; hunk lines are the PR's own text.
if not re.search(r"(?m)^deleted file mode [0-7]{6}$", block.partition("\n@@")[0]):
return block
header = block.partition("\n")[0]
match = re.fullmatch(r'diff --git ("?)a/(.*)\1 \1b/\2\1', header)
Expand Down
98 changes: 96 additions & 2 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@

from __future__ import annotations

import codecs
import errno
import subprocess
import re
import stat
import tempfile
import threading
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 +246,99 @@ 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",
Comment thread
eowca marked this conversation as resolved.
Resolved
"--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]
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]{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
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:
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 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)
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


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 @@ -1280,10 +1280,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, 14, 1)
assert_git_cost(git_calls, 15, 1) # 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 @@ -1750,7 +1750,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
46 changes: 46 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,51 @@ 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():
(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()


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})
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",
".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 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
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"):
Comment thread
eowca marked this conversation as resolved.
Resolved
worktree._non_utf8_sizes(git_repo, ["b" * 40])


def test_split_diff_summarizes_only_files_git_reports_deleted(git_repo: Path) -> None:
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 \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:
wt = worktree.start(repo, "work", "main")
base = worktree.base_sha(wt)
Expand Down
Loading