From 2bebc1db8a14b615423814b9e266d05be18c70b7 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:46:57 +0100 Subject: [PATCH] Serialize PR body refreshes in the task worktree Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 4 +++- src/loopzero/cli.py | 46 ++++++++++++++++++++++++++++++++------------ tests/test_cli.py | 27 ++++++++++++++++++++++++-- 3 files changed, 62 insertions(+), 15 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 45039dae..69655a18 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -33,7 +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. CI and branch protection +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. +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, and branch protection remains essential. diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index d8e5033b..c4026272 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -4,6 +4,7 @@ import argparse import dataclasses +import fcntl import hashlib import importlib.metadata import io @@ -17,6 +18,7 @@ import tempfile import time from collections.abc import Callable, Iterator +from contextlib import contextmanager from datetime import UTC, datetime from functools import partial from pathlib import Path @@ -345,6 +347,18 @@ def _print_receipt(wt: Path, report: CheckReport, action: str) -> None: return +@contextmanager +def _lock_task_state(wt: Path) -> Iterator[None]: + directory = wt / ".loopzero" + directory.mkdir(parents=True, exist_ok=True) + fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + os.close(fd) + + def _save_report(wt: Path, report: CheckReport) -> None: path = wt / CHECKS_FILE path.parent.mkdir(parents=True, exist_ok=True) @@ -479,10 +493,14 @@ def replace(match: re.Match[str]) -> str: return prefix + content.lstrip("\n") -def _update_pr_checks(wt: Path, head: str, config: Config, pr: github.PR) -> None: - body = _pr_body(wt, head, pr.body) - if body != (pr.body or "").replace("\r\n", "\n"): - github.update_body(config.repo, pr.number, body) +def _update_pr_checks(wt: Path, head: str, config: Config, branch: str) -> None: + with _lock_task_state(wt): + live = github.pr_for_branch(config.repo, branch) + if live is None or live.state != "OPEN" or live.head_sha != head: + return + body = _pr_body(wt, head, live.body) + if body != live.body.replace("\r\n", "\n"): + github.update_body(config.repo, live.number, body) _REQUIRED_TASK_LINES = ("Context", "Problem", "Goal") @@ -526,9 +544,7 @@ def _refresh_pr_checks(wt: Path, config: Config) -> None: return try: branch, head = worktree.branch(wt), worktree.head(wt) - pr = github.pr_for_branch(config.repo, branch) - if pr is not None and pr.state == "OPEN" and pr.head_sha == head: - _update_pr_checks(wt, head, config, pr) + _update_pr_checks(wt, head, config, branch) except (github.GhError, OSError, ValueError, CliError) as exc: print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr) @@ -618,7 +634,7 @@ def cmd_pr(args: argparse.Namespace) -> int: f"task branch {branch} already merged as PR #{pr.number} ({pr.url}); " "run `loopzero start ` for a new task" ) - existing = _sync_task_narrative(wt, pr.body or "") if pr is not None else None + existing = _sync_task_narrative(wt, pr.body) if pr is not None else None body = _pr_body(wt, head, existing) force_lease = pr is not None and pr.state == "OPEN" and not _is_ancestor(wt, pr.head_sha, head) push = ["push", "-u", "origin"] @@ -639,8 +655,13 @@ def cmd_pr(args: argparse.Namespace) -> int: raise CliError(f"{exc}; remote moved since PR lookup; fetch and retry") from exc raise if pr is not None and pr.state == "OPEN": - if body != (pr.body or "").replace("\r\n", "\n"): - github.update_body(config.repo, pr.number, body) + with _lock_task_state(wt): + live = github.pr_view(config.repo, pr.number) + if live.state != "OPEN": + raise CliError(f"PR #{pr.number} closed during publication") + body = _pr_body(wt, head, _sync_task_narrative(wt, live.body)) + if body != live.body.replace("\r\n", "\n"): + github.update_body(config.repo, pr.number, body) else: pr = github.create_draft_pr( config.repo, branch, config.base_branch, _pr_title(wt, branch), body @@ -798,8 +819,9 @@ def cmd_review(args: argparse.Namespace) -> int: "inspect the cause and run `loopzero review --repost` to reconcile or explicitly retry" ) from exc try: - live = github.pr_view(config.repo, pr.number) - github.update_body(config.repo, pr.number, _append_review(live.body, result)) + with _lock_task_state(wt): + 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) return _review_verdict(result) diff --git a/tests/test_cli.py b/tests/test_cli.py index ec5202d3..2190054c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -367,7 +367,9 @@ def test_repeated_pr_does_not_rewrite_unchanged_body(wt: Path, gh: FakeGh, capsy before = len(gh.calls) assert run(capsys, "pr")[0] == 0 assert [c["argv"][:2] for c in gh.calls[before:]] == [ - ["api", branch_history_key().split(" ", 1)[1]], *LOOKUP_CALLS] + ["api", branch_history_key().split(" ", 1)[1]], *LOOKUP_CALLS, + ["api", f"repos/{REPO}/pulls/7"], + ] def test_check_does_not_rewrite_when_only_duration_changes(wt: Path, gh: FakeGh, capsys) -> None: @@ -415,6 +417,25 @@ 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") + update = cli._update_pr_checks + + def delay(path, sha, config, pr): + 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))) + update(path, sha, config, pr) + + monkeypatch.setattr(cli, "_update_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, @@ -877,7 +898,9 @@ def test_pr_updates_existing_open_pr(wt: Path, gh: FakeGh, capsys) -> None: assert code == 0 and out == URL + "\n" assert [c["argv"][:2] for c in gh.calls] == [ ["api", branch_history_key().split(" ", 1)[1]], *LOOKUP_CALLS, - ["api", f"repos/{REPO}/pulls/7"]] + ["api", f"repos/{REPO}/pulls/7"], + ["api", f"repos/{REPO}/pulls/7"], + ] assert "(no `loopzero check` run recorded)" in gh.calls[-1]["--input"]