From 15878aeec12be040edd0b4195a54a474c95c5249 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:37:46 +0100 Subject: [PATCH 1/3] Serialize updates to the pull request body Carry forward the reviewed change and tested merge resolution from #1099. Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 4 +++- src/loopzero/cli.py | 32 ++++++++++++++++++++------------ tests/test_cli.py | 24 ++++++++++++++++++++++-- 3 files changed, 45 insertions(+), 15 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d0e4dadf..0251a9a8 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 1c8c3bcc..e8c8a20b 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -519,10 +519,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") @@ -566,9 +570,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) @@ -659,7 +661,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"] @@ -675,8 +677,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 @@ -853,8 +860,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) diff --git a/tests/test_cli.py b/tests/test_cli.py index 2a8653f2..f86ad0fc 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -406,7 +406,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", [ @@ -437,6 +438,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, @@ -936,7 +956,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"] From 4eb0f7d5c02eba6019b3ef9e4322f55738054a4c Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:43:30 +0100 Subject: [PATCH 2/3] Abort PR pushes on ancestry probe errors Architecture-Review: unchanged; Git still owns ancestry and a known divergent PR head still requires the exact lease. Co-Authored-By: Codex --- src/loopzero/cli.py | 12 +++++++++--- tests/test_cli.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 2b65727e..fd4a64e7 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -168,6 +168,10 @@ def _is_ancestor(wt: Path, sha: str, head: str) -> bool: ["git", "merge-base", "--is-ancestor", sha, head], cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT, ) + if done.exit_code not in (0, 1): + detail = _proc.tail(done.stderr or done.stdout, 1) + raise CliError(f"git merge-base --is-ancestor failed (exit {done.exit_code}): " + f"{detail or 'retry the ancestry check'}") return done.exit_code == 0 @@ -667,9 +671,9 @@ def cmd_pr(args: argparse.Namespace) -> int: ) existing = _sync_task_narrative(wt, pr.body or "") if pr is not None else None body = _pr_body(wt, head, config, existing) - force_lease = pr is not None and pr.state == "OPEN" and not _is_ancestor(wt, pr.head_sha, head) + force_lease = False push = ["push", "-u", "origin"] - if force_lease: + if pr is not None and pr.state == "OPEN": # Only rewrite history this worktree has seen; an unknown remote head is someone else's. known = _proc.run(["git", "cat-file", "-e", f"{pr.head_sha}^{{commit}}"], cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT) @@ -677,7 +681,9 @@ def cmd_pr(args: argparse.Namespace) -> int: raise CliError( f"PR head {pr.head_sha[:12]} is not in this worktree; fetch and integrate it first" ) - push.extend(("--porcelain", f"--force-with-lease={branch}:{pr.head_sha}")) + force_lease = not _is_ancestor(wt, pr.head_sha, head) + if force_lease: + push.extend(("--porcelain", f"--force-with-lease={branch}:{pr.head_sha}")) push.append(branch) _git_push(wt, push, force_lease=force_lease) if pr is not None and pr.state == "OPEN": diff --git a/tests/test_cli.py b/tests/test_cli.py index 09023284..39a53fbb 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -941,6 +941,43 @@ def test_pr_updates_existing_open_pr(wt: Path, gh: FakeGh, capsys) -> None: assert "(no `loopzero check` run recorded)" in gh.calls[-1]["--input"] +@pytest.mark.parametrize( + ("probe", "diagnostic"), + [ + ("kill -TERM $$", "exit -15"), + ("echo 'fatal: unable to read commit' >&2; exit 128", "unable to read commit"), + ], +) +def test_pr_aborts_on_ancestry_probe_error(wt, gh, fake_tool, tmp_path, capsys, probe, diagnostic): + gh.respond_pr_list([pr_json(headRefOid=head_of(wt))]) + gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {}) + pushes = tmp_path / "pushes" + fake_tool("git", f'''\ +if [ "$1" = "merge-base" ] && [ "$2" = "--is-ancestor" ]; then {probe}; fi +if [ "$1" = "push" ]; then touch "{pushes}"; exit 0; fi +exec /usr/bin/git "$@" +''') + + code, out, err = run(capsys, "pr") + + assert (code, out) == (1, "") + assert "git merge-base --is-ancestor" in err and diagnostic in err + assert not pushes.exists() + assert all("--method" not in call["argv"] for call in gh.calls) + + +def test_pr_aborts_on_missing_remote_head(wt, gh, fake_tool, tmp_path, capsys): + gh.respond_pr_list([pr_json(headRefOid="a" * 40)]) + pushes = trace_pushes(fake_tool, tmp_path) + + code, out, err = run(capsys, "pr") + + assert (code, out) == (1, "") + assert "fetch and integrate it first" in err + assert not pushes.exists() + assert all("--method" not in call["argv"] for call in gh.calls) + + @pytest.mark.parametrize("hook_fails", [False, True]) def test_pr_uses_lease_for_rewritten_open_pr( wt: Path, repo: Path, gh: FakeGh, fake_tool, tmp_path: Path, capsys, hook_fails: bool From 3f5a27cba2113a4fa6ccca16044f065134aa54cd Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:45:07 +0100 Subject: [PATCH 3/3] Integrate receipt identity with serialized PR updates Carry the already-landed receipt rendering change from #1160 into the delta. Keep the check lookup and write under the shared lock and render from the freshly read PR when publishing. Architecture-Review: unchanged; receipt verification and serialized body updates retain their documented behavior. Co-Authored-By: Codex --- src/loopzero/cli.py | 56 +++++++++++++++++++++++++++------------------ tests/test_cli.py | 36 +++++++++++++++++++++++------ 2 files changed, 63 insertions(+), 29 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index e8c8a20b..5effd0b9 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -346,14 +346,18 @@ def _readiness( # --------------------------------------------------------------------------- checks report +def _check_report_matches(report: CheckReport, wt: Path, config: Config, head: str) -> bool: + return (report.head == head and not report.dirty + and tuple(result.command for result in report.results) == config.checks + and report.settings_sha256 is not None + and report.settings_sha256 == sandbox.settings_fingerprint(config, wt)) + + def _current_check_report(wt: Path, config: Config, head: str) -> CheckReport | None: report = _load_report(wt) - if (report is None or report.head != head or report.dirty or not report.ok - or tuple(result.command for result in report.results) != config.checks - or report.settings_sha256 is None - or report.settings_sha256 != sandbox.settings_fingerprint(config, wt)): - return None - return report + if report is not None and report.ok and _check_report_matches(report, wt, config, head): + return report + return None def _print_receipt(wt: Path, report: CheckReport, action: str) -> None: @@ -434,12 +438,14 @@ def _load_report(wt: Path) -> CheckReport | None: return None -def _validation_section(wt: Path, head: str) -> str: +def _validation_section(wt: Path, head: str, config: Config) -> str: loaded = _load_report(wt) if loaded is None: return "(no `loopzero check` run recorded)" recorded, results = loaded.head, loaded.results lines = [f"Recorded for `{recorded[:12]}`" + ("" if recorded == head else " (not current head)")] + if not _check_report_matches(loaded, wt, config, head): + lines[0] += " (unverified, run `loopzero check`)" lines += [ f"- `{r.command}`: exit {r.exit_code}" for r in results ] or ["- (no check commands configured)"] @@ -456,10 +462,10 @@ def _validation_section(wt: Path, head: str) -> str: ) -def _pr_body(wt: Path, head: str, existing: str | None = None) -> str: +def _pr_body(wt: Path, head: str, config: Config, existing: str | None = None) -> str: """Refresh only generated checks; the live body owns existing PR prose.""" body = (existing if existing is not None else worktree.task_text(wt)).replace("\r\n", "\n") - block = f"{_CHECKS_START}\n{_validation_section(wt, head)}\n{_CHECKS_END}" + block = f"{_CHECKS_START}\n{_validation_section(wt, head, config)}\n{_CHECKS_END}" pattern = re.compile(r"^## (?:Validation|Checks)\n(.*?)(?=^## |\Z)", re.DOTALL | re.MULTILINE) match = pattern.search(body) @@ -519,14 +525,10 @@ def replace(match: re.Match[str]) -> str: return prefix + content.lstrip("\n") -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) +def _update_pr_checks(wt: Path, head: str, config: Config, pr: github.PR) -> None: + 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) _REQUIRED_TASK_LINES = ("Context", "Problem", "Goal") @@ -563,6 +565,14 @@ def _append_review(body: str, result: ReviewResult) -> str: def _refresh_pr_checks(wt: Path, config: Config) -> None: + try: + with _lock_task_state(wt): + _refresh_existing_pr_checks(wt, config) + except OSError as exc: + print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr) + + +def _refresh_existing_pr_checks(wt: Path, config: Config) -> None: """Best-effort refresh only when local HEAD is the existing PR head.""" argv = ["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"] try: @@ -570,7 +580,9 @@ def _refresh_pr_checks(wt: Path, config: Config) -> None: if upstream.exit_code != 0: return branch, head = worktree.branch(wt), worktree.head(wt) - _update_pr_checks(wt, head, config, branch) + 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) except (github.GhError, _proc.ProcTimeout, OSError, ValueError, CliError) as exc: print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr) @@ -648,7 +660,7 @@ def cmd_check(args: argparse.Namespace) -> int: def cmd_pr(args: argparse.Namespace) -> int: - wt, config = _context(args) + wt, config = _context(args, pin_checks=True) branch, head = worktree.branch(wt), worktree.head(wt) _require_task_branch(config, branch) _require_clean(wt) @@ -661,8 +673,8 @@ 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) if pr is not None else None - body = _pr_body(wt, head, existing) + existing = _sync_task_narrative(wt, pr.body or "") if pr is not None else None + body = _pr_body(wt, head, config, existing) force_lease = pr is not None and pr.state == "OPEN" and not _is_ancestor(wt, pr.head_sha, head) push = ["push", "-u", "origin"] if force_lease: @@ -681,7 +693,7 @@ def cmd_pr(args: argparse.Namespace) -> int: 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)) + body = _pr_body(wt, head, config, _sync_task_narrative(wt, live.body or "")) if body != live.body.replace("\r\n", "\n"): github.update_body(config.repo, pr.number, body) else: diff --git a/tests/test_cli.py b/tests/test_cli.py index f86ad0fc..25bf3b9c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -394,10 +394,11 @@ def test_initial_pr_keeps_human_validation(wt: Path, gh: FakeGh, capsys) -> None def test_pr_body_is_unchanged_when_checks_are_unchanged(wt: Path, gh: FakeGh, capsys, command) -> None: head = head_of(wt) if command == "check": + config = cli._load_config(SimpleNamespace(config=None, command="ready"), wt, pin_checks=True) cli._save_report(wt, CheckReport(head, False, ( CheckResult("echo ok", 0, 999.0, "ok"), CheckResult("test -f README.md", 0, 999.0, ""), - ))) + ), cli.sandbox.settings_fingerprint(config, wt))) gh.respond_pr_list([pr_json(headRefOid=head)]) gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {}) assert run(capsys, "pr")[0] == 0 @@ -443,15 +444,15 @@ def test_delayed_check_preserves_review_summary(wt, gh, fake_bin, capsys, monkey 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 + refresh = cli._refresh_pr_checks - def delay(path, sha, config, pr): + 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))) - update(path, sha, config, pr) + refresh(path, config) - monkeypatch.setattr(cli, "_update_pr_checks", delay) + 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")) @@ -943,7 +944,7 @@ def test_pr_migrates_old_checks_heading_to_validation(wt: Path) -> None: task = wt / ".loopzero" / "task.md" task.write_text(task.read_text().replace("## Validation", "## Checks")) - body = cli._pr_body(wt, head_of(wt)) + body = cli._pr_body(wt, head_of(wt), cli.config_mod.load(wt / "workflow.toml")) assert "## Checks" not in body assert body.count("## Validation") == 1 @@ -4330,7 +4331,7 @@ def test_load_report_requires_integer_exit_code(wt, head, capsys, exit_code, ok) def test_passive_receipt_load_is_silent(wt, gh, capsys, head): arm_approved_ready_pr(gh, head, wt) cli._load_report(wt) - cli._validation_section(wt, head) + cli._validation_section(wt, head, cli.config_mod.load(wt / "workflow.toml")) assert "receipt " not in capsys.readouterr().out @@ -4486,3 +4487,24 @@ def test_generated_pr_body_limit(wt, gh, capsys, monkeypatch, create, extra): assert err == "" assert len(writes) == 1 assert json.loads(writes[0]["--input"])["body"] == prose + suffix + + +def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys): + head = head_of(wt) + live = "# PR\n\n## Validation\nManual validation evidence.\n" + gh.respond_pr_list([pr_json(headRefOid=head, body=live)]) + gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {}) + cli._save_report(wt, CheckReport(head, False, (CheckResult("echo ok", 0, 0.0, ""),))) + + assert run(capsys, "pr")[0] == 0 + draft = json.loads(gh.calls[-1]["--input"])["body"] + assert "unverified" in draft and "run `loopzero check`" in draft + assert "Manual validation evidence." in draft + + git(wt, "push", "-q", "-u", "origin", "lz/t1") + gh.respond_pr_list([pr_json(headRefOid=head, body=draft)]) + assert run(capsys, "check")[0] == 0 + draft = json.loads(gh.calls[-1]["--input"])["body"] + assert "unverified" not in draft + assert f"Recorded for `{head[:12]}`\n- `echo ok`: exit 0" in draft + assert "Manual validation evidence." in draft