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
34 changes: 27 additions & 7 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -565,6 +569,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:
Expand Down Expand Up @@ -668,22 +680,29 @@ 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)
if known.exit_code != 0:
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":
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, 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:
pr = github.create_draft_pr(
config.repo, branch, config.base_branch, _pr_title(wt, branch), body
Expand Down Expand Up @@ -860,8 +879,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
61 changes: 59 additions & 2 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,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 @@ -459,6 +460,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")
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,
Expand Down Expand Up @@ -1040,10 +1060,47 @@ 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"]


@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
Expand Down
Loading