diff --git a/core/CONTRACT.md b/core/CONTRACT.md index c9d164e7..a70b9875 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -23,9 +23,10 @@ own delivery state; `.loopzero/` holds task text and local receipts. 5. `loopzero ready --wait` marks ready PRs ready for review. It also activates drafts blocked only by missing/skipped checks to trigger CI, even with mergeability pending. Without waiting, activation exits 3. - Both waiters observe the unchanged head while all blockers can settle, - with `--wait[=SECONDS]` (default 1800). Pending mergeability can block with - green checks and gets its own timeout message (exit 3). + Both waiters use `--wait[=SECONDS]` (default 1800) on the unchanged head. + Zero seconds can still activate or enqueue a PR. Pending mergeability can + time out (exit 3) with green checks. `loopzero merge --cancel` requests + Mergify removal without `--wait`. Green can precede CI scheduling. After two minutes with only missing checks and none pending, inspect scheduling, triggers and permissions, then retry. 6. After step 5 exits 0, run from a durable directory such as `/tmp` diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3e5a69c5..462bb23c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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 diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index a0890dd2..aed8f2c9 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -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: diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 29bd50fc..da743ea5 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -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 [] @@ -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) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index a127887c..b212a2a7 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -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 = "" + + 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("", 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))) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 7bf653e3..720e78b8 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -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") diff --git a/tests/test_cli.py b/tests/test_cli.py index 81376235..ca25c35f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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 @@ -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: @@ -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"]) @@ -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: @@ -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("", 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 diff --git a/tests/test_runners.py b/tests/test_runners.py index 2cfa34e8..25760c30 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -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" diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 230adc02..d4c30478 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -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)