From 86700af7c44ba14938baf69490201763bd104d8d Mon Sep 17 00:00:00 2001 From: eowca Date: Thu, 26 Nov 2026 03:10:27 +0100 Subject: [PATCH 01/11] Isolate fake reviewer tests from host credentials (#1344) Co-authored-by: eowca <4008965+eowca@users.noreply.github.com> Co-authored-by: Codex --- tests/test_runners.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/tests/test_runners.py b/tests/test_runners.py index 7fbaca25..991d10ab 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -17,7 +17,7 @@ import pytest -from loopzero import sandbox, worktree +from loopzero import runners, sandbox, worktree from loopzero.runners import ( REVIEW_SCHEMA, RunnerAuthFailed, @@ -113,8 +113,17 @@ def _bwrap_argv(log: Path) -> list[str]: @pytest.fixture(autouse=True) -def fake_bwrap(fake_tool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: - for name in ("ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY"): +def fake_bwrap(fake_tool, tmp_path: Path, tmp_path_factory, monkeypatch: pytest.MonkeyPatch) -> Path: + # Keep reviewer state outside tmp_path, which many tests mount as the checkout. + home = tmp_path_factory.mktemp("reviewer-home") + monkeypatch.setenv("HOME", str(home)) + for name in ( + "CODEX_HOME", + "CLAUDE_CONFIG_DIR", + "CLAUDE_SECURESTORAGE_CONFIG_DIR", + *runners.CLAUDE_AUTH_ENV, + *runners.CODEX_AUTH_ENV, + ): monkeypatch.delenv(name, raising=False) log = tmp_path / "review-bwrap.argv" fake_tool("bwrap", FAKE_BWRAP.format(log=log)) From 72f087e4161fa346d5aff1092c468696683f4997 Mon Sep 17 00:00:00 2001 From: eowca Date: Thu, 26 Nov 2026 03:10:33 +0100 Subject: [PATCH 02/11] Preserve review rounds for verified changes (#1358) Architecture-Review: unchanged; the skills reinforce existing review, receipt, and readiness behavior. Co-authored-by: eowca <4008965+eowca@users.noreply.github.com> Co-authored-by: Codex --- core/skills/implement/SKILL.md | 6 ++++-- core/skills/resolve-findings/SKILL.md | 14 +++++++------- core/skills/work-issue/SKILL.md | 6 ++++-- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/core/skills/implement/SKILL.md b/core/skills/implement/SKILL.md index b26bd52a..70e37ee1 100644 --- a/core/skills/implement/SKILL.md +++ b/core/skills/implement/SKILL.md @@ -28,8 +28,10 @@ and map each to a test or recorded evidence. Observe required UI/runtime behavio proof for UI changes per [Reporting](../../CONTRACT.md#reporting). Required acceptance that remains unobserved stays open with a next-action owner. Record the tested revision, observations, trade-offs -and limits in Notes or human Validation. Follow the contract's -[gate receipt fields and reuse rules](../../CONTRACT.md#gate-execution-and-delivery-priority). +and limits in Notes or human Validation. Start primary review only with a +completed passing `loopzero check` receipt for the exact pushed head. Focused +tests and running checks are intermediate evidence. Reuse a passing same-head +receipt under the [contract's reuse rules](../../CONTRACT.md#gate-execution-and-delivery-priority). Run commands expected to take more than about two minutes detached as in [Long-running jobs](../../../docs/DELEGATION.md#long-running-jobs). diff --git a/core/skills/resolve-findings/SKILL.md b/core/skills/resolve-findings/SKILL.md index d9a96d68..f5ac745c 100644 --- a/core/skills/resolve-findings/SKILL.md +++ b/core/skills/resolve-findings/SKILL.md @@ -22,10 +22,10 @@ security-path downgrades need requester authority. For conflicting findings, reconcile their acceptance and impact. New critical evidence requires a separate authorized PR review thread rather than silently expanding this batch. -After the delta, follow the contract's [round-two rule](../../CONTRACT.md#review-budget). -Return accepted repairs to delivery: fixing findings does not finish the task -until the fixed head is delivered. - -Then continue the task you were given as far as it authorizes, or hand over -what is left of its acceptance. If two repairs have failed, the route is -probably wrong, so reconsider it before a third. +Before requesting the delta, compare the full repair with the primary-reviewed +head. Identify affected callers and guarantees for each repaired behavior. Use +existing test seams to exercise the failing case and any success, failure or +timing behavior the repair can change. Apply [security-review](../security-review/SKILL.md) +to changed trust boundaries. Record the evidence with the repair, run the +existing checks and follow the contract's [review budget](../../CONTRACT.md#review-budget) +through delivery or handoff of remaining acceptance. diff --git a/core/skills/work-issue/SKILL.md b/core/skills/work-issue/SKILL.md index c4e97513..005823c0 100644 --- a/core/skills/work-issue/SKILL.md +++ b/core/skills/work-issue/SKILL.md @@ -30,8 +30,10 @@ blueprint. Include required completion in the closing delivery. A child issue does not own its parent's blueprint. Recheck collisions before publication and again before merge, rereading live acceptance, prior delivery and ownership. Reconcile changed state before proceeding. -Review, CI and observable post-merge acceptance waits remain this task; -neither bypass them nor start another issue. +On approval, run readiness at the approved head and defer suggestions and cleanup. +Before making a source edit for the [delta](../../CONTRACT.md#review-budget), name +the unmet acceptance criterion or newly verified defect that requires it. +Review, CI and post-merge acceptance waits remain this task. Before using [CI or observation-based acceptance](reference.md#acceptance-evidence) or [resuming after interruption or context loss](reference.md#re-entry), follow the linked safeguards. From 9051b75705410e1423b7c73840e26ee36f1e4afe Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:16:52 +0100 Subject: [PATCH 03/11] Serialize review round publication across checkouts Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 2 ++ src/loopzero/cli.py | 48 +++++++++++++++++++++--------------------- src/loopzero/github.py | 12 +++++++++++ tests/conftest.py | 1 + tests/test_cli.py | 35 ++++++++++++++++++++++++------ 5 files changed, 67 insertions(+), 31 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 661a86f4..d67dcf95 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -35,6 +35,8 @@ reserved classes. Git owns commits, branches and ancestry. GitHub owns the live PR narrative, reviews, finding threads, check statuses and merge state. Within a task worktree, PR body writers lock the state directory from the live read through the update. +Review publication rechecks the round while holding a same-host lock keyed by +repository and PR. The lock covers POST and lost-response read-back. CI and branch protection provide the hosted enforcement. Readiness is a checklist over these sources, not a tamper-proof security boundary: repository writers can edit PR evidence, diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 515d3da7..977ea5c7 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -793,21 +793,14 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: or not isinstance(publication.get("publisher"), str) or not publication["publisher"]): raise CliError("saved publication identity differs from this repository/PR") - confirmed, reviews = _recover_review(wt, config, pr, result, + confirmed, _ = _recover_review(wt, config, pr, result, publication["publisher"], token) if confirmed: return _review_verdict(result) - 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( - _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") else: try: result = _run_review(wt, config, head, kind, reviewed, args.model, args.effort, @@ -833,24 +826,31 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: prefix = _repost_prefix(result) _save_review(wt, result, {"repo": config.repo, "number": pr.number, "publisher": publisher}) token = _refresh_publisher_token(token, publisher) - try: - github.post_review( - config.repo, pr.number, head, result, body_prefix=prefix, pr=pr, token=token, - publisher=publisher, + with github.pr_lock(config.repo, pr.number): + reviews = _pr_reviews(config.repo, pr.number) + allowed, _ = _decide_kind( + _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head ) - except (github.GhError, _proc.ProcTimeout) as exc: - path = _review_file(wt, head, kind) + if allowed != kind: + raise CliError("review round changed during publication; run loopzero review again") try: - if _recover_review(wt, config, pr, result, publisher, token)[0]: - return _review_verdict(result) - except (github.GhError, CliError, _proc.ProcTimeout) as recovery: - raise CliError(f"{exc} | publication read-back blocked: {recovery}; " - f"review saved at {path}; retry `loopzero review --repost` " - "after resolving the read-back failure") from recovery - raise CliError( - f"{exc} | publication unconfirmed; review saved at {path}; " - "inspect the cause and run `loopzero review --repost` to reconcile or explicitly retry" - ) from exc + github.post_review( + config.repo, pr.number, head, result, body_prefix=prefix, pr=pr, token=token, + publisher=publisher, + ) + except (github.GhError, _proc.ProcTimeout) as exc: + path = _review_file(wt, head, kind) + try: + if _recover_review(wt, config, pr, result, publisher, token)[0]: + return _review_verdict(result) + except (github.GhError, CliError, _proc.ProcTimeout) as recovery: + raise CliError(f"{exc} | publication read-back blocked: {recovery}; " + f"review saved at {path}; retry `loopzero review --repost` " + "after resolving the read-back failure") from recovery + raise CliError( + f"{exc} | publication unconfirmed; review saved at {path}; " + "inspect the cause and run `loopzero review --repost` to reconcile or explicitly retry" + ) from exc try: with _lock_task_state(wt): live = github.pr_view(config.repo, pr.number) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index e85f5300..28b76c1a 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -2,6 +2,7 @@ from __future__ import annotations +import fcntl import hashlib import json import os @@ -25,6 +26,7 @@ GH_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GH_TOKEN", "GITHUB_TOKEN", "GH_HOST") APP_TOKEN_HELPER = Path.home() / ".config/loopzero/app-token" +PR_LOCK_DIR = Path.home() / ".cache/loopzero/pr-locks" _app_token_cache = ("", 0.0) MISSING_REVIEW_REASON = "no review recorded for the current head" MARKER_RE = re.compile( @@ -263,6 +265,16 @@ def _cached_app_token() -> str: return token if token and 0 <= time.time() - minted < 3000 else "" +@contextmanager +def pr_lock(repo: str, number: int) -> Iterator[None]: + """Serialize a GitHub write across local checkouts for this PR.""" + key = hashlib.sha256(f"{repo.casefold()}#{number}".encode()).hexdigest() + PR_LOCK_DIR.mkdir(mode=0o700, parents=True, exist_ok=True) + with (PR_LOCK_DIR / key).open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + yield + + def app_token() -> str: global _app_token_cache if token := _cached_app_token(): diff --git a/tests/conftest.py b/tests/conftest.py index 7a5fdcbd..069628b4 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -16,6 +16,7 @@ @pytest.fixture(autouse=True) def no_real_app_helper(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(github, "PR_LOCK_DIR", tmp_path / "pr-locks") monkeypatch.setattr(github, "APP_TOKEN_HELPER", tmp_path / "absent-app-token", raising=False) monkeypatch.setattr(github, "_app_token_cache", ("", 0.0), raising=False) diff --git a/tests/test_cli.py b/tests/test_cli.py index 3cd7131b..93b2be40 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1326,21 +1326,42 @@ def test_review_primary_posts_marker(wt: Path, gh: FakeGh, fake_bin: Path, capsy assert f"- primary, claude, {head[:12]}, request_changes" in updated -def test_overlapping_review_dispatches_and_publishes_once(wt, gh, fake_bin, capsys, monkeypatch): - prepare_review(wt, gh, fake_bin) +@pytest.mark.parametrize("separate_checkout", [False, True]) +def test_overlapping_review_dispatches_and_publishes_once( + wt, repo, gh, fake_bin, capsys, monkeypatch, separate_checkout, +): + head = prepare_review(wt, gh, fake_bin) + other = wt + if separate_checkout: + other = wt.parent / "other" + git(repo, "worktree", "add", "--force", str(other), "lz/t1") + shutil.copytree(wt / ".loopzero", other / ".loopzero") + post = github.post_review + + def publish(*args, **kwargs): + post(*args, **kwargs) + gh.respond(reviews_key(), [rev(head, "primary")]) + + monkeypatch.setattr(github, "post_review", publish) review = cli._run_review dispatched, overlapping = [], [] def overlap(*args, **kwargs): dispatched.append(args[2]) if len(dispatched) == 1: - overlapping.append(run(capsys, "review")) + with monkeypatch.context() as nested: + nested.chdir(other) + overlapping.append(run(capsys, "review")) return review(*args, **kwargs) monkeypatch.setattr(cli, "_run_review", overlap) - assert run(capsys, "review")[0] == 0 - assert len(dispatched) == 1 - assert overlapping[0][0] == 1 and "review already running" in overlapping[0][2] + code, _, err = run(capsys, "review") + if separate_checkout: + assert code == 1 and "already has a primary review" in err, overlapping + assert len(dispatched) == 2 and overlapping[0][0] == 0 + else: + assert code == 0 and len(dispatched) == 1 + assert overlapping[0][0] == 1 and "review already running" in overlapping[0][2] assert sum(call["argv"][1] == post_key().split()[1] and "--method" in call["argv"] for call in gh.calls) == 1 @@ -1929,7 +1950,7 @@ def test_review_posts_as_checked_identity(wt, gh, fake_bin, monkeypatch, capsys, prepare_review(wt, gh, fake_bin, post_id=3) gh.respond("api graphql viewer", {"data": {"viewer": {"login": publisher}}}) assert run(capsys, "review")[0] == 0 - assert len(gh.calls) == 8 # Includes the body refresh after review publication. + assert len(gh.calls) == 9 # Includes the final round check and the body refresh. assert sum(c["argv"][:2] == ["api", "graphql"] for c in gh.calls) == 1 assert not any("/files" in c["argv"][1] for c in gh.calls) assert posted_review(gh)["event"] == ("APPROVE" if publisher == LOGIN else "COMMENT") From 3bf642b11132953bf95a32d88831de597ee9b3e6 Mon Sep 17 00:00:00 2001 From: eowca Date: Thu, 26 Nov 2026 03:19:09 +0100 Subject: [PATCH 04/11] Preserve size-budget path bytes across filesystem locales (#1339) Co-authored-by: eowca <4008965+eowca@users.noreply.github.com> Co-authored-by: Codex --- scripts/size_budget.sh | 5 +++-- tests/test_size_budget.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/scripts/size_budget.sh b/scripts/size_budget.sh index ebd78fb5..9803fe6d 100755 --- a/scripts/size_budget.sh +++ b/scripts/size_budget.sh @@ -55,6 +55,7 @@ fi "${PY[@]}" - "$base" src/loopzero "$COMPLEXITY_CAP" <<'PY' || status=1 import ast +import os import subprocess import sys from pathlib import Path @@ -122,14 +123,14 @@ base_scores: dict[tuple[str, str], int] = {} for raw in git_bytes("ls-tree", "-rz", "--name-only", base, "--", target).split(b"\0"): if not raw or not raw.endswith(b".py"): continue - rel = raw.decode("utf-8", errors="surrogateescape") + rel = os.fsdecode(raw) base_scores.update(file_complexities(rel, git_bytes("show", f"{base}:{rel}"))) tree_scores: dict[tuple[str, str], int] = {} for raw in git_bytes("ls-files", "-zco", "--exclude-standard", "--", target).split(b"\0"): if not raw or not raw.endswith(b".py"): continue - rel = raw.decode("utf-8", errors="surrogateescape") + rel = os.fsdecode(raw) p = Path(rel) if p.is_file(): tree_scores.update(file_complexities(rel, p.read_bytes())) diff --git a/tests/test_size_budget.py b/tests/test_size_budget.py index 7b030ea0..0afb26e8 100644 --- a/tests/test_size_budget.py +++ b/tests/test_size_budget.py @@ -41,7 +41,7 @@ def _branchy(name: str, branches: int) -> str: @pytest.mark.parametrize("failure", [None, "deleted", "show"]) def test_size_budget_counts_unicode_and_propagates_read_errors(git_repo, fake_tool, failure): - source = git_repo / "src/loopzero" / ("a.py" if failure else "é space\nname.py") + source = git_repo / "src/loopzero" / ("a.py" if failure else os.fsdecode(b"\xc3\xa9 space\nname.py")) source.parent.mkdir(parents=True) source.write_text("one\ntwo\n") source.with_name("z.py").write_text("three\n") From 8e25213ab403952a5272ff3434f33612aee1214f Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:20:19 +0100 Subject: [PATCH 05/11] Report a review round taken during publication Architecture-Review: unchanged; make the existing locked round rejection specific to the race. Co-Authored-By: Codex --- src/loopzero/cli.py | 16 ++++++++++------ tests/test_cli.py | 2 +- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 977ea5c7..d608ec55 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -827,12 +827,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: _save_review(wt, result, {"repo": config.repo, "number": pr.number, "publisher": publisher}) token = _refresh_publisher_token(token, publisher) with github.pr_lock(config.repo, pr.number): - reviews = _pr_reviews(config.repo, pr.number) - allowed, _ = _decide_kind( - _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head - ) - if allowed != kind: - raise CliError("review round changed during publication; run loopzero review again") + _require_open_review_round(config, pr, head, kind) try: github.post_review( config.repo, pr.number, head, result, body_prefix=prefix, pr=pr, token=token, @@ -860,6 +855,15 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: return _review_verdict(result) +def _require_open_review_round(config: Config, pr: github.PR, head: str, kind: str) -> None: + markers = _pr_markers(_pr_reviews(config.repo, pr.number), head, config.review_publishers, + repo=config.repo, number=pr.number) + if any(marker.kind == kind for marker in markers): + raise CliError(f"the {kind} review round is already taken; run loopzero ready") + if _decide_kind(markers, head)[0] != kind: + raise CliError("review round changed during publication; run loopzero review again") + + def _refresh_publisher_token(token: str, publisher: str) -> str: """The review may outlive the app token: re-mint it, but only for the same publisher.""" if not token or (fresh := github.app_token()) == token: diff --git a/tests/test_cli.py b/tests/test_cli.py index 93b2be40..0a62b69f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1357,7 +1357,7 @@ def overlap(*args, **kwargs): monkeypatch.setattr(cli, "_run_review", overlap) code, _, err = run(capsys, "review") if separate_checkout: - assert code == 1 and "already has a primary review" in err, overlapping + assert code == 1 and "primary review round is already taken" in err, overlapping assert len(dispatched) == 2 and overlapping[0][0] == 0 else: assert code == 0 and len(dispatched) == 1 From 6ab49d4b8f2a8c485e1061949a755134c2a82b2e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:21:51 +0100 Subject: [PATCH 06/11] Distinguish a taken review round from head drift Architecture-Review: unchanged; keep locked review admission scoped to the intended head. Co-Authored-By: Codex --- src/loopzero/cli.py | 2 +- tests/test_cli.py | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index d608ec55..db590417 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -858,7 +858,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: def _require_open_review_round(config: Config, pr: github.PR, head: str, kind: str) -> None: markers = _pr_markers(_pr_reviews(config.repo, pr.number), head, config.review_publishers, repo=config.repo, number=pr.number) - if any(marker.kind == kind for marker in markers): + if any(marker.kind == kind and marker.head == head for marker in markers): raise CliError(f"the {kind} review round is already taken; run loopzero ready") if _decide_kind(markers, head)[0] != kind: raise CliError("review round changed during publication; run loopzero review again") diff --git a/tests/test_cli.py b/tests/test_cli.py index 0a62b69f..9f16e7d0 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4784,3 +4784,14 @@ def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys): assert "unverified" not in draft assert f"Recorded for `{head[:12]}`\n- `echo ok`: exit 0" in draft assert "Manual validation evidence." in draft + + +@pytest.mark.parametrize("same_head", [False, True]) +def test_final_review_round_check_distinguishes_heads(wt, gh, head, same_head): + cfg = config.load(wt / "workflow.toml") + pr = github.PR(7, URL, head, "main", False, "OPEN", "MERGEABLE") + gh.respond("api graphql viewer", {"data": {"viewer": {"login": LOGIN}}}) + gh.respond(reviews_key(), [rev(head if same_head else "a" * 40, "primary")]) + expected = "round is already taken" if same_head else "round changed during publication" + with pytest.raises(cli.CliError, match=expected): + cli._require_open_review_round(cfg, pr, head, "primary") From bd539a48d1a7cec656ac1fdef1045607d32d5336 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:21:56 +0100 Subject: [PATCH 07/11] Serialize PR body refreshes across checkouts Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 4 ++-- src/loopzero/cli.py | 23 ++++++++------------- tests/test_cli.py | 49 ++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 58 insertions(+), 18 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d67dcf95..ea49f2fe 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -33,8 +33,8 @@ local-receipt exceptions. Merge authority permits merging by default outside reserved classes. Git owns commits, branches and ancestry. GitHub owns the live PR narrative, -reviews, finding threads, check statuses and merge state. Within a task worktree, -PR body writers lock the state directory from the live read through the update. +reviews, finding threads, check statuses and merge state. PR body writers hold a same-host lock keyed by repository and PR from +the live read through the update, including writes from different checkouts. Review publication rechecks the round while holding a same-host lock keyed by repository and PR. The lock covers POST and lost-response read-back. CI and branch protection diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index aac4291d..aa1580b1 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -540,14 +540,6 @@ def _append_review(body: str, result: ReviewResult) -> str: def _refresh_pr_checks(wt: Path, config: Config) -> None: - try: - with _lock_task_state(wt): - _refresh_existing_pr_checks(wt, config) - except OSError as exc: - print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr) - - -def _refresh_existing_pr_checks(wt: Path, config: Config) -> None: """Best-effort refresh only when local HEAD is the existing PR head.""" argv = ["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"] try: @@ -557,7 +549,10 @@ def _refresh_existing_pr_checks(wt: Path, config: Config) -> None: branch, head = worktree.branch(wt), worktree.head(wt) pr = github.pr_for_branch(config.repo, branch, open_only=True) if pr is not None and pr.head_sha == head: - _update_pr_checks(wt, head, config, pr) + with github.pr_lock(config.repo, pr.number): + live = github.pr_view(config.repo, pr.number) + if live.state == "OPEN" and live.head_sha == head: + _update_pr_checks(wt, head, config, live) except (github.GhError, _proc.ProcTimeout, OSError, ValueError, CliError) as exc: print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr) @@ -667,7 +662,7 @@ def cmd_pr(args: argparse.Namespace) -> int: push.append(branch) _git_push(wt, push, force_lease=force_lease) if pr is not None and pr.state == "OPEN": - with _lock_task_state(wt): + with github.pr_lock(config.repo, pr.number): live = github.pr_view(config.repo, pr.number) if live.state != "OPEN": raise CliError(f"PR #{pr.number} closed during publication") @@ -796,7 +791,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: confirmed, _ = _recover_review(wt, config, pr, result, publication["publisher"], token) if confirmed: - return _finish_review(wt, config, pr, result) + return _finish_review(config, pr, result) # 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): @@ -851,12 +846,12 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: f"{exc} | publication unconfirmed; review saved at {path}; " "inspect the cause and run `loopzero review --repost` to reconcile or explicitly retry" ) from exc - return _finish_review(wt, config, pr, result) + return _finish_review(config, pr, result) -def _finish_review(wt: Path, config: Config, pr: github.PR, result: ReviewResult) -> int: +def _finish_review(config: Config, pr: github.PR, result: ReviewResult) -> int: try: - with _lock_task_state(wt): + with github.pr_lock(config.repo, pr.number): live = github.pr_view(config.repo, pr.number) body = _append_review(live.body, result) if body != live.body: diff --git a/tests/test_cli.py b/tests/test_cli.py index 93b2be40..88517edb 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -9,8 +9,11 @@ import shutil import subprocess import sys +from concurrent.futures import ThreadPoolExecutor +from contextlib import contextmanager from dataclasses import replace from pathlib import Path +from threading import Event, current_thread from types import SimpleNamespace from unittest.mock import Mock from urllib.parse import quote @@ -388,7 +391,8 @@ def test_check_refresh_preserves_local_verdict(wt, gh, capsys, monkeypatch, push monkeypatch.setattr(github, "update_body", Mock(side_effect=timeout)) code, out, err = run(capsys, "check") assert (code, out.splitlines()[-1]) == ((1, "FAIL") if stage_exit else (0, "PASS")) - assert [call["argv"][:2] for call in gh.calls] == LOOKUP_CALLS + ( + reads = LOOKUP_CALLS + ([["api", endpoint]] if pushed else []) + assert [call["argv"][:2] for call in gh.calls] == reads + ( [["api", endpoint]] if pushed and not refresh_timeout else []) report = json.loads((wt / ".loopzero/checks.json").read_text()) assert report["head"] == head_of(wt) and report["dirty"] is False @@ -397,7 +401,7 @@ def test_check_refresh_preserves_local_verdict(wt, gh, capsys, monkeypatch, push if refresh_timeout: assert f"note: could not refresh PR checks: PATCH {endpoint} timed out" in err if pushed and not refresh_timeout: - body = json.loads(gh.calls[len(LOOKUP_CALLS)]["--input"])["body"] + body = json.loads(gh.calls[len(reads)]["--input"])["body"] assert body.count("## Validation") == 1 assert f"Recorded for `{head_of(wt)[:12]}`" in body assert "- `echo ok`: exit 0" in body @@ -4784,3 +4788,44 @@ def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys): assert "unverified" not in draft assert f"Recorded for `{head[:12]}`\n- `echo ok`: exit 0" in draft assert "Manual validation evidence." in draft + + +def test_cross_checkout_check_refresh_keeps_review_summary(wt, repo, head, monkeypatch): + git(wt, "push", "-q", "-u", "origin", "lz/t1") + cfg = config.load(wt / "workflow.toml") + result = ReviewResult("claude", head, "primary", "approve", (), "") + body = "# T1\n\n## Notes\nKeep this prose\n" + pr = github.PR(7, URL, head, "main", False, "OPEN", "MERGEABLE") + patch_started, review_attempted = Event(), Event() + reviewer = current_thread() + lock = github.pr_lock + + @contextmanager + def observe_lock(*args): + if current_thread() is reviewer: + review_attempted.set() + with lock(*args): + yield + + def patch(_repo, _number, updated): + nonlocal body + if current_thread() is reviewer: + body = updated + review_attempted.set() + else: + patch_started.set() + assert review_attempted.wait(10) + body = updated + + monkeypatch.setattr(github, "pr_lock", observe_lock) + monkeypatch.setattr(github, "pr_for_branch", lambda *a, **k: replace(pr, body=body)) + monkeypatch.setattr(github, "pr_view", lambda *a: replace(pr, body=body)) + monkeypatch.setattr(github, "update_body", patch) + with ThreadPoolExecutor() as pool: + check = pool.submit(cli._refresh_pr_checks, wt, cfg) + assert patch_started.wait(10) + monkeypatch.chdir(repo) + assert cli._finish_review(cfg, pr, result) == 0 + check.result(timeout=10) + assert cli._CHECKS_START in body and "Keep this prose" in body + assert f"- primary, claude, {head[:12]}, approve" in body From 312302400d842474c58b9e8601a14ec7e21d8d02 Mon Sep 17 00:00:00 2001 From: eowca Date: Thu, 26 Nov 2026 03:22:52 +0100 Subject: [PATCH 08/11] Raise the test line cap to 13,850 (#1352) Owner Decisions ruling on #575: https://github.com/feder-positronics/loop-zero/issues/575#issuecomment-7180212375 Architecture-Review: unchanged; test line allowance re-baselined per OD ruling, authority/readiness/state unchanged Co-authored-by: eowca <4008965+eowca@users.noreply.github.com> Co-authored-by: Codex --- scripts/size_budget.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/size_budget.sh b/scripts/size_budget.sh index 9803fe6d..94a08555 100755 --- a/scripts/size_budget.sh +++ b/scripts/size_budget.sh @@ -13,7 +13,7 @@ set -euo pipefail # Measured 2026-11-25: 1406 core Markdown / 600 delegation Markdown lines. # Allow ~10% growth, rounded up, so small fixes do not require cap changes. SRC_CAP=8250 -TESTS_CAP=13500 +TESTS_CAP=13850 CORE_DOCS_CAP=1500 DELEGATION_DOC_CAP=660 COMPLEXITY_CAP=10 From 5f7fcf913a9f8f8f2101b8d58c7c22014f94ea90 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:23:43 +0100 Subject: [PATCH 09/11] Retain idempotent summary recovery in the combined patch Architecture-Review: unchanged; preserve the recovery PR behavior when the shared lock is used. Co-Authored-By: Codex --- src/loopzero/cli.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index a4ad9662..528fb3c3 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -532,6 +532,8 @@ def _append_review(body: str, result: ReviewResult) -> str: match = pattern.search(body) if not match: return f"{body.rstrip()}\n\n## Review\n{line}\n" + if line in match.group(2).splitlines(): + return body existing = match.group(2).rstrip() if existing.startswith("(filled by `loopzero review`)"): existing = "" From cb226bd952521f0275233e70c6d5dd838612b027 Mon Sep 17 00:00:00 2001 From: eowca Date: Thu, 26 Nov 2026 03:24:03 +0100 Subject: [PATCH 10/11] Share native review parsing steps (#1351) Architecture-Review: unchanged; native review payloads, verdict evidence and diagnostics retain their existing validation. Co-authored-by: eowca <4008965+eowca@users.noreply.github.com> Co-authored-by: Codex --- src/loopzero/runners.py | 54 +++++++++++++++++------------------------ 1 file changed, 22 insertions(+), 32 deletions(-) diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 3499b866..d0df767c 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -215,6 +215,11 @@ def _extract_json_object(text: str) -> object: return json.loads(stripped[start : end + 1]) +def _claude_payload(envelope: dict) -> object: + payload = envelope.get("structured_output") + 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: """Validate a decoded review object against the findings schema.""" if not isinstance(payload, dict): @@ -930,22 +935,16 @@ def _codex_evidence(result): or sum(e.get("type") == "turn.completed" for e in events) != 1 ): raise RunnerBadOutput("codex: incomplete/mixed native terminal evidence") - final = [ - e.get("item", {}).get("text") - for e in events + messages = [ + (i, e["item"].get("text")) + for i, e in enumerate(events) if e.get("type") == "item.completed" and isinstance(e.get("item"), dict) and e["item"].get("type") == "agent_message" ] - if not final or _evidence_json(final[-1]) != _evidence_json(envelope["final_message"]): + if not messages or _evidence_json(messages[-1][1]) != _evidence_json(envelope["final_message"]): raise RunnerBadOutput("codex: native final verdict is missing") - last_message = max( - i - for i, e in enumerate(events) - if e.get("type") == "item.completed" - and isinstance(e.get("item"), dict) - and e["item"].get("type") == "agent_message" - ) + last_message = messages[-1][0] if any( e.get("type") == "item.completed" and e.get("item", {}).get("type") == "command_execution" @@ -1159,12 +1158,10 @@ def _review_claude( if _looks_too_long(text) or _looks_too_long(raw): raise RunnerPromptTooLong("claude: prompt is too long", _tail(raw)) raise RunnerBadOutput(f"claude: {envelope.get('subtype', 'error')}", _tail(raw)) - payload = envelope.get("structured_output") - if payload is None: - try: - payload = _extract_json_object(str(envelope.get("result", ""))) - except (json.JSONDecodeError, ValueError) as exc: - raise RunnerBadOutput("claude: result text is not JSON", _tail(raw)) from exc + try: + payload = _claude_payload(envelope) + except (json.JSONDecodeError, ValueError) as exc: + raise RunnerBadOutput("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 @@ -1307,11 +1304,10 @@ def review_with( """Run one review of ``diff`` at ``head`` with the given model family.""" if family not in REVIEWER_FAMILIES: raise ValueError(f"unknown reviewer family {family!r}; expected one of {REVIEWER_FAMILIES}") - if kind not in ("primary", "delta"): - raise ValueError(f"unknown review kind {kind!r}; expected 'primary' or 'delta'") + policy = _review_policy(kind, split=chunk is not None) prompt = build_prompt(kind=kind, head=head, task_text=task_text, diff=diff, chunk=chunk) adapter = _review_claude if family == "claude" else _review_codex - policy, extra = _review_policy(kind, split=chunk is not None), {} + extra = {} if family == "codex" and review_context is not None: context = {**review_context, "cwd": str(cwd.resolve()), "index": chunk[0] if chunk else 1, "chunks": chunk[1] if chunk else 1, "requested": {"model": model, "effort": effort}, @@ -1471,22 +1467,16 @@ def validate_runner_result(result: ReviewResult) -> bool: and all(item.get("subtype", "success") == "success" for item in envelopes) and all(not item.get("is_error") for item in envelopes) and all(isinstance(item, dict) for item in usages) - and all(isinstance(item, (int, float)) and not isinstance(item, bool) for item in costs) - and all( - isinstance(item, (int, float)) and not isinstance(item, bool) - for item in durations - ) + and all(isinstance(item, (int, float)) and not isinstance(item, bool) + for item in costs + durations) and provenance.get("usage") == expected_usage and provenance.get("total_cost_usd") == sum(costs) and provenance.get("duration_api_ms") == sum(durations) ) - payloads = [item.get("structured_output") for item in envelopes] - for index, payload in enumerate(payloads): - if payload is None: - try: - payloads[index] = _extract_json_object(str(envelopes[index].get("result", ""))) - except (json.JSONDecodeError, ValueError): - return False + try: + payloads = [_claude_payload(item) for item in envelopes] + except (json.JSONDecodeError, ValueError): + return False elif result.family == "codex": envelope_sessions = [item.get("session_id") for item in envelopes] usages = [item.get("token_usage") for item in envelopes] From a04d159b582606430571e254e7a598e0f973bc70 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:28:12 +0100 Subject: [PATCH 11/11] Verify unrelated PR writes stay independent Co-Authored-By: Codex --- tests/test_cli.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/test_cli.py b/tests/test_cli.py index 28f474e4..f85c8674 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4824,6 +4824,8 @@ def patch(_repo, _number, updated): with ThreadPoolExecutor() as pool: check = pool.submit(cli._refresh_pr_checks, wt, cfg) assert patch_started.wait(10) + with lock(REPO, 8): + assert not check.done() monkeypatch.chdir(repo) assert cli._finish_review(cfg, pr, result) == 0 check.result(timeout=10)