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 @@ -189,7 +189,10 @@ commit identity stays in the JSON material header. Explicit UTF-8 stdin carries
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.
visible. The native inspection digest always binds the original Git bytes. Git forces
text hunks for every file (overriding `-diff`, `binary` and NUL detection) and
runs no external diff command or text conversion, so changed lines stay visible.
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
17 changes: 15 additions & 2 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,9 +325,22 @@ def _readiness(
def _check_report_problem(
report: CheckReport | None, wt: Path, config: Config, head: str, *, require_pass: bool = True,
) -> str | None:
if (report is None or report.head != head or report.dirty or (require_pass and not report.ok)
or tuple(result.command for result in report.results) != config.checks):
if report is None:
return "run loopzero check at this head"
if report.head != head:
return f"check receipt is for {report.head[:12]}. Run `loopzero check` at {head[:12]}."
if report.dirty:
return ("check receipt was recorded in a dirty worktree. Run `git status --short`, "
"settle the changes, then run `loopzero check`.")
commands = tuple(result.command for result in report.results)
if (require_pass and not report.ok) or commands != config.checks:
if not commands or commands[-1] == sandbox.INCOMPLETE_CHECK_COMMAND:
return "check receipt is incomplete. Run `loopzero check` to resume with the current workflow."
if require_pass and not report.ok:
return ("check receipt records a failed stage. Fix the failure, then run `loopzero check`. "
"Retry unchanged only if the failure was transient.")
return ("check receipt's plan differs from the trusted workflow. "
"Run `loopzero check` with the current workflow.")
recovery = ("Run loopzero check in this worktree at this head with the same current CLI and effective "
"settings as ready, using a local coordinator for delegated stages.")
if report.settings_sha256 is None:
Expand Down
6 changes: 4 additions & 2 deletions src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -813,7 +813,8 @@ def _inspection_commands(command, cwd):
args = [
part
for part in group[1:]
if part not in {"--no-color", "--no-ext-diff", "--no-textconv"}
if part not in {"--no-color", "--no-ext-diff", "--no-textconv", "--text",
"--ignore-submodules=none", "--submodule=short"}
]
if len(args) != 2 or not all(_hex(part, 40) for part in args):
return []
Expand Down Expand Up @@ -1384,7 +1385,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
5 changes: 4 additions & 1 deletion src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,13 +169,16 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
return CheckReport(head=head, dirty=dirty, results=tuple(results), settings_sha256=settings_sha256)


INCOMPLETE_CHECK_COMMAND = "<checks incomplete>"


def _checkpoint_success(checkpoint: Callable[[CheckReport], None] | None,
report: CheckReport, previous: dict[str, CheckResult],
remaining: tuple[str, ...]) -> None:
stage = report.results[-1]
if checkpoint is not None and stage.input_key and stage.exit_code == 0:
# Even the last stage leaves a nonpassing receipt until final validation.
incomplete = CheckResult("<checks incomplete>", 1, 0.0, "")
incomplete = CheckResult(INCOMPLETE_CHECK_COMMAND, 1, 0.0, "")
unvisited = tuple(previous[command] for command in remaining if command in previous)
checkpoint(replace(report, results=(*report.results, *unvisited, incomplete)))

Expand Down
5 changes: 4 additions & 1 deletion src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,10 @@ def is_dirty(wt: Path) -> bool:


def diff_since(wt: Path, sha: str) -> bytes:
diff = _git(Path(wt), "diff", "--no-color", sha, "HEAD", preserve_newlines=True)
# Show every file as text, whatever attributes or NUL bytes the reviewed head adds,
# without diff drivers, and keep submodule pointers even if .gitmodules ignores them.
diff = _git(Path(wt), "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--text",
"--ignore-submodules=none", "--submodule=short", sha, "HEAD", preserve_newlines=True)
return diff.encode("utf-8", errors="surrogateescape")


Expand Down
35 changes: 20 additions & 15 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import subprocess
import sys
from contextlib import suppress
from dataclasses import replace
from dataclasses import asdict, replace
from pathlib import Path
from select import select
from types import SimpleNamespace
Expand Down Expand Up @@ -3022,7 +3022,7 @@ def test_ready_requires_clean_successful_local_report_at_head(
if condition == "wrong-head":
report["head"] = "0" * 40
elif condition == "wrong-commands":
report["results"][0]["command"] = "true"
report["results"].pop()
elif condition == "legacy":
del report["settings_sha256"]
else:
Expand All @@ -3036,8 +3036,10 @@ def test_ready_requires_clean_successful_local_report_at_head(
assert f"not ready: {reason}." in out
assert ("Run loopzero check in this worktree at this head with the same current CLI and effective "
"settings as ready, using a local coordinator for delegated stages." in out)
elif condition == "wrong-commands":
assert "not ready: check receipt's plan differs from the trusted workflow." in out
elif condition != "matching":
assert out.endswith("not ready: run loopzero check at this head\n")
assert ("not ready: run loopzero check at this head" if condition == "missing" else "not ready: check receipt") in out


@pytest.mark.parametrize("wait_for", [None, "ready", "merge"])
Expand Down Expand Up @@ -3764,7 +3766,7 @@ def test_status_silently_ignores_legacy_report_without_dirty(

assert code == 0 and err == ""
assert "ready: no" in out
assert " - run loopzero check at this head" in out
assert " - check receipt was recorded in a dirty worktree." in out


def test_gh_errors_are_one_line_on_stderr(wt: Path, gh: FakeGh, capsys) -> None:
Expand Down Expand Up @@ -4594,22 +4596,25 @@ def broken(*args, **kwargs):
assert run(capsys, command)[0] == 0


@pytest.mark.parametrize("invalid", ["stale", "red", "dirty", "commands"])
def test_invalid_receipt_is_not_announced(wt, gh, capsys, head, invalid):
@pytest.mark.parametrize("field,value,reason", [
("head", "a" * 40, "check receipt is for aaaaaaaaaaaa."),
("exit_code", 1, "check receipt records a failed stage."),
("dirty", True, "check receipt was recorded in a dirty worktree."),
("command", "changed", "check receipt's plan differs from the trusted workflow."),
("results", [], "check receipt is incomplete."),
("results", "checkpoint", "check receipt is incomplete."),
])
def test_invalid_receipt_is_not_announced(wt, gh, capsys, head, field, value, reason):
arm_approved_ready_pr(gh, head, wt)
path = wt / ".loopzero/checks.json"
data = json.loads(path.read_text())
if invalid == "stale":
data["head"] = "a" * 40
elif invalid == "dirty":
data["dirty"] = True
elif invalid == "red":
data["results"][0]["exit_code"] = 1
else:
data["results"][0]["command"] = "changed"
target = data["results"][0] if field in {"exit_code", "command"} else data
if value == "checkpoint":
value = [data["results"][0], asdict(CheckResult("<checks incomplete>", 1, 0.0, ""))]
target[field] = value
path.write_text(json.dumps(data))
code, out, _ = run(capsys, "ready")
assert code == 1 and "run loopzero check at this head" in out
assert code == 1 and f"not ready: {reason}" in out
assert "receipt accepted:" not in out


Expand Down
6 changes: 6 additions & 0 deletions tests/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -1270,6 +1270,12 @@ def timeout(*args, **kwargs):
assert len(detail.encode()) < 450 and ("…" in detail) == bool(size)


def test_inspection_accepts_the_reviewer_patch_command() -> None:
command = (f"git -C /repo diff --no-color --no-ext-diff --no-textconv --text "
f"--ignore-submodules=none --submodule=short {'a' * 40} {'b' * 40}")
assert runners._inspection_commands(command, "/repo") == [("diff", "a" * 40, "b" * 40)]


def test_split_diff_respects_budget_and_summarizes_deleted_file() -> None:
deleted = (
"diff --git a/gone.py b/gone.py\n"
Expand Down
31 changes: 31 additions & 0 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,37 @@ 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"})
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",
".gitmodules": b'[submodule "a-sub"]\n\tpath = a-sub\n\tignore = all\n'})
diff = worktree.diff_since(git_repo, base)
assert b"Binary files" not in diff and f"+Subproject commit {base}".encode() in diff
assert b"+new = 'attr hunk'" in diff and b"+new = 'nul hunk'\x00" in diff and b"+\x89PNG\r" in diff


def test_split_diff_summarizes_only_files_git_reports_deleted(git_repo: Path) -> None:
from loopzero.runners import render_patch, split_diff # keeps the shared import block untouched
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(render_patch(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