Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
32 changes: 18 additions & 14 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: PR body writers can now publish another check's in-progress checkpoint from the same worktree

_refresh_pr_checks and cmd_pr (line 734) used to read checks.json through _validation_section while holding worktree.lock_local_state. That stopped them from seeing the partial reports that sandbox.run_checks writes through checkpoint=partial(_save_report, ...) while a check is running. They now hold only github.pr_lock.

How it fails: in one worktree, check A finishes and releases the worktree lock (line 684). Check B starts and writes a partial checkpoint. A's refresh, or a concurrent loopzero pr, then puts B's incomplete results into the Validation section. Before this change, both would have waited for B's final receipt. B's own refresh normally overwrites it later. But that refresh is best-effort, so if it fails, or B is interrupted, the PR keeps the partial Validation.

Smallest fix: take the worktree lock around the PR lock in both places (with worktree.lock_local_state(wt), github.pr_lock(...)). This can't deadlock, because review takes only pr_lock and no path takes pr_lock before the worktree lock. Alternatively, document that body writers may publish checkpoints. Either way, the docstring of worktree.lock_local_state (worktree.py:131) still says it serializes "PR-body updates for this worktree", which is no longer true and should be updated.

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)

Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)


Expand Down
61 changes: 39 additions & 22 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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")

Expand Down Expand Up @@ -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", [
Expand Down Expand Up @@ -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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Pause hook in the acceptance test patches the process-wide fcntl.flock

github.fcntl is the shared fcntl module, so monkeypatch.setattr(github.fcntl, "flock", acquire) also changes every worktree and state lock taken in the review thread. The test only works because review's first contended LOCK_EX happens to be the PR lock. If review later takes a contended worktree lock first, proceed would be set at the wrong point, and the test could still pass without proving it paused at the PR-lock handoff. Consider scoping the hook to the PR-lock path, for example by checking that fd.name is under github.PR_LOCK_DIR.

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)])
Expand All @@ -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
Expand Down Expand Up @@ -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 "
Expand Down
Loading