Skip to content
Closed
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
4 changes: 3 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
32 changes: 20 additions & 12 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,10 +516,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")
Expand Down Expand Up @@ -563,9 +567,7 @@ def _refresh_pr_checks(wt: Path, config: Config) -> None:
if upstream.exit_code != 0:
return
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, _proc.ProcTimeout, OSError, ValueError, CliError) as exc:
print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr)

Expand Down Expand Up @@ -656,7 +658,7 @@ def cmd_pr(args: argparse.Namespace) -> int:
f"task branch {branch} already merged as PR #{pr.number} ({pr.url}); "
"run `loopzero start <new-task-slug>` 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

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: Body built before the push is now only used for validation and draft creation

For an existing open PR, existing/body at lines 637-638 are now discarded and rebuilt from live.body inside the lock (line 662). Building it early still has a purpose: it raises on malformed markers or an oversized body before the push, and the create-draft path uses it. A short comment saying so would stop a later cleanup from removing it, or from going back to reusing the stale body in the update branch.

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"]
Expand All @@ -672,8 +674,13 @@ 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":
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
Expand Down Expand Up @@ -850,8 +857,9 @@ 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:
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)
Expand Down
24 changes: 22 additions & 2 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,8 @@ 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 []
assert [c["argv"][:2] for c in gh.calls[before:]] == history + LOOKUP_CALLS
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


@pytest.mark.parametrize("body", [
Expand Down Expand Up @@ -424,6 +425,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):

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: Delayed-check test checks the re-read, not the lock

delay runs review all the way through before it calls the real _update_pr_checks, so the check never actually overlaps with the review. The test would still pass if _lock_task_state were a no-op, because it only shows that the check reads the live body again before writing. That re-read does cover the acceptance criterion about a delayed check, but nothing tests the serialization. Smallest fix: add a focused test that holds _lock_task_state(wt) (for example from a thread or a second process). It should assert that _update_pr_checks / the review append does not call pr_view/pr_for_branch until the lock is released.

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,
Expand Down Expand Up @@ -921,7 +941,7 @@ def test_pr_updates_existing_open_pr(wt: Path, gh: FakeGh, capsys) -> None:
code, out, _ = run(capsys, "pr")
assert code == 0 and out == URL + "\n"
assert [c["argv"][:2] for c in gh.calls] == (
HISTORY_CALLS + LOOKUP_CALLS + [["api", f"repos/{REPO}/pulls/7"]])
HISTORY_CALLS + LOOKUP_CALLS + [["api", f"repos/{REPO}/pulls/7"]] * 2)
assert "(no `loopzero check` run recorded)" in gh.calls[-1]["--input"]


Expand Down
Loading