From db11fe54778c4df18e735c6e08c82b3a6d03d8d1 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:27:31 +0100 Subject: [PATCH 1/3] Surface recoverable saved reviews before retrying Architecture-Review: unchanged; existing receipt validation and explicit repost still govern publication. Co-Authored-By: Codex --- src/loopzero/cli.py | 78 ++++++++++++++++++++++++----------- tests/test_review_recovery.py | 45 ++++++++++++++++++++ 2 files changed, 100 insertions(+), 23 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 7e70e258..3eb67f7a 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -730,24 +730,10 @@ def cmd_review(args: argparse.Namespace) -> int: kind, reviewed = _decide_kind( _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head ) + publication_context = {"repo": config.repo, "number": pr.number, "publisher": publisher} if args.repost: - authors = runners.author_families(wt, head, _primary_base(wt, config)) - excluded = [family for family in config.reviewers if family in authors] result = _load_review(wt, head, kind) - if result.fallback and result.family not in excluded: - raise CliError( - f"saved review claims a same-family fallback, but {result.family} is not a configured " - "reviewer family that contributed to this PR lineage; run without --repost" - ) - if not result.fallback and not any(family not in authors for family in config.reviewers): - raise IndependentReviewerUnavailable( - _independence_message(authors, excluded, []) - ) - if result.family in authors and not result.fallback: - raise IndependentReviewerUnavailable( - f"saved reviewer family {result.family} contributed to this PR lineage; " - "run without --repost to obtain an independent review" - ) + candidates, excluded = _repost_reviewer_families(wt, config, head, result) publication = json.loads(_review_file(wt, head, kind).read_text()).get("publication") if publication is not None: if (not isinstance(publication, dict) or publication.get("repo") != config.repo @@ -762,7 +748,6 @@ def cmd_review(args: argparse.Namespace) -> int: else: reviews = _pr_reviews(config.repo, pr.number) # Exact read-back above may confirm an older published note; a new post needs the current form. - candidates = [family for family in config.reviewers if family not in authors] if result.fallback and not _published_fallback(result.fallback, candidates, excluded): raise CliError("saved fallback note is not in the published form; run without --repost") allowed, _ = _decide_kind( @@ -771,6 +756,10 @@ def cmd_review(args: argparse.Namespace) -> int: if allowed != kind: raise CliError("saved review kind differs from the remaining review budget") else: + if args.model is None and args.effort is None and _has_recoverable_review( + wt, config, head, kind, publication_context, + ): + raise CliError(f"saved {kind} review for {head[:12]}; run `loopzero review --repost`") try: result = _run_review(wt, config, head, kind, reviewed, args.model, args.effort, runtime_source=runtime_source, publication=(config.repo, pr.number, publisher)) @@ -793,7 +782,7 @@ def cmd_review(args: argparse.Namespace) -> int: raise CliError("native publication context changed; HOLD") if args.repost: prefix = _repost_prefix(result) - _save_review(wt, result, {"repo": config.repo, "number": pr.number, "publisher": publisher}) + _save_review(wt, result, publication_context) token = _refresh_publisher_token(token, publisher) try: github.post_review( @@ -838,6 +827,47 @@ def _review_verdict(result: ReviewResult) -> int: return 0 if result.verdict == "approve" else 5 # the exit code is the verdict, as for check +def _repost_reviewer_families( + wt: Path, config: Config, head: str, result: ReviewResult, +) -> tuple[list[str], list[str]]: + authors = runners.author_families(wt, head, _primary_base(wt, config)) + excluded = [family for family in config.reviewers if family in authors] + if result.fallback and result.family not in excluded: + raise CliError( + f"saved review claims a same-family fallback, but {result.family} is not a configured " + "reviewer family that contributed to this PR lineage; run without --repost" + ) + if not result.fallback and not any(family not in authors for family in config.reviewers): + raise IndependentReviewerUnavailable( + _independence_message(authors, excluded, []) + ) + if result.family in authors and not result.fallback: + raise IndependentReviewerUnavailable( + f"saved reviewer family {result.family} contributed to this PR lineage; " + "run without --repost to obtain an independent review" + ) + return [family for family in config.reviewers if family not in authors], excluded + + +def _has_recoverable_review( + wt: Path, config: Config, head: str, kind: str, publication: dict, +) -> bool: + other_kind = "delta" if kind == "primary" else "primary" + if not _review_file(wt, head, kind).exists() or _review_file(wt, head, other_kind).exists(): + return False + try: + result = _load_review(wt, head, kind, publication=publication) + candidates, excluded = _repost_reviewer_families(wt, config, head, result) + if result.fallback and not _published_fallback(result.fallback, candidates, excluded): + return False + evidence = runners.codex_evidence(result) + except (CliError, runners.RunnerBadOutput): + return False + return evidence is None or (evidence["repo"], evidence["pr"], evidence["publisher"]) == ( + publication["repo"], publication["number"], publication["publisher"], + ) + + def _repost_prefix(result: ReviewResult) -> str: sessions = result.provenance["session_ids"] return review_marker(result.head, result.kind, "repost") + "\n" + ( @@ -1064,22 +1094,24 @@ def _save_review(wt: Path, result: ReviewResult, publication: dict | None = None _write_json_atomically(path, data) -def _load_review(wt: Path, head: str, kind: str) -> ReviewResult: +def _load_review( + wt: Path, head: str, kind: str, *, publication: dict | None = None, +) -> ReviewResult: path = _review_file(wt, head, kind) if not path.exists(): raise CliError(f"no saved {kind} review for {head[:12]} at {path}; run without --repost") try: data = json.loads(path.read_text()) - except (json.JSONDecodeError, OSError) as exc: + except (ValueError, OSError) as exc: raise CliError(f"{path} is not runner-produced: invalid saved review") from exc if not isinstance(data, dict): raise CliError(f"{path} is not runner-produced: invalid saved review") if data.get("head") != head: raise CliError(f"{path} holds a review of {str(data.get('head'))[:12]}, not HEAD {head[:12]}") try: - data.pop("publication", None) - if data.get("kind") != kind: - raise ValueError("saved review kind mismatch") + saved_publication = data.pop("publication", None) + if data.get("kind") != kind or (publication is not None and saved_publication != publication): + raise ValueError("saved review kind or publication mismatch") findings = tuple(Finding(**f) for f in data["findings"]) # Ordinary receipts written before pair retirement still carry these defaults. for field, default in (("members", []), ("reconciliation", ""), diff --git a/tests/test_review_recovery.py b/tests/test_review_recovery.py index 203f247e..e87a7c8a 100644 --- a/tests/test_review_recovery.py +++ b/tests/test_review_recovery.py @@ -75,6 +75,51 @@ def assert_single_publication(gh, fake_bin): assert len([c for c in gh.calls if "--input" in c]) == 1 +@pytest.mark.parametrize("override", [None, "pr", "head", "raw", "bytes", "effort"]) +def test_plain_review_surfaces_receipt_after_interruption_before_post( + wt, gh, fake_bin, monkeypatch, capsys, override, +): + head = support.prepare_review(wt, gh, fake_bin) + reviewer = fake_bin / "claude" + reviewer.write_text(reviewer.read_text().replace( + "#!/bin/sh\n", f'#!/bin/sh\nprintf "run\\n" >> "{fake_bin}/claude.runs"\n')) + original = github.post_review + + def interrupt(*args, **kwargs): + raise KeyboardInterrupt + + monkeypatch.setattr(github, "post_review", interrupt) + assert run(capsys, "review")[0] == 130 + monkeypatch.setattr(github, "post_review", original) + + path = cli._review_file(wt, head, "primary") + saved = path.read_bytes() + if override in {"pr", "head", "raw"}: + payload = json.loads(saved) + if override == "pr": + payload["publication"]["number"] = 999 + else: + payload[override] = "invalid" + path.write_text(json.dumps(payload)) + if override == "bytes": + path.write_bytes(b"\xff") + args = ["--effort", "high"] if override == "effort" else [] + code, _out, err = run(capsys, "review", *args) + + if override is None: + assert code == 1 and "loopzero review --repost" in err + assert path.read_bytes() == saved + assert not any("--input" in c for c in gh.calls) + assert run(capsys, "review", "--repost")[0] == 0 + assert (fake_bin / "claude.runs").read_text().splitlines() == ["run"] + assert sum( + c["argv"][1] == support.post_key().split()[1] and "--input" in c for c in gh.calls + ) == 1 + else: + assert code == 0, err + assert (fake_bin / "claude.runs").read_text().splitlines() == ["run", "run"] + + @pytest.mark.parametrize("kind", ["primary", "delta"]) @pytest.mark.parametrize("verdict", [0, 5]) @pytest.mark.parametrize("interrupted", [False, True, "timeout"]) From 6008661b90103c2bbd941fcfd2293df3e39f6dd8 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:23:59 +0100 Subject: [PATCH 2/3] Document check and sandbox exit codes Architecture-Review: unchanged; the contract clarifies existing outcomes without changing execution or trust boundaries. Co-Authored-By: Codex --- core/CONTRACT.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/core/CONTRACT.md b/core/CONTRACT.md index 958e94fe..d7a75362 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -10,9 +10,8 @@ own delivery state; `.loopzero/` holds task text and local receipts. problem, context, acceptance, base SHA. Write the PR, like any issue or design doc you write, for the project owner under [Reporting](#reporting). 2. Implement, commit, then `loopzero check`: run `workflow.toml` - `[checks].commands` in the sandbox. Its exit code is the verdict. For a long - check under a [provider-portable handoff](../docs/DELEGATION.md#provider-portable-handoff), - open the draft in step 3 before starting the check. + `[checks].commands` in the sandbox. Open the draft before a long check under a + [provider-portable handoff](../docs/DELEGATION.md#provider-portable-handoff). 3. `loopzero pr` pushes and opens a **draft** PR from the task text plus generated Validation checks. Later calls sync narrative, preserving live Validation, Review and extra sections; `check` refreshes only its checks @@ -286,6 +285,12 @@ meta-directives; reviewers load no instruction files or skills from the reviewed Fail closed on missing tools and command errors, preserve the failing command and output tail, and keep a short, safe detail about the cause or stage when operator-facing code wraps an error. Stop on terminal failures or quota errors. +`check` exits 0 when stages pass, including local dirty runs that cannot satisfy +readiness. Exit 1 can mean a failed stage, a discarded or unverified result, or +a command error. Read the diagnostic and verify the receipt before classifying +the failure. Exit 2 covers invalid arguments and sandbox unavailability in +`check` or fresh `review`. + Exit 3 means waiting or timeout. Review exits 4 when independent review is unavailable and 5 when changes are requested. Interruption exits 130. From e9357260c0da03fa89256cfc08254e5edc179c9d Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:53:06 +0100 Subject: [PATCH 3/3] Fit exit-code clarification within core docs cap Architecture-Review: unchanged; the contract retains delivery semantics while shortening surrounding prose. Co-Authored-By: Codex --- core/CONTRACT.md | 33 ++++++++++++++------------------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/core/CONTRACT.md b/core/CONTRACT.md index d7a75362..5575666c 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -16,18 +16,15 @@ own delivery state; `.loopzero/` holds task text and local receipts. generated Validation checks. Later calls sync narrative, preserving live Validation, Review and extra sections; `check` refreshes only its checks block. Drafts need no clean review. -4. `loopzero review` reviews the exact head, independently by default, and - posts one GitHub review with inline findings: exit 0 `approve`, - 5 `request_changes`. -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 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. +4. `loopzero review` defaults to independent review of the exact head and posts + one GitHub review with inline findings. Approval exits 0, changes requested 5. +5. `loopzero ready --wait` marks eligible PRs ready and activates drafts with + only missing/skipped checks even with mergeability pending. Activation without a + wait exits 3. Both waiters use `--wait[=SECONDS]` (default 1800) on the same + head. Zero can activate or enqueue. 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 of missing checks with + none pending, inspect scheduling, triggers and permissions, then retry. 6. After step 5 exits 0, run from a durable directory such as `/tmp` using the absolute path to the task worktree. @@ -36,10 +33,9 @@ own delivery state; `.loopzero/` holds task text and local receipts. ``` Merge rechecks readiness, uses the configured strategy, verifies the landed - SHA, and deletes the branch and worktree. If cleanup warns, the merge landed. - Follow the recovery step it names. A queue initially enqueues; - `--wait` shares a budget across source-check and landing waits. Enqueueing - without `--wait` returns 0 without cleanup. + SHA and deletes the branch and worktree. A cleanup warning follows a verified + merge. Follow its recovery step. Queueing without `--wait` exits 0 without + cleanup. With `--wait`, source checks and landing share one budget. Merge is authorized by default under [merge authority](#merge-authority). @@ -282,9 +278,8 @@ meta-directives; reviewers load no instruction files or skills from the reviewed ## Failure -Fail closed on missing tools and command errors, preserve the failing command -and output tail, and keep a short, safe detail about the cause or stage when -operator-facing code wraps an error. Stop on terminal failures or quota errors. +Fail closed on missing tools or command errors. Preserve the command and output +tail, name the cause or stage safely, and stop on terminal failures or quota errors. `check` exits 0 when stages pass, including local dirty runs that cannot satisfy readiness. Exit 1 can mean a failed stage, a discarded or unverified result, or a command error. Read the diagnostic and verify the receipt before classifying