diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 649d98c0..6e6b4194 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -33,10 +33,10 @@ 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. -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. +reviews, finding threads, check statuses and merge state. PR body writers hold +the same-host repository-and-PR lock from the live read through the update. +Review publication holds that lock for its round recheck, POST, read-back, and +body summary. Check coalescing and receipts retain the worktree-local lock. 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 cb219532..6d45fbf9 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -572,15 +572,20 @@ def _append_review(body: str, result: ReviewResult) -> str: def _refresh_pr_checks(wt: Path, config: Config) -> None: """Best-effort refresh only when local HEAD is the existing PR head.""" try: - with worktree.lock_local_state(wt): - upstream = config_mod.run_git(wt, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}") - if upstream.exit_code == 0: - 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: - body = _pr_body(wt, head, config, pr.body) - if body != (pr.body or "").replace("\r\n", "\n"): - github.update_body(config.repo, pr.number, body) + upstream = config_mod.run_git(wt, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}") + if upstream.exit_code != 0: + return + branch, head = worktree.branch(wt), worktree.head(wt) + pr = github.pr_for_branch(config.repo, branch, open_only=True) + if pr is None or pr.head_sha != head: + return + with github.pr_lock(config.repo, pr.number): + live = github.pr_view(config.repo, pr.number) + if live.state != "OPEN" or live.head_sha != head: + return + body = _pr_body(wt, head, config, live.body) + if body != live.body.replace("\r\n", "\n"): + github.update_body(config.repo, pr.number, body) except (github.GhError, _proc.ProcTimeout, OSError, ValueError, CliError, worktree.WorktreeError) as exc: print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr) @@ -726,7 +731,7 @@ def cmd_pr(args: argparse.Namespace) -> int: _require_push_target(wt, config.repo) _git_push(wt, push, force_lease=force_lease) if pr is not None: - with worktree.lock_local_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") @@ -887,12 +892,11 @@ 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 - try: - with worktree.lock_local_state(wt): + try: live = github.pr_view(config.repo, pr.number) github.update_body(config.repo, pr.number, _append_review(live.body, result)) - except (github.GhError, _proc.ProcTimeout, OSError, ValueError) as exc: - print(f"note: could not append PR review summary: {_one_line(exc)}", file=sys.stderr) + except (github.GhError, _proc.ProcTimeout, OSError, ValueError) as exc: + print(f"note: could not append PR review summary: {_one_line(exc)}", file=sys.stderr) return _review_verdict(result) diff --git a/tests/test_cli.py b/tests/test_cli.py index f2654626..f1b8a3ad 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -17,7 +17,7 @@ from email.utils import formatdate from pathlib import Path from select import select -from threading import Event +from threading import Event, current_thread, main_thread from types import SimpleNamespace from unittest.mock import Mock from urllib.parse import quote @@ -519,8 +519,8 @@ def test_check_refresh_preserves_local_verdict(wt, gh, capsys, monkeypatch, tmp_ monkeypatch.setattr(github, "update_body", Mock(side_effect=timeout)) code, out, err = run(capsys, *options, "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 + ( - [["api", endpoint]] if pushed and not refresh_timeout else []) + extra = [["api", endpoint]] * (2 - refresh_timeout) if pushed else [] + assert [call["argv"][:2] for call in gh.calls] == LOOKUP_CALLS + extra report = json.loads((wt / ".loopzero/checks.json").read_text()) assert report["head"] == head_of(wt) and report["dirty"] is False assert report["results"][0]["exit_code"] == stage_exit @@ -532,7 +532,7 @@ def test_check_refresh_preserves_local_verdict(wt, gh, capsys, monkeypatch, tmp_ 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[-1]["--input"])["body"] assert body.count("## Validation") == 1 assert_contains(body, f"Recorded for `{head_of(wt)[:12]}`", "- `echo ok`: exit 0") @@ -599,8 +599,7 @@ def test_pr_body_is_unchanged_when_checks_are_unchanged(wt: Path, gh: FakeGh, ca before = len(gh.calls) assert run(capsys, command)[0] == 0 history = HISTORY_CALLS if command == "pr" else [] - refresh = [["api", f"repos/{REPO}/pulls/7"]] if command == "pr" else [] - assert [c["argv"][:2] for c in gh.calls[before:]] == history + LOOKUP_CALLS + refresh + assert [c["argv"][:2] for c in gh.calls[before:]] == history + LOOKUP_CALLS + LOOKUP_CALLS[-1:] @pytest.mark.parametrize("body", [ @@ -628,23 +627,41 @@ def test_check_refresh_replaces_previous_head_without_losing_evidence( assert text in updated -def test_delayed_check_preserves_review_summary(wt, gh, fake_bin, capsys, monkeypatch): +def test_delayed_check_preserves_review_summary(wt, gh, fake_bin, tmp_path, monkeypatch): head = prepare_review(wt, gh, fake_bin) - body = "# PR\n\n## Notes\nHuman evidence.\n" - gh.respond_pr_list([pr_json(headRefOid=head, body=body)]) + detail = f"api repos/{REPO}/pulls/7" + gh.respond(detail, rest_pr_json(pr_json(headRefOid=head, body="# PR\n\nHuman evidence.\n"))) git(wt, "push", "-q", "-u", "origin", "lz/t1") - refresh = cli._refresh_pr_checks - - def delay(path, config): - assert run(capsys, "review")[0] == 0 - live = json.loads(gh.calls[-1]["--input"])["body"] - gh.respond(f"api repos/{REPO}/pulls/7", rest_pr_json(pr_json(headRefOid=head, body=live))) - refresh(path, config) - - monkeypatch.setattr(cli, "_refresh_pr_checks", delay) - assert run(capsys, "check")[0] == 0 + check = tmp_path / "check" + git(wt, "clone", "-q", "-b", "lz/t1", git(wt, "remote", "get-url", "origin").strip(), str(check)) + context = cli._context + monkeypatch.setattr(cli, "_context", lambda args, **kw: (check, config.load_trusted(check)) + if args.command == "check" else context(args, **kw)) + proceed, flock, update = Event(), github.fcntl.flock, github.update_body + + def acquire(fd, op): + if current_thread() is not main_thread() and op == github.fcntl.LOCK_EX: + try: + return flock(fd, op | github.fcntl.LOCK_NB) + except BlockingIOError: + proceed.set() + return flock(fd, op) + + pending = [] + with ThreadPoolExecutor(1) as pool: + def patch(repo, number, body): + if "## Review" not in body: + pending.append(pool.submit(cli.main, ["review"])) + assert proceed.wait(10) + update(repo, number, body) + gh.respond(detail, rest_pr_json(pr_json(headRefOid=head, body=body))) + proceed.set() + + monkeypatch.setattr(github.fcntl, "flock", acquire) + monkeypatch.setattr(github, "update_body", patch) + assert cli.main(["check"]) == pending[0].result(timeout=10) == 0 final = json.loads(gh.calls[-1]["--input"])["body"] - assert all(text in final for text in ("Human evidence.", "Recorded for", "- primary, claude")) + assert_contains(final, "Human evidence.", "Recorded for", "- primary, claude") @pytest.mark.parametrize("command,exit_code", [("check", 0), ("pr", 1)]) @@ -656,7 +673,7 @@ def test_malformed_live_markers_do_not_mask_check_verdict( gh.respond_pr_list([pr_json(headRefOid=head_of(wt), body=body)]) out, _ = expect_cli(capsys, exit_code, command, stderr_contains=("malformed loopzero checks block",)) history = HISTORY_CALLS if command == "pr" else [] - assert [c["argv"][:2] for c in gh.calls] == history + LOOKUP_CALLS + assert [c["argv"][:2] for c in gh.calls] == history + LOOKUP_CALLS + (LOOKUP_CALLS[-1:] if command == "check" else []) if command == "check": assert out.endswith("PASS\n") assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["exit_code"] == 0 @@ -1490,7 +1507,7 @@ def test_review_primary_posts_marker(wt: Path, gh: FakeGh, fake_bin: Path, capsy expected_diff = git(wt, "diff", "--no-color", "origin/main", head).encode("utf-8") git_calls.clear() out, _ = expect_cli(capsys, 5, "review", stderr="") - assert_git_cost(git_calls, 18, 1) + assert_git_cost(git_calls, 17, 1) assert out.splitlines()[0].startswith("reviewer paths pinned to origin/main@") assert out.splitlines()[-1] + "\n" == ( f"primary review by claude on {head[:12]}: request_changes "