From 614b36e00b4568638f3ac80c6be6ee075f4358b4 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:53:18 +0100 Subject: [PATCH 1/8] Review conflict resolutions in the available delta round Co-Authored-By: Codex --- core/CONTRACT.md | 8 ++-- docs/ARCHITECTURE.md | 5 +++ src/loopzero/candidate.py | 4 +- src/loopzero/cli.py | 49 ++++++++++---------- src/loopzero/eligibility.py | 53 ++++++++++++++-------- tests/test_cli.py | 90 +++++++++++++++++++++++++++++-------- 6 files changed, 145 insertions(+), 64 deletions(-) diff --git a/core/CONTRACT.md b/core/CONTRACT.md index 958e94fe..28ccf2ec 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -206,9 +206,11 @@ version. Loop-zero serves internal projects only and does not target tamper resistance for outside users. Freeze new work on Codex evidence projections. Simplify or delete them when they break or obstruct delivery. -- One primary and at most one delta per PR. The delta reads only - changes since the primary; unresolved primary findings still count under - Blockers. +- One primary and at most one delta per PR. After a base merge, the delta + receives first-parent topic patches and the changes from each automatic + remerge to its recorded merge tree. Merged parents must come from the verified + base, and the reviewed commit must be on the first-parent history. Unresolved + primary findings still count under Blockers. - Default: one writing model family per PR, including delegates and repairs; another may advise read-only and review independently. Before committing imported work, record every actual writing delegate in truthful diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 49620cba..0da84c65 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -103,6 +103,11 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con the PR-wide cap of one primary and one delta across head rewrites, and the [owner-approved contributor-review exception](../core/CONTRACT.md#owner-approved-contributor-review-exception), which changes neither the selector nor the budget. + The delta requires the reviewed commit on the current head's first-parent + history and verifies merged parents against the live configured base. The + runner receives topic patches in first-parent order and the difference + between each automatic remerge and its recorded tree. Isolated Git verifies + the history and builds the patch, excluding unrelated base changes. 5. `ready` derives readiness from the current head, its check receipt, an eligible review at that head or an eligible review covering an ancestor, blocking findings (unresolved threads a review publisher opened with a head-bound marker line), diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index fed9dee8..775d29ad 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -324,7 +324,7 @@ def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: } deadline = time.monotonic() + _TREE_SECONDS - def git(*args: str, command_env: dict[str, str] = env) -> str: + def git(*args: str, command_env: dict[str, str] = env, preserve_newlines: bool = False) -> str: with (root / "output").open("w+b") as output: process = subprocess.Popen( [sys.executable, "-I", "-S", "-c", _LIMITED_GIT, str(_TREE_BYTES), @@ -353,6 +353,8 @@ def store_size() -> int: # Git renames temporaries: skip files that vanish output.seek(0) result = output.read(_TREE_OUTPUT + 1) _require(len(result) <= _TREE_OUTPUT, "Git object/output bound exceeded") + if preserve_newlines: + return result.decode("utf-8", errors="surrogateescape") return result.decode().strip() finally: if process.poll() is None: diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f1645fb8..9fcb00c4 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -848,11 +848,12 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: 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( + allowed, reviewed = _decide_kind( _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head ) if allowed != kind: raise CliError("saved review kind differs from the remaining review budget") + _delta_patch(wt, config, reviewed, head, pr.number) else: try: result = _run_review(wt, config, head, kind, reviewed, args.model, args.effort, @@ -1003,12 +1004,27 @@ def _confirm_review(wt: Path, config: Config, pr: github.PR, result: ReviewResul return True -def _delta_merge_recovery(wt: Path, reviewed: str, merge: str) -> str: - pre_merge = _git(wt, "rev-parse", f"{merge}^1") - if not _is_ancestor(wt, reviewed, pre_merge): - return f"replay the fixes on the reviewed head {reviewed[:12]}" - return (f"save the current tip on a backup branch, use `git reset --hard {pre_merge}`, " - "and cherry-pick any later fixes from the backup") +def _delta_patch(wt: Path, config: Config, since: str | None, head: str, number: int | None) -> bytes: + if since is None: + return b"" + if not _is_ancestor(wt, since, head): + raise CliError( + f"reviewed head {since[:12]} is not an ancestor of this branch. Find the original tip with `git reflog`. " + "Back up your branch, reset to that tip and replay later fixes. To publish the restored head, " + f"run `loopzero pr`, then `loopzero review` before merging {config.base_branch}, or open a new PR" + ) + if not worktree.merges_since(wt, since): + return worktree.diff_since(wt, since) + patch = (eligibility.base_merge_material(config.repo, number, since, head, config.base_branch, clean=False) + if number is not None else None) + if patch is None: + raise CliError( + f"could not verify merge history: {since[:12]} must be on the first-parent history and " + f"merged parents must come from {config.base_branch}. Save your work, then replay the fixes " + f"on the reviewed head {since[:12]}, including resolution edits. Push with `loopzero pr` " + "and run `loopzero review`, or open a new PR" + ) + return patch def _run_review( @@ -1018,23 +1034,8 @@ def _run_review( ) -> ReviewResult: lineage_base = _primary_base(wt, config) since = reviewed if kind == "delta" else lineage_base - if kind == "delta" and not _is_ancestor(wt, since, head): - raise CliError( - f"reviewed head {since[:12]} is not an ancestor of this branch. Find the original " - "branch tip with `git reflog`. Save the current tip on a backup branch, then use " - "`git reset --hard ` and replay any later fixes. To publish the restored " - f"head, run `loopzero pr`, then `loopzero review` before merging {config.base_branch}, or open a new PR " - "from the current branch" - ) - if kind == "delta" and (merges := worktree.merges_since(wt, since)): - recovery = _delta_merge_recovery(wt, since, merges[0]) - raise CliError( - f"merge commit {merges[0][:12]} since the reviewed head {since[:12]} would put the " - f"merged-in changes in the delta material. To recover, {recovery}. " - f"To publish the recovered head, run `loopzero pr`, then `loopzero review` " - f"before merging {config.base_branch} again" - ) - patch = worktree.diff_since(wt, since) + patch = (_delta_patch(wt, config, since, head, publication[1] if publication else None) + if kind == "delta" else worktree.diff_since(wt, since)) diff = runners.render_patch(patch) task = worktree.task_text(wt) authors = runners.author_families(wt, head, lineage_base) diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 965efd5d..671d4f38 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -9,6 +9,7 @@ import json import re import sys +from collections.abc import Callable from pathlib import Path from loopzero import candidate, config, github, runners @@ -95,36 +96,52 @@ def eligible_review(reviews: list[dict], head: str, publishers: tuple[str, ...], return latest if verdict else None -def _clean_base_merges(repo: str, number: int, reviewed: str, head: str, base_branch: str) -> bool: - """Prove each intervening first-parent commit is an unmodified merge from the base.""" +def _verified_merge(git: Callable[..., str], merge: str, first: str, second: str, + base: str, *, clean: bool) -> bool: + git("merge-base", "--is-ancestor", second, base) + merge_bases = git("merge-base", "--all", first, second).splitlines() + # A shallow root outside the known merge bases could hide another base. + if git("rev-list", "--max-parents=0", first, second, "--not", *merge_bases): + return False + return not clean or git("merge-tree", "--write-tree", first, second) == git("rev-parse", f"{merge}^{{tree}}") + + +def base_merge_material( + repo: str, number: int, reviewed: str, head: str, base_branch: str, *, clean: bool, +) -> bytes | None: + """Return a verified delta patch, or empty bytes for proven clean inheritance.""" try: pr = github.api_get(f"repos/{repo}/pulls/{number}") base = pr["base"]["sha"] if (pr["head"]["sha"] != head or pr["base"]["ref"] != base_branch or not re.fullmatch(r"[0-9a-f]{40}", base)): - return False + return None with candidate.fetched_git(repo, [reviewed, head, base]) as git: history = git("rev-list", "--first-parent", "--parents", f"{reviewed}..{head}") cursor = head + row_lengths = {3} if clean else {2, 3} for row in history.splitlines(): commits = row.split() - if len(commits) != 3 or commits[0] != cursor: - return False - merge, first, second = commits - git("merge-base", "--is-ancestor", second, base) - merge_bases = git("merge-base", "--all", first, second).splitlines() - # A shallow root outside the known merge bases could hide another base. - if git("rev-list", "--max-parents=0", first, second, "--not", *merge_bases): - return False - tree = git("merge-tree", "--write-tree", first, second) - if tree != git("rev-parse", f"{merge}^{{tree}}"): - return False - cursor = first - return cursor == reviewed + if len(commits) not in row_lengths or commits[0] != cursor: + return None + cursor = commits[1] + if len(commits) == 2: + continue + if not _verified_merge(git, *commits, base, clean=clean): + return None + if cursor != reviewed: + return None + if clean: + return b"" + patch = git("log", "--first-parent", "--reverse", "--remerge-diff", "-p", "--format=", + "--no-color", "--no-ext-diff", "--no-textconv", "--text", + "--ignore-submodules=none", "--submodule=short", + f"{reviewed}..{head}", preserve_newlines=True) + return patch.encode("utf-8", errors="surrogateescape") except github.GhUnavailable: raise except (candidate.CandidateError, github.GhError, KeyError, OSError, TypeError, ValueError): - return False + return None def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...], *, @@ -158,7 +175,7 @@ def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...] return None elif not (verdict.startswith("approve** (") and state in {"APPROVED", "COMMENTED"}): return None - if not _clean_base_merges(repo, number, reviewed, head, base_branch): + if base_merge_material(repo, number, reviewed, head, base_branch, clean=True) is None: return None return latest diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c136d5d..93bd1152 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -194,6 +194,21 @@ def head_of(path: Path) -> str: return git(path, "rev-parse", "HEAD").strip() +@pytest.fixture +def isolated_git(wt, monkeypatch, fake_tool): + """Use real isolated Git fetches against the test worktree.""" + fake_tool("prlimit", "exit 127\n") + popen = subprocess.Popen + + def fetch_from_worktree(argv, **kwargs): + if "fetch" in argv: + argv = [wt.as_uri() if arg == f"https://github.com/{REPO}.git" else arg for arg in argv] + return popen(argv, **kwargs) + + monkeypatch.setenv("GH_TOKEN", "test-token") + monkeypatch.setattr(subprocess, "Popen", fetch_from_worktree) + + @pytest.fixture def head(wt: Path) -> str: return head_of(wt) @@ -1791,35 +1806,74 @@ def test_review_delta_diffs_since_primary(wt: Path, gh: FakeGh, fake_bin: Path, assert marker(head, "delta") in payload["body"] -def test_review_delta_refuses_base_merge_since_primary(wt, repo, gh, fake_bin, capsys) -> None: - reviewed = head_of(wt) # intelflo#8393: primary-reviewed head, a merge of main, the delta - (repo / "upstream.py").write_text("y = 1\n") - git(repo, "add", "upstream.py") - git(repo, "commit", "-q", "-m", "landed on main") - git(wt, "merge", "-q", "--no-edit", "main") - merge = head_of(wt) - git(wt, "commit", "-q", "--allow-empty", "-m", "fix after review") - prepare_review(wt, gh, fake_bin, history=[rev(reviewed, "primary", state="CHANGES_REQUESTED")]) - code, out, err = run(capsys, "review") - assert code != 0 and out == "" and not (fake_bin / "claude.stdin").exists() - assert f"merge commit {merge[:12]} since the reviewed head {reviewed[:12]}" in err - assert f"`git reset --hard {reviewed}`" in err - assert "cherry-pick any later fixes" in err - assert "run `loopzero pr`, then `loopzero review` before merging main again" in err +def conflict_merge(wt, repo): + (wt / "README.md").write_text("branch edit\n") + git(wt, "commit", "-qam", "edit on branch") + reviewed = head_of(wt) + (repo / "README.md").write_text("base edit\n") + (repo / "upstream.py").write_text("upstream = 1\n") + git(repo, "add", "README.md", "upstream.py") + git(repo, "commit", "-qm", "landed on main") + with pytest.raises(subprocess.CalledProcessError) as exc: + git(wt, "merge", "--no-edit", "main") + assert "CONFLICT" in exc.value.stdout + (wt / "README.md").write_text("distinct resolution\n") + git(wt, "commit", "-qam", "resolve base merge") + return reviewed + + +@pytest.mark.parametrize("verified", [True, False]) +def test_review_delta_after_conflict_merge(wt, repo, gh, fake_bin, capsys, isolated_git, verified): + reviewed = conflict_merge(wt, repo) + (wt / ".gitmodules").write_text('[submodule "dep"]\npath = dep\nurl = ../dep\nignore = all\n') + git(wt, "add", ".gitmodules") + git(wt, "update-index", "--add", "--cacheinfo", f"160000,{reviewed},dep") + commit_file(wt, "topic.py", "topic = 2\n", "topic repair") + history = [rev(reviewed, "primary")] + head = prepare_review(wt, gh, fake_bin, history=history) + detail = rest_pr_json(pr_json(headRefOid=head, isDraft=False)) + detail["base"]["sha"] = git(repo, "rev-parse", "main" if verified else "main^").strip() + gh.respond(f"api repos/{REPO}/pulls/7", detail) + + code, _, err = run(capsys, "review") + + if not verified: + assert code == 1 and not (fake_bin / "claude.stdin").exists() + assert "could not verify merge history" in err and "including resolution edits" in err + return + assert code == 0, err + header, diff = (fake_bin / "claude.stdin").read_bytes().split(b"\n", 1) + assert json.loads(header)["head"] == head + assert b"+distinct resolution" in diff and b"+topic = 2" in diff and b"upstream.py" not in diff + assert f"+Subproject commit {reviewed}".encode() in diff and diff.endswith(b"+topic = 2\n") + posted = posted_review(gh) + assert posted["commit_id"] == head and marker(head, "delta") in posted["body"] + + exact = rev(head, "delta") + exact["body"] = posted["body"] + for reviews, ready in ((history, False), ([*history, exact], True)): + arm_approved_pr_with_check_result(gh, head, wt, "success", reviews=reviews, isDraft=False) + gh.respond(f"api repos/{REPO}/pulls/7", detail) + assert run(capsys, "ready")[0] == (0 if ready else 1) + assert cli.eligibility.evaluate(REPO, 7, head, "main", (LOGIN,)).ready is ready def test_review_delta_replays_fixes_when_reviewed_head_is_second_parent( - wt: Path, gh: FakeGh, fake_bin: Path, capsys + wt: Path, gh: FakeGh, fake_bin: Path, capsys, isolated_git ) -> None: reviewed = head_of(wt) git(wt, "reset", "--hard", "main") git(wt, "commit", "-q", "--allow-empty", "-m", "independent branch work") git(wt, "merge", "-q", "--no-edit", reviewed) - prepare_review(wt, gh, fake_bin, history=[rev(reviewed, "primary", state="CHANGES_REQUESTED")]) + head = prepare_review(wt, gh, fake_bin, history=[rev(reviewed, "primary", state="CHANGES_REQUESTED")]) + detail = rest_pr_json(pr_json(headRefOid=head)) + detail["base"]["sha"] = reviewed # Even a verified base parent cannot substitute for the first parent. + gh.respond(f"api repos/{REPO}/pulls/7", detail) _fake_codex(fake_bin, json.dumps(APPROVE)) _, err = expect_cli(capsys, 1, "review") - assert f"replay the fixes on the reviewed head {reviewed[:12]}" in err + assert f"{reviewed[:12]} must be on the first-parent history" in err + assert f"on the reviewed head {reviewed[:12]}, including resolution edits" in err assert "git reset --hard" not in err assert not (fake_bin / "claude.stdin").exists() assert not (fake_bin / "codex.stdin").exists() From 5c8d0e3a9cef984f390e6060fa8828512fd4d8dc Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:56:05 +0100 Subject: [PATCH 2/8] Refresh trusted publishers before local readiness Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 7 ++++-- src/loopzero/cli.py | 7 ++++-- src/loopzero/config.py | 19 ++++++++++---- tests/test_cli.py | 57 +++++++++++++++++++++++++++++++++++++++--- 4 files changed, 78 insertions(+), 12 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 49620cba..a8878d44 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -45,8 +45,11 @@ The CLI also writes a head-bound checks receipt and saved review output in `.loopzero/` for local readiness and reposting. They do not form a second authoritative delivery history; new Codex native audit receipts have the restricted retention requirement described below. Local readiness requires its current successful check receipt; hosted eligibility evaluates GitHub -review evidence using trusted base configuration. Losing local artifacts may -require rerunning checks or review, and never creates a hosted approval. +review evidence using trusted base configuration. Local readiness and merge fetch +the configured origin base once at startup before loading its publisher policy. +A receipt bound to the base may require a new check after that base advances. +Losing local artifacts may require rerunning checks or review, and never creates +a hosted approval. Saved runner artifacts also retain the repository, PR and actual request publisher before publication. A lost POST reply triggers a read-only reconciliation bounded by one 30-second transport deadline, with no read retries. Recovery regenerates diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f1645fb8..d2c3aba3 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -125,6 +125,7 @@ def _repo_root(wt: Path) -> Path: def _load_config( args: argparse.Namespace, root: Path, *, pin_checks: bool = False, previous: Config | None = None, + refresh: bool = False, ) -> Config: path = args.config or root / "workflow.toml" if not pin_checks: @@ -132,7 +133,7 @@ def _load_config( if args.config: print("checks are unpinned because --config was provided") return config_mod.load(path) - config = config_mod.load_trusted(root, previous=previous) + config = config_mod.load_trusted(root, previous=previous, refresh=refresh) if args.command == "check": if not config.checks: raise config_mod.ConfigError( @@ -145,7 +146,9 @@ def _load_config( def _context(args: argparse.Namespace, *, pin_checks: bool = False) -> tuple[Path, Config]: wt = _toplevel() - return wt, _load_config(args, wt, pin_checks=pin_checks) + return wt, _load_config( + args, wt, pin_checks=pin_checks, refresh=args.command in {"ready", "merge"}, + ) def _is_ancestor(wt: Path, sha: str, head: str) -> bool: diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 81388cfa..a6f72af2 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -108,12 +108,21 @@ def _has_replacement_refs(common_dir: Path) -> bool: return b" refs/replace/" in packed -def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tuple[Config, str]: +def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, refresh: bool) -> tuple[Config, str]: source = f"origin/{branch}:workflow.toml" hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override." + ref = f"refs/remotes/origin/{branch}" + if refresh: + fetched = _proc.run( + ["git", "fetch", "--quiet", "--no-tags", "--no-recurse-submodules", + "--no-write-fetch-head", "origin", f"+refs/heads/{branch}:{ref}"], + cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, + ) + if fetched.exit_code != 0: + raise ConfigError(f"could not refresh origin/{branch}. {hint}") directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else [] resolved = _proc.run( - ["git", "rev-parse", *directory_args, "--verify", f"refs/remotes/origin/{branch}^{{commit}}"], + ["git", "rev-parse", *directory_args, "--verify", f"{ref}^{{commit}}"], cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, ) if resolved.exit_code != 0: @@ -140,7 +149,7 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tu raise ConfigError(f"{source}: {exc}. {hint}") from None -def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config: +def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: bool = False) -> Config: """Select delivery policy using Git's origin default and its trusted workflow.""" prefix = "refs/remotes/origin/" default = _proc.run( @@ -154,10 +163,10 @@ def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config: "or supply --config for bootstrap or an override." ) branch = ref.removeprefix(prefix) - policy, revision = _remote_workflow(worktree, branch, previous) + policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh) if policy.base_branch == branch: return replace(policy, trusted_base_revision=revision) - base, revision = _remote_workflow(worktree, policy.base_branch, previous) + base, revision = _remote_workflow(worktree, policy.base_branch, previous, refresh=refresh) if base.base_branch != policy.base_branch: raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config") return replace(base, trusted_base_revision=revision) diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c136d5d..a88db423 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2192,7 +2192,7 @@ def test_ready_marks_draft_ready(wt: Path, gh: FakeGh, capsys, head, branch, git gh.respond("pr ready", "") git_calls.clear() code, out, err = run(capsys, "ready") - assert_git_cost(git_calls, 7, 1) + assert_git_cost(git_calls, 8, 1) assert (code, err) == (0, "") and out.endswith(f"ready: {URL}\n") assert ["pr", "ready", "7", "--repo", REPO] in [c["argv"] for c in gh.calls] @@ -2467,7 +2467,7 @@ def after_sleep(): @pytest.mark.parametrize("command", ["ready", "merge"]) @pytest.mark.parametrize("settled", ["CONFLICTING", "MERGEABLE", "UNKNOWN"]) -def test_wait_for_github_mergeability(wt, gh, capsys, monkeypatch, command, settled): +def test_wait_for_github_mergeability(wt, gh, capsys, monkeypatch, command, settled, git_calls): head = commit_mergify_configuration(wt) arm_approved_ready_pr(gh, head, wt, mergeable="UNKNOWN", isDraft=False) gh.respond_pr_view(pr_json(headRefOid=head, mergeable=settled, isDraft=False, @@ -2478,18 +2478,69 @@ def test_wait_for_github_mergeability(wt, gh, capsys, monkeypatch, command, sett monkeypatch.setattr(cli, "_wait_for_mergify", lambda *_: None) poll_clock(monkeypatch) + git_calls.clear() code, out, err = run(capsys, command, "--wait=1") + assert sum(call[0] == "fetch" for call in git_calls) == 1 if settled == "CONFLICTING": assert code == 1 and "has merge conflicts" in out + err elif settled == "UNKNOWN": - assert code == 3 and out.endswith(f"timed out waiting for GitHub to compute mergeability on {head[:12]}. Run `loopzero {command} --wait` to resume on this head.\n") + assert code == 3 and out.endswith(f"timed out waiting for GitHub to compute mergeability on {head[:12]}. Run `loopzero {command} --wait` to resume on this head.\n"), (code, out, err) else: assert code == (0 if command == "ready" else 3) assert requests == ([(REPO, 7, head, "main")] if command == "merge" and settled == "MERGEABLE" else []) +@pytest.mark.parametrize("publisher,expected", [ + ("retired-publisher", "pending"), ("replacement-publisher", "success"), +]) +def test_readiness_and_hosted_use_current_base_publishers(wt, gh, head, tmp_path, monkeypatch, capsys, + publisher, expected): + git(tmp_path, "clone", "-q", str(tmp_path / "origin.git"), "trusted") + trusted = tmp_path / "trusted" + workflow = trusted / "workflow.toml" + retired_workflow = (WORKFLOW.replace('required_ci = ["checks"]', + 'required_ci = ["checks", "Loop-zero Eligibility"]') + + 'review_publishers = ["retired-publisher"]\n') + workflow.write_text(retired_workflow) + git(trusted, "commit", "-qam", "trust old review publisher") + git(trusted, "push", "-q", "origin", "main") + git(wt, "fetch", "-q", "origin", "main") + stale = git(wt, "rev-parse", "origin/main") + + arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=False, review_login=publisher) + gh.respond(f"api repos/{REPO}/commits/{head}/statuses", + [{"context": "Loop-zero Eligibility", "state": "success"}]) + workflow.write_text(retired_workflow.replace("retired-publisher", "replacement-publisher")) + git(trusted, "commit", "-qam", "rotate review publisher") + git(trusted, "push", "-q", "origin", "main") + assert git(wt, "rev-parse", "origin/main") == stale + assert git(trusted, "rev-parse", "HEAD") != stale + + code, out, _ = run(capsys, "ready") + assert code == (0 if expected == "success" else 1) + assert (github.MISSING_REVIEW_REASON in out) == (expected == "pending") + if expected == "pending": + git(wt, "remote", "set-url", "origin", str(tmp_path / "unavailable.git")) + code, _, err = run(capsys, "ready") + assert code == 1 and "could not refresh origin/main" in err + explicit = tmp_path / "explicit.toml" + explicit.write_text(retired_workflow) + assert run(capsys, "--config", str(explicit), "ready")[0] == 0 + + event = trusted / "event.json" + event.write_text(json.dumps({"inputs": {"pr": "7"}})) + monkeypatch.chdir(trusted) + monkeypatch.setenv("GITHUB_REPOSITORY", REPO) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) + gh.respond(f"api repos/{REPO}/statuses/{head}", {}) + assert hosted.main() == 0 + payload = json.loads(gh.calls[-1]["--input"]) + assert gh.calls[-1]["argv"][1] == f"repos/{REPO}/statuses/{head}" + assert payload["state"] == expected + + @pytest.mark.parametrize("command,check,hold_at_admission", [ ("ready", "success", False), ("ready", "skipped", False), ("merge", "success", False), ("merge", "success", True), From 1e737f6470f5b55bc79a278d2ecd4e2e42607f5b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:07:27 +0100 Subject: [PATCH 3/8] Exercise fetched remote state in readiness fixtures Co-Authored-By: Codex --- tests/test_cli.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index a88db423..98ba15cd 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1445,13 +1445,16 @@ def test_review_runtime_paths_use_only_verified_base( def test_runtime_pinning_requires_trusted_workflow( wt: Path, gh: FakeGh, fake_bin: Path, capsys, command: str, missing: str, ) -> None: + origin = Path(git(wt, "remote", "get-url", "origin").strip()) if missing == "default": git(wt, "symbolic-ref", "--delete", "refs/remotes/origin/HEAD") elif missing == "remote": git(wt, "update-ref", "-d", "refs/remotes/origin/main") + git(origin, "update-ref", "-d", "refs/heads/main") else: - git(wt, "update-ref", "refs/remotes/origin/main", - git(wt, "rev-list", "--max-parents=0", "HEAD").strip()) + initial = git(wt, "rev-list", "--max-parents=0", "HEAD").strip() + git(wt, "update-ref", "refs/remotes/origin/main", initial) + git(origin, "update-ref", "refs/heads/main", initial) prepare_review(wt, gh, fake_bin) code, out, err = run(capsys, command) assert "reviewer paths" not in out + err @@ -2151,7 +2154,7 @@ def test_ready_after_reviewed_head( popen = subprocess.Popen def isolated_fetch(argv, **kwargs): - if "fetch" in argv: + if "fetch" in argv and f"https://github.com/{REPO}.git" in argv: if history == "missing history": raise cli.eligibility.candidate.CandidateError("history unavailable") argv = [wt.as_uri() if arg == f"https://github.com/{REPO}.git" else arg for arg in argv] @@ -3167,6 +3170,7 @@ def test_merged_bare_primary_cleans_only_clean_linked_worktree( repo: Path, gh: FakeGh, capsys, monkeypatch, state ) -> None: primary = repo.parent / "origin.git" + git(primary, "remote", "add", "origin", str(primary)) linked = repo.parent / "linked task" git(primary, "worktree", "add", "-q", "-b", "lz/bare", str(linked), "main") monkeypatch.chdir(linked) @@ -3696,7 +3700,7 @@ def test_commands_refuse_base_branch(wt: Path, gh: FakeGh, capsys, base) -> None git(wt, "checkout", "-q", "--ignore-other-worktrees", base) else: publish_workflow(wt, workflow.read_text()) - git(wt, "update-ref", f"refs/remotes/origin/{base}", "refs/remotes/origin/main") + git(wt, "push", "-q", "origin", f"origin/main:refs/heads/{base}") git(wt, "checkout", "-q", "-b", base) for command in ("pr", "review", "ready", "merge"): code, out, err = run(capsys, command) From 9e53d8fba5ac2c26264323e139a13854fb38e7de Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:15:50 +0100 Subject: [PATCH 4/8] Keep malformed reviewer output in a private diagnostic file Architecture-Review: unchanged; the command data flow and delivery roles still apply. Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 2 +- src/loopzero/cli.py | 40 ++++++++++++++++++++------------- src/loopzero/runners.py | 49 +++++++++++++++++++++++------------------ tests/test_cli.py | 29 ++++++++++++++++++++++++ tests/test_runners.py | 6 +++-- 5 files changed, 87 insertions(+), 39 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 49620cba..e25d3c38 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -57,7 +57,7 @@ verdict. Pending, dismissed, conflicting or changing evidence blocks recovery. only an explicit retry after complete absence may publish again. The existing self-review rejection fallback to COMMENT remains a separate transport rule. -Private review receipts and sidecars live under the task worktree's `.loopzero/` and disappear when guarded merge cleanup removes the worktree. GitHub retains the published review evidence. +Private review receipts, sidecars and malformed output excerpts live under the task worktree's `.loopzero/` and disappear when guarded merge cleanup removes the worktree. GitHub retains the published review evidence. Private agent transcripts and metrics ledgers do not belong in this guide or in a new persistent store. diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f1645fb8..7b7c2f70 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1039,7 +1039,7 @@ def _run_review( 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] - failures: list[str] = [] + errors: dict[str, tuple[str, str]] = {} excluded = [family for family in config.reviewers if family in authors] def select(family: str) -> Callable[..., ReviewResult]: settings = config.review.get(family) @@ -1073,7 +1073,7 @@ def select(family: str) -> Callable[..., ReviewResult]: attempts = candidates + excluded for index, family in enumerate(attempts): if family in unusable: - failures.append(unusable[family]) + errors[family] = unusable[family], "" continue if family in excluded and not fallback: fallback = ("independent reviewers failed: " + "; ".join(reasons) @@ -1095,33 +1095,43 @@ def select(family: str) -> Callable[..., ReviewResult]: break except RUNNER_FAILURES as exc: reason, detail, fallback_reason = _review_failure(family, exc) - failures.append(detail) + errors[family] = detail, exc.tail if isinstance(exc, runners.RunnerMalformedOutput) else "" reasons.append(f"{family}: {fallback_reason}") if any(next_family in selected for next_family in attempts[index + 1:]): print(f"reviewer {family} unavailable: {reason}", file=sys.stderr) else: raise IndependentReviewerUnavailable( - _independence_message(authors, excluded, failures) + _independence_message(authors, excluded, [detail for detail, _ in errors.values()]) + + _save_review_failure_output(wt, head, kind, errors) ) return dataclasses.replace(result, fallback=fallback) +def _save_review_failure_output(wt: Path, head: str, kind: str, errors: dict[str, tuple[str, str]]) -> str: + if not (fragments := {family: tail for family, (_, tail) in errors.items() if tail}): + return "" + path = wt / ".loopzero" / f"reviewer-output-{head[:12]}-{kind}.json" + try: + with _lock_task_state(wt) as directory: + _write_json_atomically(directory, path.name, fragments) + except OSError as exc: + return f"\nCould not save reviewer output: {exc.strerror or exc}" + return f"\nReviewer output: {path.relative_to(wt)}" + + def _review_failure(family: str, exc: Exception) -> tuple[str, str, str]: lines = str(exc).splitlines() - detail = "\n".join(lines[:3]) - fallback_reason = _FALLBACK_REASONS[3] + detail = "\n".join(lines[:1 if isinstance(exc, runners.RunnerMalformedOutput) else 3]) if isinstance(exc, runners.RunnerAuthFailed): login = "claude auth login" if family == "claude" else "codex login" - detail += f"\nFix: run `{login}`." - fallback_reason = _FALLBACK_REASONS[0] - elif isinstance(exc, runners.RunnerUsageLimit): - detail += "\nFix: wait for the limit to reset or switch this reviewer's account." - fallback_reason = _FALLBACK_REASONS[1] - elif isinstance(exc, runners.RunnerMissing): + return lines[0], detail + f"\nFix: run `{login}`.", _FALLBACK_REASONS[0] + if isinstance(exc, runners.RunnerUsageLimit): + fix = "\nFix: wait for the limit to reset or switch this reviewer's account." + return lines[0], detail + fix, _FALLBACK_REASONS[1] + if isinstance(exc, runners.RunnerMissing): package = "@anthropic-ai/claude-code" if family == "claude" else "@openai/codex" - detail += f"\nFix: install it with `npm install -g {package}`." - fallback_reason = _FALLBACK_REASONS[2] - return lines[0], detail, fallback_reason + return lines[0], detail + f"\nFix: install it with `npm install -g {package}`.", _FALLBACK_REASONS[2] + return lines[0], detail, _FALLBACK_REASONS[3] def _independence_message( diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 9f9cc584..7ae7aee9 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -87,6 +87,10 @@ def __init__(self, message: str, tail: str = "") -> None: self.tail = tail +class RunnerMalformedOutput(RunnerBadOutput): + """The runner returned a payload that could not be parsed as a review.""" + + class RunnerPromptTooLong(RunnerBadOutput): """The provider rejected the prompt for exceeding its context window.""" @@ -214,33 +218,34 @@ def _claude_payload(envelope: dict) -> object: return _extract_json_object(str(envelope.get("result", ""))) if payload is None else payload -def parse_review(payload: object, *, family: str, head: str, kind: str, raw: str) -> ReviewResult: +def parse_review(payload: object, *, family: str, head: str, kind: str, raw: str, excerpt: str | None = None) -> ReviewResult: """Validate a decoded review object against the findings schema.""" + diagnostic = _tail(raw if excerpt is None else excerpt) if not isinstance(payload, dict): - raise RunnerBadOutput(f"{family}: review is not a JSON object", _tail(raw)) + raise RunnerMalformedOutput(f"{family}: review is not a JSON object", diagnostic) if set(payload) != {"verdict", "findings"}: - raise RunnerBadOutput(f"{family}: review has unexpected or missing keys", _tail(raw)) + raise RunnerMalformedOutput(f"{family}: review has unexpected or missing keys", diagnostic) verdict, items = payload["verdict"], payload["findings"] if ( not isinstance(verdict, str) or verdict not in ("approve", "request_changes") or not isinstance(items, list) ): - raise RunnerBadOutput(f"{family}: review lacks verdict/findings", _tail(raw)) + raise RunnerMalformedOutput(f"{family}: review lacks verdict/findings", diagnostic) findings: list[Finding] = [] for item in items: required = {"severity", "path", "line", "title", "body"} if not isinstance(item, dict) or set(item) != required: - raise RunnerBadOutput(f"{family}: finding has unexpected or missing keys", _tail(raw)) + raise RunnerMalformedOutput(f"{family}: finding has unexpected or missing keys", diagnostic) if not isinstance(item["severity"], str) or item["severity"] not in SEVERITIES: - raise RunnerBadOutput(f"{family}: finding has bad severity", _tail(raw)) + raise RunnerMalformedOutput(f"{family}: finding has bad severity", diagnostic) path, line = item["path"], item["line"] if path is not None and not isinstance(path, str): - raise RunnerBadOutput(f"{family}: finding path is not a string", _tail(raw)) + raise RunnerMalformedOutput(f"{family}: finding path is not a string", diagnostic) if line is not None and (isinstance(line, bool) or not isinstance(line, int)): - raise RunnerBadOutput(f"{family}: finding line is not an integer", _tail(raw)) + raise RunnerMalformedOutput(f"{family}: finding line is not an integer", diagnostic) if not isinstance(item["title"], str) or not isinstance(item["body"], str): - raise RunnerBadOutput(f"{family}: finding title/body must be strings", _tail(raw)) + raise RunnerMalformedOutput(f"{family}: finding title/body must be strings", diagnostic) findings.append(Finding(**item)) if any(f.severity in BLOCKING for f in findings): verdict = "request_changes" @@ -533,7 +538,7 @@ def _repository_skill_paths(cwd: Path) -> set[str]: def _claude_provenance(envelope: dict, raw: str) -> dict[str, object]: required = ("session_id", "usage", "total_cost_usd", "duration_api_ms") if any(name not in envelope for name in required): - raise RunnerBadOutput("claude: result envelope lacks provenance", _tail(raw)) + raise RunnerMalformedOutput("claude: result envelope lacks provenance", _tail(raw)) session_id = envelope["session_id"] usage = envelope["usage"] cost = envelope["total_cost_usd"] @@ -547,7 +552,7 @@ def _claude_provenance(envelope: dict, raw: str) -> dict[str, object]: or isinstance(duration, bool) or not isinstance(duration, (int, float)) ): - raise RunnerBadOutput("claude: result envelope has invalid provenance", _tail(raw)) + raise RunnerMalformedOutput("claude: result envelope has invalid provenance", _tail(raw)) return { "family": "claude", "session_id": session_id, @@ -1079,7 +1084,7 @@ def _codex_provenance( else None ) if not session_id or not isinstance(usage, dict): - raise RunnerBadOutput( + raise RunnerMalformedOutput( "codex: execution output lacks session/token provenance", _tail(stdout + stderr) ) clean_stderr = re.sub(r"\x1b\[[0-9;]*m", "", stderr) @@ -1145,9 +1150,9 @@ def _review_claude( try: envelope = _extract_json_object(raw) except (json.JSONDecodeError, ValueError) as exc: - raise RunnerBadOutput("claude: stdout is not JSON", _tail(raw)) from exc + raise RunnerMalformedOutput("claude: stdout is not JSON", _tail(raw)) from exc if not isinstance(envelope, dict): - raise RunnerBadOutput("claude: result envelope is not an object", _tail(raw)) + raise RunnerMalformedOutput("claude: result envelope is not an object", _tail(raw)) if _claude_envelope_auth_failure(envelope): raise RunnerAuthFailed(f"claude: CLI is not authenticated\n{_tail(raw)}") if envelope.get("is_error") and _subscription_exhausted(raw, envelope): @@ -1162,7 +1167,7 @@ def _review_claude( try: payload = _claude_payload(envelope) except (json.JSONDecodeError, ValueError) as exc: - raise RunnerBadOutput("claude: result text is not JSON", _tail(raw)) from exc + raise RunnerMalformedOutput("claude: result text is not JSON", _tail(raw)) from exc usage = envelope.get("modelUsage") models = tuple(key for key in usage if isinstance(key, str)) if isinstance(usage, dict) else () reported_model = ", ".join(models) or None @@ -1263,18 +1268,20 @@ def _review_codex( ) final = _codex_final_file(last_file) if final["status"] not in ("complete", "absent"): - raise RunnerBadOutput("codex: final message file could not be read completely") + raise RunnerMalformedOutput("codex: final message file could not be read completely") + message_bytes = base64.b64decode(final.get("bytes_base64", "")) try: - message = base64.b64decode(final.get("bytes_base64", "")).decode("utf-8") + message = message_bytes.decode("utf-8") except UnicodeDecodeError as exc: - raise RunnerBadOutput("codex: final message is not UTF-8") from exc + fragment = _tail(message_bytes.decode(errors="replace")) + raise RunnerMalformedOutput("codex: final message is not UTF-8", fragment) from exc provenance, raw = _codex_provenance(done.stdout, done.stderr, message, home=home) if not message.strip(): - raise RunnerBadOutput("codex: no final message written", _tail(done.stdout + done.stderr)) + raise RunnerMalformedOutput("codex: no final message written", _tail(done.stdout + done.stderr)) try: payload = _extract_json_object(message) except (json.JSONDecodeError, ValueError) as exc: - raise RunnerBadOutput("codex: final message is not JSON", _tail(message)) from exc + raise RunnerMalformedOutput("codex: final message is not JSON", _tail(message)) from exc envelope = _evidence_json(raw) envelope["configured_settings"] = configured envelope["cli_version"] = cli_version @@ -1285,7 +1292,7 @@ def _review_codex( provenance["requested_settings"] = [{"model": model, "effort": effort}] banner_model = _CODEX_MODEL_RE.search(done.stderr) return replace( - parse_review(payload, family="codex", head=head, kind=kind, raw=raw), + parse_review(payload, family="codex", head=head, kind=kind, raw=raw, excerpt=message), model=model or (banner_model.group(1) if banner_model else None), effort=effort, duration_s=done.duration_s, provenance=provenance, diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c136d5d..b36f8fb1 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -358,6 +358,35 @@ def expect_cli(capsys, exit_code, *argv, stdout=None, stderr=None, stdout_contai return out, err +@pytest.mark.parametrize("save", [True, False]) +def test_review_malformed_fragments_stay_out_of_terminal(wt, gh, fake_bin, monkeypatch, capsys, save): + prepare_review(wt, gh, fake_bin) + envelopes = {family: json.dumps({"unexpected": family * 700}) for family in ("claude", "codex")} + + def malformed(family, *, head, kind, **kwargs): + raw = envelopes[family] + cli.runners.parse_review(json.loads(raw), family=family, head=head, kind=kind, raw=raw) + + monkeypatch.setattr(cli.runners, "review_with", malformed) + if not save: + def fail(*args): + raise PermissionError("diagnostic write denied") + monkeypatch.setattr(cli, "_write_json_atomically", fail) + code, out, err = run(capsys, "review") + size = len((out + err).encode()) + assert size < 650, size + assert code == 4 and "rerun" in err and "wait for the owner" in err + for family in envelopes: + assert f"{family}: review has unexpected or missing keys" in err + assert family * 10 not in err + if save: + path = next((wt / ".loopzero").glob("reviewer-output-*.json")) + assert path.name in err and path.stat().st_mode & 0o777 == 0o600 + assert json.loads(path.read_text()) == {family: raw[-2000:] for family, raw in envelopes.items()} + else: + assert "diagnostic write denied" in err + + # --- start / check -------------------------------------------------------------------- diff --git a/tests/test_runners.py b/tests/test_runners.py index e14ccdba..540d3a34 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -1212,9 +1212,11 @@ def test_unknown_family_and_kind(tmp_path: Path) -> None: ], ) def test_review_schema_is_strict(fake_bin: Path, tmp_path: Path, finding: dict) -> None: - _fake_codex(fake_bin, json.dumps({"verdict": "request_changes", "findings": [finding]})) - with pytest.raises(RunnerBadOutput): + message = json.dumps({"verdict": "request_changes", "findings": [finding]}) + _fake_codex(fake_bin, message) + with pytest.raises(runners.RunnerMalformedOutput) as error: _review("codex", tmp_path) + assert error.value.tail == message + "\n" @pytest.mark.parametrize(("has_stderr", "size"), [(True, 0), (True, 3000), (False, 3000)]) From b67aef410299f1f8dd27a60030a173fbbc79ac69 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:16:27 +0100 Subject: [PATCH 5/8] Keep regression proof within fifteen net test lines Co-Authored-By: Codex --- tests/test_cli.py | 82 ++++++++++++----------------------------------- 1 file changed, 21 insertions(+), 61 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 98ba15cd..805bfd86 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1448,13 +1448,11 @@ def test_runtime_pinning_requires_trusted_workflow( origin = Path(git(wt, "remote", "get-url", "origin").strip()) if missing == "default": git(wt, "symbolic-ref", "--delete", "refs/remotes/origin/HEAD") - elif missing == "remote": - git(wt, "update-ref", "-d", "refs/remotes/origin/main") - git(origin, "update-ref", "-d", "refs/heads/main") else: - initial = git(wt, "rev-list", "--max-parents=0", "HEAD").strip() - git(wt, "update-ref", "refs/remotes/origin/main", initial) - git(origin, "update-ref", "refs/heads/main", initial) + options = ("-d",) if missing == "remote" else () + revision = () if options else (git(wt, "rev-list", "--max-parents=0", "HEAD").strip(),) + for checkout, ref in ((wt, "refs/remotes/origin/main"), (origin, "refs/heads/main")): + git(checkout, "update-ref", *options, ref, *revision) prepare_review(wt, gh, fake_bin) code, out, err = run(capsys, command) assert "reviewer paths" not in out + err @@ -2470,7 +2468,7 @@ def after_sleep(): @pytest.mark.parametrize("command", ["ready", "merge"]) @pytest.mark.parametrize("settled", ["CONFLICTING", "MERGEABLE", "UNKNOWN"]) -def test_wait_for_github_mergeability(wt, gh, capsys, monkeypatch, command, settled, git_calls): +def test_wait_for_github_mergeability(wt, gh, capsys, monkeypatch, command, settled): head = commit_mergify_configuration(wt) arm_approved_ready_pr(gh, head, wt, mergeable="UNKNOWN", isDraft=False) gh.respond_pr_view(pr_json(headRefOid=head, mergeable=settled, isDraft=False, @@ -2481,69 +2479,18 @@ def test_wait_for_github_mergeability(wt, gh, capsys, monkeypatch, command, sett monkeypatch.setattr(cli, "_wait_for_mergify", lambda *_: None) poll_clock(monkeypatch) - git_calls.clear() code, out, err = run(capsys, command, "--wait=1") - assert sum(call[0] == "fetch" for call in git_calls) == 1 if settled == "CONFLICTING": assert code == 1 and "has merge conflicts" in out + err elif settled == "UNKNOWN": - assert code == 3 and out.endswith(f"timed out waiting for GitHub to compute mergeability on {head[:12]}. Run `loopzero {command} --wait` to resume on this head.\n"), (code, out, err) + assert code == 3 and out.endswith(f"timed out waiting for GitHub to compute mergeability on {head[:12]}. Run `loopzero {command} --wait` to resume on this head.\n") else: assert code == (0 if command == "ready" else 3) assert requests == ([(REPO, 7, head, "main")] if command == "merge" and settled == "MERGEABLE" else []) -@pytest.mark.parametrize("publisher,expected", [ - ("retired-publisher", "pending"), ("replacement-publisher", "success"), -]) -def test_readiness_and_hosted_use_current_base_publishers(wt, gh, head, tmp_path, monkeypatch, capsys, - publisher, expected): - git(tmp_path, "clone", "-q", str(tmp_path / "origin.git"), "trusted") - trusted = tmp_path / "trusted" - workflow = trusted / "workflow.toml" - retired_workflow = (WORKFLOW.replace('required_ci = ["checks"]', - 'required_ci = ["checks", "Loop-zero Eligibility"]') - + 'review_publishers = ["retired-publisher"]\n') - workflow.write_text(retired_workflow) - git(trusted, "commit", "-qam", "trust old review publisher") - git(trusted, "push", "-q", "origin", "main") - git(wt, "fetch", "-q", "origin", "main") - stale = git(wt, "rev-parse", "origin/main") - - arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=False, review_login=publisher) - gh.respond(f"api repos/{REPO}/commits/{head}/statuses", - [{"context": "Loop-zero Eligibility", "state": "success"}]) - workflow.write_text(retired_workflow.replace("retired-publisher", "replacement-publisher")) - git(trusted, "commit", "-qam", "rotate review publisher") - git(trusted, "push", "-q", "origin", "main") - assert git(wt, "rev-parse", "origin/main") == stale - assert git(trusted, "rev-parse", "HEAD") != stale - - code, out, _ = run(capsys, "ready") - assert code == (0 if expected == "success" else 1) - assert (github.MISSING_REVIEW_REASON in out) == (expected == "pending") - if expected == "pending": - git(wt, "remote", "set-url", "origin", str(tmp_path / "unavailable.git")) - code, _, err = run(capsys, "ready") - assert code == 1 and "could not refresh origin/main" in err - explicit = tmp_path / "explicit.toml" - explicit.write_text(retired_workflow) - assert run(capsys, "--config", str(explicit), "ready")[0] == 0 - - event = trusted / "event.json" - event.write_text(json.dumps({"inputs": {"pr": "7"}})) - monkeypatch.chdir(trusted) - monkeypatch.setenv("GITHUB_REPOSITORY", REPO) - monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) - gh.respond(f"api repos/{REPO}/statuses/{head}", {}) - assert hosted.main() == 0 - payload = json.loads(gh.calls[-1]["--input"]) - assert gh.calls[-1]["argv"][1] == f"repos/{REPO}/statuses/{head}" - assert payload["state"] == expected - - @pytest.mark.parametrize("command,check,hold_at_admission", [ ("ready", "success", False), ("ready", "skipped", False), ("merge", "success", False), ("merge", "success", True), @@ -4178,12 +4125,25 @@ def test_hosted_eligibility_uses_publisher_not_token(wt, gh, state, verdict, exp @pytest.mark.parametrize("publisher", ["stranger", "lz-bot"]) -def test_ready_pins_review_publishers_to_base(wt, gh, capsys, publisher, head): - (wt / "workflow.toml").write_text(WORKFLOW + f'\nreview_publishers = ["{publisher}"]\n') +def test_ready_pins_review_publishers_to_base(wt, repo, gh, capsys, monkeypatch, publisher, head): + policy = WORKFLOW.replace('required_ci = ["checks"]', 'required_ci = ["checks", "Loop-zero Eligibility"]') + publish_workflow(wt, policy + '\nreview_publishers = ["stranger"]\n') + commit_file(repo, "workflow.toml", policy + f'\nreview_publishers = ["{LOGIN}"]\n', "rotate publisher") + git(repo, "push", str(repo.parent / "origin.git"), "main") # preserve the retired local publisher + (wt / "workflow.toml").write_text(policy + f'\nreview_publishers = ["{publisher}"]\n') arm_approved_pr_with_check_result( gh, head, wt, "success", review_login=publisher, isDraft=False ) + gh.respond(f"api repos/{REPO}/commits/{head}/statuses", [{"context": "Loop-zero Eligibility", "state": "success"}]) assert run(capsys, "ready")[0] == (0 if publisher == LOGIN else 1) + event = repo / "event.json" + event.write_text(json.dumps({"inputs": {"pr": "7"}})) + monkeypatch.chdir(repo) + monkeypatch.setenv("GITHUB_REPOSITORY", REPO) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) + gh.respond(f"api repos/{REPO}/statuses/{head}", {}) + assert hosted.main() == 0 + assert json.loads(gh.calls[-1]["--input"])["state"] == ("success" if publisher == LOGIN else "pending") def test_mergify_confirmed_wait_reads_pr_once_per_steady_poll(wt, gh, monkeypatch): From 3d561478ec231897aa8ed20c4658409e75b545c4 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:16:50 +0100 Subject: [PATCH 6/8] Place output regression tests next to their command coverage Co-Authored-By: Codex --- tests/test_cli.py | 58 +++++++++++++++++++++++------------------------ 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index b36f8fb1..c733cd73 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -358,35 +358,6 @@ def expect_cli(capsys, exit_code, *argv, stdout=None, stderr=None, stdout_contai return out, err -@pytest.mark.parametrize("save", [True, False]) -def test_review_malformed_fragments_stay_out_of_terminal(wt, gh, fake_bin, monkeypatch, capsys, save): - prepare_review(wt, gh, fake_bin) - envelopes = {family: json.dumps({"unexpected": family * 700}) for family in ("claude", "codex")} - - def malformed(family, *, head, kind, **kwargs): - raw = envelopes[family] - cli.runners.parse_review(json.loads(raw), family=family, head=head, kind=kind, raw=raw) - - monkeypatch.setattr(cli.runners, "review_with", malformed) - if not save: - def fail(*args): - raise PermissionError("diagnostic write denied") - monkeypatch.setattr(cli, "_write_json_atomically", fail) - code, out, err = run(capsys, "review") - size = len((out + err).encode()) - assert size < 650, size - assert code == 4 and "rerun" in err and "wait for the owner" in err - for family in envelopes: - assert f"{family}: review has unexpected or missing keys" in err - assert family * 10 not in err - if save: - path = next((wt / ".loopzero").glob("reviewer-output-*.json")) - assert path.name in err and path.stat().st_mode & 0o777 == 0o600 - assert json.loads(path.read_text()) == {family: raw[-2000:] for family, raw in envelopes.items()} - else: - assert "diagnostic write denied" in err - - # --- start / check -------------------------------------------------------------------- @@ -2053,6 +2024,35 @@ def test_review_observes_new_codex_version_in_saved_receipt( assert result.provenance["cli_version"] == version +@pytest.mark.parametrize("save", [True, False]) +def test_review_malformed_fragments_stay_out_of_terminal(wt, gh, fake_bin, monkeypatch, capsys, save): + prepare_review(wt, gh, fake_bin) + envelopes = {family: json.dumps({"unexpected": family * 700}) for family in ("claude", "codex")} + + def malformed(family, *, head, kind, **kwargs): + raw = envelopes[family] + cli.runners.parse_review(json.loads(raw), family=family, head=head, kind=kind, raw=raw) + + monkeypatch.setattr(cli.runners, "review_with", malformed) + if not save: + def fail(*args): + raise PermissionError("diagnostic write denied") + monkeypatch.setattr(cli, "_write_json_atomically", fail) + code, out, err = run(capsys, "review") + size = len((out + err).encode()) + assert size < 650, size + assert code == 4 and "rerun" in err and "wait for the owner" in err + for family in envelopes: + assert f"{family}: review has unexpected or missing keys" in err + assert family * 10 not in err + if save: + path = next((wt / ".loopzero").glob("reviewer-output-*.json")) + assert path.name in err and path.stat().st_mode & 0o777 == 0o600 + assert json.loads(path.read_text()) == {family: raw[-2000:] for family, raw in envelopes.items()} + else: + assert "diagnostic write denied" in err + + @pytest.mark.parametrize("mixed_authors", [False, True]) def test_review_fails_with_three_line_errors_and_remedies_without_spending_budget( wt: Path, gh: FakeGh, capsys, monkeypatch, head, mixed_authors From ff1d23d7e7b6885a6071e63f86b48836d4f5417b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:19:25 +0100 Subject: [PATCH 7/8] Keep reviewer diagnostics compatible with guarded cleanup Architecture-Review: unchanged; cleanup still permits only task-owned artifacts and refuses symlinks. Co-Authored-By: Codex --- src/loopzero/runners.py | 12 ++++++------ src/loopzero/worktree.py | 2 +- tests/test_worktree.py | 1 + 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 7ae7aee9..833e97e9 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -538,7 +538,7 @@ def _repository_skill_paths(cwd: Path) -> set[str]: def _claude_provenance(envelope: dict, raw: str) -> dict[str, object]: required = ("session_id", "usage", "total_cost_usd", "duration_api_ms") if any(name not in envelope for name in required): - raise RunnerMalformedOutput("claude: result envelope lacks provenance", _tail(raw)) + raise RunnerBadOutput("claude: result envelope lacks provenance", _tail(raw)) session_id = envelope["session_id"] usage = envelope["usage"] cost = envelope["total_cost_usd"] @@ -552,7 +552,7 @@ def _claude_provenance(envelope: dict, raw: str) -> dict[str, object]: or isinstance(duration, bool) or not isinstance(duration, (int, float)) ): - raise RunnerMalformedOutput("claude: result envelope has invalid provenance", _tail(raw)) + raise RunnerBadOutput("claude: result envelope has invalid provenance", _tail(raw)) return { "family": "claude", "session_id": session_id, @@ -1084,7 +1084,7 @@ def _codex_provenance( else None ) if not session_id or not isinstance(usage, dict): - raise RunnerMalformedOutput( + raise RunnerBadOutput( "codex: execution output lacks session/token provenance", _tail(stdout + stderr) ) clean_stderr = re.sub(r"\x1b\[[0-9;]*m", "", stderr) @@ -1167,7 +1167,7 @@ def _review_claude( try: payload = _claude_payload(envelope) except (json.JSONDecodeError, ValueError) as exc: - raise RunnerMalformedOutput("claude: result text is not JSON", _tail(raw)) from exc + raise RunnerMalformedOutput("claude: result text is not JSON", _tail(str(envelope.get("result", "")))) from exc usage = envelope.get("modelUsage") models = tuple(key for key in usage if isinstance(key, str)) if isinstance(usage, dict) else () reported_model = ", ".join(models) or None @@ -1175,7 +1175,7 @@ def _review_claude( provenance["requested_settings"] = [{"model": model, "effort": effort}] provenance["configured_settings"] = [configured] return replace( - parse_review(payload, family="claude", head=head, kind=kind, raw=raw), + parse_review(payload, family="claude", head=head, kind=kind, raw=raw, excerpt=json.dumps(payload)), model=reported_model or model, effort=effort, duration_s=done.duration_s, provenance=provenance, ) @@ -1277,7 +1277,7 @@ def _review_codex( raise RunnerMalformedOutput("codex: final message is not UTF-8", fragment) from exc provenance, raw = _codex_provenance(done.stdout, done.stderr, message, home=home) if not message.strip(): - raise RunnerMalformedOutput("codex: no final message written", _tail(done.stdout + done.stderr)) + raise RunnerBadOutput("codex: no final message written", _tail(done.stdout + done.stderr)) try: payload = _extract_json_object(message) except (json.JSONDecodeError, ValueError) as exc: diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 444c8d5e..ced38891 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -302,7 +302,7 @@ def _require_no_ignored_user_files(wt: Path) -> None: for path in ignored.split("\0")[:-1]: if ( (path in {".loopzero/task.md", ".loopzero/checks.json"} - or re.fullmatch(r"\.loopzero/review-[0-9a-f]{12}-(primary|delta)\.json", path)) + or re.fullmatch(r"\.loopzero/review(?:er-output)?-[0-9a-f]{12}-(primary|delta)\.json", path)) and not (wt / path).is_symlink() ): continue diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 838ea563..e840362f 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -282,6 +282,7 @@ def test_task_helpers_errors(repo: Path) -> None: def test_cleanup_removes_worktree_and_branch(repo: Path, monkeypatch) -> None: wt, calls, real = worktree.start(repo, "done", "main"), [], worktree._git monkeypatch.setattr(worktree, "_git", lambda d, *a, **k: calls.append((d, a)) or real(d, *a, **k)) + (wt / f".loopzero/reviewer-output-{worktree.head(wt)[:12]}-primary.json").write_text("{}") worktree.cleanup(wt, worktree.head(wt)) # #439: no cleanup git runs in (or -C) the primary checkout assert calls and all(Path(d).resolve() != repo.resolve() and "-C" not in a for d, a in calls) assert not wt.exists() and not git(repo, "branch", "--list", "lz/done") and "done" not in git(repo, "worktree", "list") From 2bc84ac36b6119dc2caa29626a07c813a4ef834e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:21:38 +0100 Subject: [PATCH 8/8] Fit the review budget text within the documentation cap --- core/CONTRACT.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/core/CONTRACT.md b/core/CONTRACT.md index 28ccf2ec..4f9da924 100644 --- a/core/CONTRACT.md +++ b/core/CONTRACT.md @@ -206,11 +206,9 @@ version. Loop-zero serves internal projects only and does not target tamper resistance for outside users. Freeze new work on Codex evidence projections. Simplify or delete them when they break or obstruct delivery. -- One primary and at most one delta per PR. After a base merge, the delta - receives first-parent topic patches and the changes from each automatic - remerge to its recorded merge tree. Merged parents must come from the verified - base, and the reviewed commit must be on the first-parent history. Unresolved - primary findings still count under Blockers. +- One primary and at most one delta per PR. After a base merge, the delta covers first-parent topic changes and + edits to each automatic remerge. The reviewed commit must be on the first-parent history, and merged parents + must come from the verified base. Unresolved primary findings still count under Blockers. - Default: one writing model family per PR, including delegates and repairs; another may advise read-only and review independently. Before committing imported work, record every actual writing delegate in truthful