diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c22c54d7..6c5001a3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -33,8 +33,9 @@ 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. On one host, PR body +writers with the same home directory share a repository-and-PR lock from the live +read through the update. Receipt publication retains its 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 2ae035b3..e8ee6c4e 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -21,6 +21,7 @@ import tempfile import time from collections.abc import Callable, Iterator +from contextlib import contextmanager from functools import partial, wraps from pathlib import Path @@ -578,18 +579,41 @@ def _append_review(body: str, result: ReviewResult) -> str: return (body[:match.start(1)] + line + "\n\n" + body[match.end():]).rstrip() + "\n" +@contextmanager +def _lock_pr_body(repo: str, number: int) -> Iterator[None]: + key = hashlib.sha256(f"{repo.casefold()}#{number}".encode()).hexdigest() + path = Path.home() / ".cache" / "loopzero" / "pr-bodies" / key + path.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + os.close(fd) + + +def _refresh_pr_review(repo: str, number: int, result: ReviewResult) -> None: + with _lock_pr_body(repo, number): + live = github.pr_view(repo, number) + github.update_body(repo, number, _append_review(live.body, result)) + + 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 _lock_pr_body(config.repo, pr.number): + live = github.pr_view(config.repo, pr.number) + if live.state == "OPEN" and live.head_sha == head: + 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) @@ -716,7 +740,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 and pr.state == "OPEN": - with worktree.lock_local_state(wt): + with _lock_pr_body(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") @@ -876,9 +900,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: "inspect the cause and run `loopzero review --repost` to reconcile or explicitly retry" ) from exc try: - with worktree.lock_local_state(wt): - live = github.pr_view(config.repo, pr.number) - github.update_body(config.repo, pr.number, _append_review(live.body, result)) + _refresh_pr_review(config.repo, pr.number, 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) return _review_verdict(result) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 4d38c4de..95dd8478 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -118,11 +118,6 @@ def _local_state_directory(wt: Path, *, create: bool = False, lock: bool = False os.close(fd) -def lock_local_state(wt: Path): - """Serialize receipt publication and PR-body updates for this worktree.""" - return _local_state_directory(wt, create=True, lock=True) - - def _regular_state(wt: Path, fd: int, name: str) -> bool: with suppress(FileNotFoundError): if not stat.S_ISREG(os.stat(name, dir_fd=fd, follow_symlinks=False).st_mode): diff --git a/tests/test_cli.py b/tests/test_cli.py index aab7989a..fe2f54c1 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -11,11 +11,13 @@ import signal import subprocess import sys +from concurrent.futures import ThreadPoolExecutor from contextlib import suppress from dataclasses import asdict, replace from email.utils import formatdate from pathlib import Path from select import select +from threading import Event, current_thread, main_thread from types import SimpleNamespace from unittest.mock import Mock from urllib.parse import quote @@ -506,8 +508,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 + ( - [["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 @@ -515,11 +517,48 @@ 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[-1]["--input"])["body"] assert body.count("## Validation") == 1 assert_contains(body, f"Recorded for `{head_of(wt)[:12]}`", "- `echo ok`: exit 0") +def test_check_and_review_serialize_shared_pr_body(wt, tmp_path, capsys, monkeypatch): + git(wt, "push", "-q", "-u", "origin", "lz/t1") + other = tmp_path / "review" + git(wt, "clone", "-q", "-b", "lz/t1", git(wt, "remote", "get-url", "origin").strip(), str(other)) + monkeypatch.chdir(other) + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setattr(cli, "_context", lambda *_, **__: (wt, config.load_trusted(wt))) + pr = github.pr_from_rest(rest_pr_json(pr_json(headRefOid=head_of(wt), body="# Human prose\n"))) + monkeypatch.setattr(github, "pr_for_branch", lambda *_, **__: pr) + bodies, proceed, flock = [pr.body], Event(), cli.fcntl.flock + monkeypatch.setattr(github, "pr_view", lambda *_: replace(pr, body=bodies[-1])) + + def acquire(fd, flags): + if current_thread() is not main_thread(): + try: + return flock(fd, flags | cli.fcntl.LOCK_NB) + except BlockingIOError: + proceed.set() + return flock(fd, flags) + + result = ReviewResult("claude", pr.head_sha, "primary", "approve", (), "") + with ThreadPoolExecutor(1) as pool: + def patch(repo, number, body): + if "## Review" not in body: + pending.append(pool.submit(cli._refresh_pr_review, repo, number, result)) + assert proceed.wait(5) + bodies.append(body) + proceed.set() + + pending = [] + monkeypatch.setattr(cli.fcntl, "flock", acquire) + monkeypatch.setattr(github, "update_body", patch) + assert run(capsys, "check")[0] == 0 + pending[0].result(timeout=5) + assert_contains(bodies[-1], "# Human prose", "## Validation", "Recorded for", "## Review", "approve") + + @pytest.mark.parametrize("newline", ["\n", "\r\n"]) @pytest.mark.parametrize("command", ["check", "pr"]) def test_refresh_preserves_live_pr_evidence( @@ -582,8 +621,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", [ @@ -611,25 +649,6 @@ 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): - 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)]) - 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 - final = json.loads(gh.calls[-1]["--input"])["body"] - assert all(text in final for text in ("Human evidence.", "Recorded for", "- primary, claude")) - - @pytest.mark.parametrize("command,exit_code", [("check", 0), ("pr", 1)]) def test_malformed_live_markers_do_not_mask_check_verdict( wt: Path, gh: FakeGh, capsys, command: str, exit_code: int, @@ -639,7 +658,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 @@ -1487,7 +1506,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 "