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
5 changes: 4 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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
Expand Down
17 changes: 13 additions & 4 deletions src/loopzero/_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 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]
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,
Expand All @@ -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):
Expand All @@ -112,6 +117,10 @@ def run(
stderr=err or "",
duration_s=elapsed,
) from exc
if isinstance(stdout, bytes):
stdout = stdout.decode(raw_encoding, errors="surrogateescape")
if isinstance(stderr, bytes):
stderr = stderr.decode(raw_encoding, errors="replace")
return Completed(
exit_code=proc.returncode,
stdout=stdout or "",
Expand Down
19 changes: 13 additions & 6 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,10 @@ def _is_ancestor(wt: Path, sha: str, head: str) -> bool:
["git", "merge-base", "--is-ancestor", sha, head],
cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT,
)
if done.exit_code not in (0, 1):
detail = _proc.tail(done.stderr or done.stdout, 1)
raise CliError(f"git merge-base --is-ancestor failed (exit {done.exit_code}): "
f"{detail or 'retry the ancestry check'}")
return done.exit_code == 0


Expand Down Expand Up @@ -668,17 +672,19 @@ def cmd_pr(args: argparse.Namespace) -> int:
)
existing = _sync_task_narrative(wt, pr.body or "") if pr is not None else None
body = _pr_body(wt, head, config, existing)
force_lease = pr is not None and pr.state == "OPEN" and not _is_ancestor(wt, pr.head_sha, head)
force_lease = False
push = ["push", "-u", "origin"]
if force_lease:
if pr is not None and pr.state == "OPEN":
# Only rewrite history this worktree has seen; an unknown remote head is someone else's.
known = _proc.run(["git", "cat-file", "-e", f"{pr.head_sha}^{{commit}}"], cwd=wt,
env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT)
if known.exit_code != 0:
raise CliError(
f"PR head {pr.head_sha[:12]} is not in this worktree; fetch and integrate it first"
)
push.extend(("--porcelain", f"--force-with-lease={branch}:{pr.head_sha}"))
force_lease = not _is_ancestor(wt, pr.head_sha, head)
if force_lease:
push.extend(("--porcelain", f"--force-with-lease={branch}:{pr.head_sha}"))
push.append(branch)
_git_push(wt, push, force_lease=force_lease)
if pr is not None and pr.state == "OPEN":
Expand Down Expand Up @@ -995,7 +1001,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]
Expand All @@ -1015,8 +1022,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.
Expand Down
8 changes: 8 additions & 0 deletions src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,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."""
Expand Down
15 changes: 11 additions & 4 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,17 @@ 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, preserve_whitespace: bool = False) -> str:
def _git(
cwd: Path, *args: str, timeout: float = 120,
preserve_whitespace: bool = False, preserve_newlines: bool = False,
) -> str:
argv = ("git", *args)
done = run(list(argv), cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout)
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)
if preserve_newlines:
return done.stdout
return done.stdout.removesuffix("\n") if preserve_whitespace else done.stdout.strip()


Expand Down Expand Up @@ -243,8 +249,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")
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]:
Expand Down
41 changes: 39 additions & 2 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1044,6 +1044,43 @@ def test_pr_updates_existing_open_pr(wt: Path, gh: FakeGh, capsys) -> None:
assert "(no `loopzero check` run recorded)" in gh.calls[-1]["--input"]


@pytest.mark.parametrize(
("probe", "diagnostic"),
[
("kill -TERM $$", "exit -15"),
("echo 'fatal: unable to read commit' >&2; exit 128", "unable to read commit"),
],
)
def test_pr_aborts_on_ancestry_probe_error(wt, gh, fake_tool, tmp_path, capsys, probe, diagnostic):
gh.respond_pr_list([pr_json(headRefOid=head_of(wt))])
gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {})
pushes = tmp_path / "pushes"
fake_tool("git", f'''\
if [ "$1" = "merge-base" ] && [ "$2" = "--is-ancestor" ]; then {probe}; fi
if [ "$1" = "push" ]; then touch "{pushes}"; exit 0; fi
exec /usr/bin/git "$@"
''')

code, out, err = run(capsys, "pr")

assert (code, out) == (1, "")
assert "git merge-base --is-ancestor" in err and diagnostic in err
assert not pushes.exists()
assert all("--method" not in call["argv"] for call in gh.calls)


def test_pr_aborts_on_missing_remote_head(wt, gh, fake_tool, tmp_path, capsys):
gh.respond_pr_list([pr_json(headRefOid="a" * 40)])
pushes = trace_pushes(fake_tool, tmp_path)

code, out, err = run(capsys, "pr")

assert (code, out) == (1, "")
assert "fetch and integrate it first" in err
assert not pushes.exists()
assert all("--method" not in call["argv"] for call in gh.calls)


@pytest.mark.parametrize("hook_fails", [False, True])
def test_pr_uses_lease_for_rewritten_open_pr(
wt: Path, repo: Path, gh: FakeGh, fake_tool, tmp_path: Path, capsys, hook_fails: bool
Expand Down Expand Up @@ -1192,7 +1229,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)
Expand Down Expand Up @@ -1667,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", 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)
Expand Down
14 changes: 10 additions & 4 deletions tests/test_codex_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import dataclasses
import hashlib
import json
import subprocess
from pathlib import Path

import pytest
Expand Down Expand Up @@ -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}}))
Expand Down Expand Up @@ -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()
Expand All @@ -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 = (
Expand Down
46 changes: 46 additions & 0 deletions tests/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,52 @@ 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):
import subprocess

from loopzero import runners, worktree

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


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)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,9 @@ 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)


Expand Down
Loading