From 0469418b2ad3b80a89f8afb3f787b1f63b0de9d5 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:40:50 +0100 Subject: [PATCH 1/7] Preserve exact Git patch in review material and evidence Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 4 +++- src/loopzero/_proc.py | 17 +++++++++++++---- src/loopzero/worktree.py | 12 ++++++++---- tests/test_runners.py | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 57 insertions(+), 9 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c4d03052..16c5d807 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -175,7 +175,9 @@ 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 exact UTF-8 Git patch, including carriage returns +and the final newline. A patch that cannot be decoded as UTF-8 cannot supply +exact review evidence. 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/_proc.py b/src/loopzero/_proc.py index c86dc83f..6988a7b5 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -65,16 +65,21 @@ def run( merge_output: bool = False, input: str | None = None, encoding: str | None = None, + preserve_newlines: bool = False, ) -> Completed: """Run `argv` (never through a shell) with an environment stripped to the allowlist. `merge_output=True` sends stderr into stdout so interleaving is preserved. `input` is written to the child's stdin; without it stdin is /dev/null. `encoding` overrides the parent locale for text I/O; None retains subprocess defaults. + With `preserve_newlines`, decode stdout strictly without newline translation + (UTF-8 by default). Nonzero exit is reported in `Completed.exit_code`; callers decide whether to raise. """ argv = [str(part) for part in argv] started = time.monotonic() + raw_encoding = encoding or "utf-8" + stdin = input.encode(raw_encoding) if preserve_newlines and input is not None else input try: with subprocess.Popen( argv, @@ -83,13 +88,13 @@ def run( stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT if merge_output else subprocess.PIPE, - text=True, - encoding=encoding, - errors="replace", + text=not preserve_newlines, + encoding=None if preserve_newlines else encoding, + errors=None if preserve_newlines else "replace", start_new_session=os.name == "posix", ) as proc: try: - stdout, stderr = proc.communicate(input, timeout=timeout) + stdout, stderr = proc.communicate(stdin, timeout=timeout) except BaseException: if os.name == "posix": with suppress(ProcessLookupError): @@ -112,6 +117,10 @@ def run( stderr=err or "", duration_s=elapsed, ) from exc + if isinstance(stdout, bytes): + stdout = stdout.decode(raw_encoding) + if isinstance(stderr, bytes): + stderr = stderr.decode(raw_encoding, errors="replace") return Completed( exit_code=proc.returncode, stdout=stdout or "", diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index f4a82f3a..112588b1 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -51,12 +51,16 @@ def __init__(self, command: tuple[str, ...], tail: str) -> None: super().__init__(f"{' '.join(command)} failed: {tail.strip()[-400:]}") -def _git(cwd: Path, *args: str, timeout: float = 120) -> str: +def _git(cwd: Path, *args: str, timeout: float = 120, preserve_newlines: bool = False) -> str: argv = ("git", *args) - done = run(list(argv), cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout) + try: + done = run(list(argv), cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, + preserve_newlines=preserve_newlines) + except UnicodeDecodeError as exc: + raise GitError(argv, "output is not valid UTF-8") from exc if done.exit_code != 0: raise GitError(argv, done.stderr or done.stdout) - return done.stdout.strip() + return done.stdout if preserve_newlines else done.stdout.strip() def branch_name(repo_root: Path, slug: str) -> str: @@ -244,7 +248,7 @@ def is_dirty(wt: Path) -> bool: def diff_since(wt: Path, sha: str) -> str: - return _git(Path(wt), "diff", "--no-color", sha, "HEAD") + return _git(Path(wt), "diff", "--no-color", sha, "HEAD", preserve_newlines=True) def merges_since(wt: Path, sha: str) -> list[str]: diff --git a/tests/test_runners.py b/tests/test_runners.py index 1d5b2c30..52984ee9 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -250,6 +250,39 @@ def repo(tmp_path): # ----------------------------------------------------------------- prompt +def test_committed_crlf_diff_matches_native_evidence(git_repo): + import subprocess + + from loopzero import runners, worktree + + from .conftest import git + + git(git_repo, "config", "core.autocrlf", "false") + base = worktree.head(git_repo) + (git_repo / "README.md").write_bytes(b"hello\r\n") + git(git_repo, "commit", "-am", "change line endings") + head = worktree.head(git_repo) + native = subprocess.check_output(["git", "diff", "--no-color", base, head], cwd=git_repo) + assert b"-hello\n+hello\r\n" in native + + diff = worktree.diff_since(git_repo, base) + prompt = runners.build_prompt(kind="primary", head=head, task_text="", diff=diff) + assert prompt.split("\n", 1)[1].encode() == native + context = { + "cwd": str(git_repo), "head": head, "base": base, + "diff_sha256": hashlib.sha256(diff.encode()).hexdigest(), "diff_bytes": len(diff.encode()), + } + command = f"git -C {git_repo} rev-parse HEAD && git -C {git_repo} diff --no-color {base} {head}" + item = {"type": "command_execution", "id": "read-1", "command": command} + output = head + "\n" + native.decode() + events = [ + {"type": "item.started", "item": item}, + {"type": "item.completed", + "item": dict(item, status="completed", exit_code=0, aggregated_output=output)}, + ] + assert runners._native_inspection({"events": events}, context)["diff_event"]["end"] == len(output) + + def test_prompt_frames_exact_task_and_raw_diff() -> None: prompt = build_prompt(kind="delta", head="deadbeef", task_text=" Objective ", diff="+line\n") header, diff = prompt.split("\n", 1) From 4525544fe0a1a3535618d0893bd29eebf8df3672 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:43:11 +0100 Subject: [PATCH 2/7] Keep Git patches with legacy encodings reviewable Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 3 +-- src/loopzero/_proc.py | 4 ++-- src/loopzero/worktree.py | 7 ++----- tests/test_worktree.py | 8 ++++++++ 4 files changed, 13 insertions(+), 9 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 16c5d807..70680dbf 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -176,8 +176,7 @@ 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 UTF-8 Git patch, including carriage returns -and the final newline. A patch that cannot be decoded as UTF-8 cannot supply -exact review evidence. +and the final newline. Invalid UTF-8 is displayed with replacement characters. 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/_proc.py b/src/loopzero/_proc.py index 6988a7b5..6860fb1d 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -72,7 +72,7 @@ def run( `merge_output=True` sends stderr into stdout so interleaving is preserved. `input` is written to the child's stdin; without it stdin is /dev/null. `encoding` overrides the parent locale for text I/O; None retains subprocess defaults. - With `preserve_newlines`, decode stdout strictly without newline translation + With `preserve_newlines`, decode output without newline translation (UTF-8 by default). Nonzero exit is reported in `Completed.exit_code`; callers decide whether to raise. """ @@ -118,7 +118,7 @@ def run( duration_s=elapsed, ) from exc if isinstance(stdout, bytes): - stdout = stdout.decode(raw_encoding) + stdout = stdout.decode(raw_encoding, errors="replace") if isinstance(stderr, bytes): stderr = stderr.decode(raw_encoding, errors="replace") return Completed( diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 112588b1..e2a9104e 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -53,11 +53,8 @@ def __init__(self, command: tuple[str, ...], tail: str) -> None: def _git(cwd: Path, *args: str, timeout: float = 120, preserve_newlines: bool = False) -> str: argv = ("git", *args) - try: - done = run(list(argv), cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, - preserve_newlines=preserve_newlines) - except UnicodeDecodeError as exc: - raise GitError(argv, "output is not valid UTF-8") from exc + done = run(list(argv), cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, + preserve_newlines=preserve_newlines) if done.exit_code != 0: raise GitError(argv, done.stderr or done.stdout) return done.stdout if preserve_newlines else done.stdout.strip() diff --git a/tests/test_worktree.py b/tests/test_worktree.py index a4c168a8..1001949f 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -200,6 +200,14 @@ def test_dirty_head_and_diff(repo: Path) -> None: assert worktree.is_dirty(wt) +def test_diff_retains_reviewable_text_for_non_utf8_patch(repo): + base = worktree.head(repo) + (repo / "latin1.txt").write_bytes(b"caf\xe9\r\n") + git(repo, "add", "latin1.txt") + git(repo, "commit", "-m", "add Latin-1 text") + assert worktree.diff_since(repo, base).endswith("+caf\ufffd\r\n") + + def test_task_helpers_errors(repo: Path) -> None: wt = worktree.start(repo, "tk", "main") worktree.task_file(wt).write_text("# no base line\n") From 0a0d2e2968fb496e7135c25864b621f44b9ac7cc Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:46:00 +0100 Subject: [PATCH 3/7] Hash raw patch bytes and escape legacy encodings in prompts Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 6 ++++-- src/loopzero/_proc.py | 6 +++--- src/loopzero/cli.py | 7 ++++--- src/loopzero/runners.py | 8 ++++++++ src/loopzero/worktree.py | 5 +++-- tests/test_runners.py | 31 ++++++++++++++++++++++--------- tests/test_worktree.py | 12 ++---------- 7 files changed, 46 insertions(+), 29 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 70680dbf..041c119f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -175,8 +175,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 UTF-8 Git patch, including carriage returns -and the final newline. Invalid UTF-8 is displayed with replacement characters. +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. 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/_proc.py b/src/loopzero/_proc.py index 6860fb1d..31e63dfa 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -72,8 +72,8 @@ def run( `merge_output=True` sends stderr into stdout so interleaving is preserved. `input` is written to the child's stdin; without it stdin is /dev/null. `encoding` overrides the parent locale for text I/O; None retains subprocess defaults. - With `preserve_newlines`, decode output without newline translation - (UTF-8 by default). + With `preserve_newlines`, decode without newline translation (UTF-8 by default) + and preserve undecodable stdout bytes via surrogateescape. Nonzero exit is reported in `Completed.exit_code`; callers decide whether to raise. """ argv = [str(part) for part in argv] @@ -118,7 +118,7 @@ def run( duration_s=elapsed, ) from exc if isinstance(stdout, bytes): - stdout = stdout.decode(raw_encoding, errors="replace") + stdout = stdout.decode(raw_encoding, errors="surrogateescape") if isinstance(stderr, bytes): stderr = stderr.decode(raw_encoding, errors="replace") return Completed( diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 140c24a9..f9782cf5 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -946,7 +946,8 @@ def _run_review( f"To publish the recovered head, run `loopzero pr`, then `loopzero review` " f"before merging {config.base_branch} again" ) - diff = worktree.diff_since(wt, since) + patch = worktree.diff_since(wt, since) + diff = runners.render_patch(patch) task = worktree.task_text(wt) authors = runners.author_families(wt, head, lineage_base) candidates = [family for family in config.reviewers if family not in authors] @@ -966,8 +967,8 @@ def select(family: str) -> Callable[..., ReviewResult]: model=model or (settings.model if settings else None), effort=chosen, review_context=({"repo": config.repo, "pr": publication[1], "publisher": publication[2], "head": head, "kind": kind, "base": since, - "diff_sha256": hashlib.sha256(diff.encode()).hexdigest(), - "diff_bytes": len(diff.encode())} if publication and family == "codex" else None), + "diff_sha256": hashlib.sha256(patch).hexdigest(), + "diff_bytes": len(patch)} if publication and family == "codex" else None), ) selected = {family: select(family) for family in candidates} # Settle fallback settings before any launch; an unusable one only matters if reached. diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index a6dbdd73..0a57bfb5 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -158,6 +158,14 @@ def _review_policy(kind: str, *, split: bool) -> str: ) +def render_patch(patch: bytes) -> str: + """Keep UTF-8 patches exact. Escape invalid bytes and literal backslashes otherwise.""" + try: + return patch.decode("utf-8") + except UnicodeDecodeError: + return patch.replace(b"\\", b"\\\\").decode("utf-8", errors="backslashreplace") + + def build_prompt(*, kind: str, head: str, task_text: str, diff: str, chunk: tuple[int, int] | None = None) -> str: """Frame exact review material without putting fixed reviewer policy on stdin.""" diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index e2a9104e..cc921418 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -244,8 +244,9 @@ def is_dirty(wt: Path) -> bool: return bool(_git(Path(wt), "status", "--porcelain", "--untracked-files=all")) -def diff_since(wt: Path, sha: str) -> str: - return _git(Path(wt), "diff", "--no-color", sha, "HEAD", preserve_newlines=True) +def diff_since(wt: Path, sha: str) -> bytes: + diff = _git(Path(wt), "diff", "--no-color", sha, "HEAD", preserve_newlines=True) + return diff.encode("utf-8", errors="surrogateescape") def merges_since(wt: Path, sha: str) -> list[str]: diff --git a/tests/test_runners.py b/tests/test_runners.py index 52984ee9..84485fa1 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -250,7 +250,8 @@ def repo(tmp_path): # ----------------------------------------------------------------- prompt -def test_committed_crlf_diff_matches_native_evidence(git_repo): +@pytest.mark.parametrize("legacy_encoding", [False, True]) +def test_committed_diff_preserves_git_bytes_for_native_evidence(git_repo, legacy_encoding): import subprocess from loopzero import runners, worktree @@ -258,29 +259,41 @@ def test_committed_crlf_diff_matches_native_evidence(git_repo): from .conftest import git git(git_repo, "config", "core.autocrlf", "false") + path = git_repo / "README.md" + if legacy_encoding: + path.write_bytes(b"caf\xe9\n") + git(git_repo, "commit", "-am", "add Latin-1 text") base = worktree.head(git_repo) - (git_repo / "README.md").write_bytes(b"hello\r\n") + path.write_bytes(b"caf\xe8\r\n" if legacy_encoding else b"hello\r\n") git(git_repo, "commit", "-am", "change line endings") head = worktree.head(git_repo) native = subprocess.check_output(["git", "diff", "--no-color", base, head], cwd=git_repo) - assert b"-hello\n+hello\r\n" in native - - diff = worktree.diff_since(git_repo, base) + patch = worktree.diff_since(git_repo, base) + assert patch == native + diff = runners.render_patch(patch) prompt = runners.build_prompt(kind="primary", head=head, task_text="", diff=diff) - assert prompt.split("\n", 1)[1].encode() == native + if legacy_encoding: + assert "-caf\\xe9\n+caf\\xe8\r\n" in prompt + else: + assert b"-hello\n+hello\r\n" in native + assert prompt.split("\n", 1)[1].encode() == native context = { "cwd": str(git_repo), "head": head, "base": base, - "diff_sha256": hashlib.sha256(diff.encode()).hexdigest(), "diff_bytes": len(diff.encode()), + "diff_sha256": hashlib.sha256(patch).hexdigest(), "diff_bytes": len(patch), } command = f"git -C {git_repo} rev-parse HEAD && git -C {git_repo} diff --no-color {base} {head}" item = {"type": "command_execution", "id": "read-1", "command": command} - output = head + "\n" + native.decode() + output = head + "\n" + native.decode(errors="replace") events = [ {"type": "item.started", "item": item}, {"type": "item.completed", "item": dict(item, status="completed", exit_code=0, aggregated_output=output)}, ] - assert runners._native_inspection({"events": events}, context)["diff_event"]["end"] == len(output) + inspection = runners._native_inspection({"events": events}, context) + if legacy_encoding: + assert not inspection + else: + assert inspection["diff_event"]["end"] == len(output) def test_prompt_frames_exact_task_and_raw_diff() -> None: diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 1001949f..5340c317 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -194,20 +194,12 @@ def test_dirty_head_and_diff(repo: Path) -> None: assert not worktree.is_dirty(wt) assert worktree.head(wt) != base diff = worktree.diff_since(wt, base) - assert "+print(1)" in diff and "new.py" in diff + assert b"+print(1)" in diff and b"new.py" in diff (wt / "new.py").write_text("print(2)\n") - assert "print(2)" not in worktree.diff_since(wt, base), "diff covers commits only" + assert b"print(2)" not in worktree.diff_since(wt, base), "diff covers commits only" assert worktree.is_dirty(wt) -def test_diff_retains_reviewable_text_for_non_utf8_patch(repo): - base = worktree.head(repo) - (repo / "latin1.txt").write_bytes(b"caf\xe9\r\n") - git(repo, "add", "latin1.txt") - git(repo, "commit", "-m", "add Latin-1 text") - assert worktree.diff_since(repo, base).endswith("+caf\ufffd\r\n") - - def test_task_helpers_errors(repo: Path) -> None: wt = worktree.start(repo, "tk", "main") worktree.task_file(wt).write_text("# no base line\n") From ddb222af12ec0e081225c6e11695a26e26df4258 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:46:09 +0100 Subject: [PATCH 4/7] Verify the complete Git patch in CLI and transport tests Architecture-Review: unchanged; tests exercise the documented exact Git evidence path. Co-Authored-By: Codex --- tests/test_cli.py | 4 ++-- tests/test_codex_transport.py | 14 ++++++++++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 09023284..e574b136 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1089,7 +1089,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", "origin/main", head).encode("utf-8") git_calls.clear() code, out, err = run(capsys, "review") assert_git_cost(git_calls, 16, 2) @@ -1564,7 +1564,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", first, head).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..8f6fbd1a 100644 --- a/tests/test_codex_transport.py +++ b/tests/test_codex_transport.py @@ -5,6 +5,7 @@ import dataclasses import hashlib import json +import subprocess from pathlib import Path import pytest @@ -40,8 +41,8 @@ def native(git_repo, fake_bin, fake_tool): for index,argv in enumerate([['git','-C',cwd,'rev-parse','HEAD'],['git','-C',cwd,'diff','--no-color',BASE,HEAD]]): command=' '.join(argv);item={'id':'read-'+str(index),'type':'command_execution','command':command} print(json.dumps({'type':'item.started','item':dict(item,status='in_progress')})) - done=subprocess.run(argv,capture_output=True,text=True) - print(json.dumps({'type':'item.completed','item':dict(item,status='completed',exit_code=done.returncode,aggregated_output=done.stdout)})) + done=subprocess.run(argv,capture_output=True) + print(json.dumps({'type':'item.completed','item':dict(item,status='completed',exit_code=done.returncode,aggregated_output=done.stdout.decode())})) message=json.dumps({'verdict':'approve','findings':[]}) pathlib.Path(args[args.index('--output-last-message')+1]).write_text(message) print(json.dumps({'type':'item.completed','item':{'id':'final','type':'agent_message','text':message}})) @@ -361,7 +362,8 @@ def test_large_publication_confirmation_and_hosted_agreement(native, gh, tmp_pat cfg = Config(repo, "main", ("true",), (), "squash", ("codex",), review_publishers=("bot",)) if kind.startswith("delta"): reviewed, merge_base = result.head, native[1]["base"] - (native[2] / "delta.txt").write_text("delta only\n") + git(native[2], "config", "core.autocrlf", "false") + (native[2] / "delta.txt").write_bytes(b"delta only\r\n") git(native[2], "add", "delta.txt") git(native[2], "commit", "-qm", "delta repair") head = git(native[2], "rev-parse", "HEAD").strip() @@ -376,7 +378,11 @@ 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 = subprocess.check_output( + ["git", "diff", "--no-color", reviewed, head], cwd=native[2] + ) + assert b"+delta only\r\n" in delta_diff + assert proof["calls"][0]["inspection"] == "verified" assert proof["calls"][0]["diff_sha256"] == hashlib.sha256(delta_diff).hexdigest() head = result.head prefix = ( From ab640256d74db73ab27211c745abb8c1362a62a9 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:53:32 +0100 Subject: [PATCH 5/7] Exercise patch evidence in the existing transport fixture Architecture-Review: unchanged; the compact fixtures verify the documented original patch digest. Co-Authored-By: Codex --- tests/test_codex_transport.py | 11 +++++----- tests/test_runners.py | 40 ++++++----------------------------- 2 files changed, 13 insertions(+), 38 deletions(-) diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.py index 8f6fbd1a..962b4379 100644 --- a/tests/test_codex_transport.py +++ b/tests/test_codex_transport.py @@ -42,7 +42,7 @@ def native(git_repo, fake_bin, fake_tool): command=' '.join(argv);item={'id':'read-'+str(index),'type':'command_execution','command':command} print(json.dumps({'type':'item.started','item':dict(item,status='in_progress')})) done=subprocess.run(argv,capture_output=True) - print(json.dumps({'type':'item.completed','item':dict(item,status='completed',exit_code=done.returncode,aggregated_output=done.stdout.decode())})) + print(json.dumps({'type':'item.completed','item':dict(item,status='completed',exit_code=done.returncode,aggregated_output=done.stdout.decode(errors="replace"))})) message=json.dumps({'verdict':'approve','findings':[]}) pathlib.Path(args[args.index('--output-last-message')+1]).write_text(message) print(json.dumps({'type':'item.completed','item':{'id':'final','type':'agent_message','text':message}})) @@ -353,7 +353,7 @@ def test_retired_pair_marker_cannot_pass_eligibility(native, source, include_evi ) is None -@pytest.mark.parametrize("kind", ["normal", "repost", "tampered_digest", "changed_raw", "delta"]) +@pytest.mark.parametrize("kind", ["normal", "repost", "tampered_digest", "changed_raw", "delta", "delta_legacy"]) def test_large_publication_confirmation_and_hosted_agreement(native, gh, tmp_path, fake_bin, monkeypatch, kind): from tests.test_github import pr_json, rest_pr_json, threads_json @@ -363,7 +363,8 @@ def test_large_publication_confirmation_and_hosted_agreement(native, gh, tmp_pat if kind.startswith("delta"): reviewed, merge_base = result.head, native[1]["base"] git(native[2], "config", "core.autocrlf", "false") - (native[2] / "delta.txt").write_bytes(b"delta only\r\n") + content = b"delta only\r\n" if kind == "delta" else b"caf\xe9\r\n" + (native[2] / "delta.txt").write_bytes(content) git(native[2], "add", "delta.txt") git(native[2], "commit", "-qm", "delta repair") head = git(native[2], "rev-parse", "HEAD").strip() @@ -381,8 +382,8 @@ def test_large_publication_confirmation_and_hosted_agreement(native, gh, tmp_pat delta_diff = subprocess.check_output( ["git", "diff", "--no-color", reviewed, head], cwd=native[2] ) - assert b"+delta only\r\n" in delta_diff - assert proof["calls"][0]["inspection"] == "verified" + assert b"+" + content in delta_diff + assert proof["calls"][0]["inspection"] == ("verified" if kind == "delta" else "unknown") assert proof["calls"][0]["diff_sha256"] == hashlib.sha256(delta_diff).hexdigest() head = result.head prefix = ( diff --git a/tests/test_runners.py b/tests/test_runners.py index fd531141..e2596a23 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -255,8 +255,7 @@ def repo(tmp_path): # ----------------------------------------------------------------- prompt -@pytest.mark.parametrize("legacy_encoding", [False, True]) -def test_committed_diff_preserves_git_bytes_for_native_evidence(git_repo, legacy_encoding): +def test_committed_legacy_diff_preserves_git_bytes(git_repo): import subprocess from loopzero import runners, worktree @@ -265,40 +264,15 @@ def test_committed_diff_preserves_git_bytes_for_native_evidence(git_repo, legacy git(git_repo, "config", "core.autocrlf", "false") path = git_repo / "README.md" - if legacy_encoding: - path.write_bytes(b"caf\xe9\n") - git(git_repo, "commit", "-am", "add Latin-1 text") + path.write_bytes(b"caf\xe9\n") + git(git_repo, "commit", "-am", "add Latin-1 text") base = worktree.head(git_repo) - path.write_bytes(b"caf\xe8\r\n" if legacy_encoding else b"hello\r\n") - git(git_repo, "commit", "-am", "change line endings") - head = worktree.head(git_repo) - native = subprocess.check_output(["git", "diff", "--no-color", base, head], cwd=git_repo) + path.write_bytes(b"caf\xe8\r\n") + git(git_repo, "commit", "-am", "change Latin-1 byte and line ending") + native = subprocess.check_output(["git", "diff", "--no-color", base, "HEAD"], cwd=git_repo) patch = worktree.diff_since(git_repo, base) assert patch == native - diff = runners.render_patch(patch) - prompt = runners.build_prompt(kind="primary", head=head, task_text="", diff=diff) - if legacy_encoding: - assert "-caf\\xe9\n+caf\\xe8\r\n" in prompt - else: - assert b"-hello\n+hello\r\n" in native - assert prompt.split("\n", 1)[1].encode() == native - context = { - "cwd": str(git_repo), "head": head, "base": base, - "diff_sha256": hashlib.sha256(patch).hexdigest(), "diff_bytes": len(patch), - } - command = f"git -C {git_repo} rev-parse HEAD && git -C {git_repo} diff --no-color {base} {head}" - item = {"type": "command_execution", "id": "read-1", "command": command} - output = head + "\n" + native.decode(errors="replace") - events = [ - {"type": "item.started", "item": item}, - {"type": "item.completed", - "item": dict(item, status="completed", exit_code=0, aggregated_output=output)}, - ] - inspection = runners._native_inspection({"events": events}, context) - if legacy_encoding: - assert not inspection - else: - assert inspection["diff_event"]["end"] == len(output) + assert "-caf\\xe9\n+caf\\xe8\r\n" in runners.render_patch(patch) def test_prompt_frames_exact_task_and_raw_diff() -> None: From e8a5bde8fb4b0b4034a083ab0a0edcb453ab066d Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:54:24 +0100 Subject: [PATCH 6/7] Use one transport fixture for both committed patch encodings Architecture-Review: unchanged; the transport test covers both exact and rendered patches. Co-Authored-By: Codex --- tests/test_codex_transport.py | 10 ++++++---- tests/test_runners.py | 20 -------------------- 2 files changed, 6 insertions(+), 24 deletions(-) diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.py index 962b4379..c73fc401 100644 --- a/tests/test_codex_transport.py +++ b/tests/test_codex_transport.py @@ -363,9 +363,9 @@ def test_large_publication_confirmation_and_hosted_agreement(native, gh, tmp_pat if kind.startswith("delta"): reviewed, merge_base = result.head, native[1]["base"] git(native[2], "config", "core.autocrlf", "false") - content = b"delta only\r\n" if kind == "delta" else b"caf\xe9\r\n" - (native[2] / "delta.txt").write_bytes(content) - git(native[2], "add", "delta.txt") + content = b"hello\r\n" if kind == "delta" else b"caf\xe9\r\n" + (native[2] / "README.md").write_bytes(content) + git(native[2], "add", "README.md") git(native[2], "commit", "-qm", "delta repair") head = git(native[2], "rev-parse", "HEAD").strip() git(native[2], "update-ref", "refs/remotes/origin/main", merge_base) @@ -382,7 +382,9 @@ def test_large_publication_confirmation_and_hosted_agreement(native, gh, tmp_pat delta_diff = subprocess.check_output( ["git", "diff", "--no-color", reviewed, head], cwd=native[2] ) - assert b"+" + content in delta_diff + assert b"-hello\n+" + content in delta_diff + if kind == "delta_legacy": + assert "+caf\\xe9\r\n" in runners.render_patch(delta_diff) assert proof["calls"][0]["inspection"] == ("verified" if kind == "delta" else "unknown") assert proof["calls"][0]["diff_sha256"] == hashlib.sha256(delta_diff).hexdigest() head = result.head diff --git a/tests/test_runners.py b/tests/test_runners.py index e2596a23..7fbaca25 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -255,26 +255,6 @@ def repo(tmp_path): # ----------------------------------------------------------------- prompt -def test_committed_legacy_diff_preserves_git_bytes(git_repo): - import subprocess - - from loopzero import runners, worktree - - from .conftest import git - - git(git_repo, "config", "core.autocrlf", "false") - path = git_repo / "README.md" - path.write_bytes(b"caf\xe9\n") - git(git_repo, "commit", "-am", "add Latin-1 text") - base = worktree.head(git_repo) - path.write_bytes(b"caf\xe8\r\n") - git(git_repo, "commit", "-am", "change Latin-1 byte and line ending") - native = subprocess.check_output(["git", "diff", "--no-color", base, "HEAD"], cwd=git_repo) - patch = worktree.diff_since(git_repo, base) - assert patch == native - assert "-caf\\xe9\n+caf\\xe8\r\n" in runners.render_patch(patch) - - def test_prompt_frames_exact_task_and_raw_diff() -> None: prompt = build_prompt(kind="delta", head="deadbeef", task_text=" Objective ", diff="+line\n") header, diff = prompt.split("\n", 1) From 1752ac831900f9c14093e6bfaab923849803f53a Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:14:44 +0100 Subject: [PATCH 7/7] Render the Git deletion fixture before splitting it Architecture-Review: unchanged; the deletion fixture follows the documented patch rendering path. Co-Authored-By: Codex --- tests/test_codex_transport.py | 13 +++++-------- tests/test_runners.py | 3 ++- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.py index c73fc401..4f2a728c 100644 --- a/tests/test_codex_transport.py +++ b/tests/test_codex_transport.py @@ -365,13 +365,11 @@ def test_large_publication_confirmation_and_hosted_agreement(native, gh, tmp_pat git(native[2], "config", "core.autocrlf", "false") content = b"hello\r\n" if kind == "delta" else b"caf\xe9\r\n" (native[2] / "README.md").write_bytes(content) - git(native[2], "add", "README.md") - git(native[2], "commit", "-qm", "delta repair") + git(native[2], "commit", "-qam", "delta repair") head = git(native[2], "rev-parse", "HEAD").strip() git(native[2], "update-ref", "refs/remotes/origin/main", merge_base) - task = native[2] / ".loopzero/task.md" - task.parent.mkdir() - task.write_text("Inspect the delta") + (native[2] / ".loopzero").mkdir() + (native[2] / ".loopzero/task.md").write_text("Inspect the delta") tool = fake_bin / "codex" old_range, new_range = f"{merge_base!r},{reviewed!r}", f"{reviewed!r},{head!r}" tool.write_text(tool.read_text().replace(old_range, new_range)) @@ -379,9 +377,8 @@ 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 = subprocess.check_output( - ["git", "diff", "--no-color", reviewed, head], cwd=native[2] - ) + argv = ["git", "diff", "--no-color", reviewed, head] + delta_diff = subprocess.check_output(argv, cwd=native[2]) assert b"-hello\n+" + content in delta_diff if kind == "delta_legacy": assert "+caf\\xe9\r\n" in runners.render_patch(delta_diff) diff --git a/tests/test_runners.py b/tests/test_runners.py index 7fbaca25..fe76836e 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -29,6 +29,7 @@ build_prompt, codex_evidence, merge_reviews, + render_patch, review_with, split_diff, ) @@ -1198,7 +1199,7 @@ def test_split_diff_summarizes_real_git_deletion(git_repo: Path, name: str) -> N base = git(git_repo, "rev-parse", "HEAD").strip() git(git_repo, "rm", "--", name) git(git_repo, "commit", "-qm", "delete file") - diff = worktree.diff_since(git_repo, base) + diff = render_patch(worktree.diff_since(git_repo, base)) chunks = split_diff(diff, 4096)