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
6 changes: 5 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,11 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
head or an eligible review covering an ancestor, blocking findings
(unresolved threads a review publisher opened with a head-bound marker line),
target branch and required CI. The receipt must record a clean passing run
at that head with the current commands and check settings digest. A settings
at that head with the current commands and check settings digest. Ready and
merge validate the PR, head and hold before checking the local receipt.
An invalid receipt stops the command before it fetches remote readiness
evidence. Writes to advance readiness or merging recheck the receipt.
Status continues to collect all readiness diagnostics. A settings
change or an older receipt without the digest requires a fresh check. The
digest covers execution and stage reuse settings without recording raw
environment values. For local sandbox receipts it omits inherited `PATH`,
Expand Down
43 changes: 30 additions & 13 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ def _require_task_branch(config: Config, branch: str) -> None:
raise CliError(f"branch {branch!r} is the configured base; use a task branch")


def _require_pr(config: Config, branch: str, *, allow_merged: bool = False) -> github.PR:
pr = github.pr_for_branch(config.repo, branch)
def _require_pr(config: Config, branch: str, *, allow_merged: bool = False, list_only: bool = False) -> github.PR:
pr = github.pr_for_branch(config.repo, branch, list_only=list_only)
if pr is None:
raise CliError(f"no pull request for {branch}; run `loopzero pr` first")
if pr.state != "OPEN" and not (allow_merged and pr.state == "MERGED"):
Expand Down Expand Up @@ -304,12 +304,18 @@ def _review_cap_reason(config: Config, pr: github.PR, head: str, reviews: list[d
MERGEABILITY_PENDING = "GitHub is computing mergeability"


def _readiness_precheck(wt: Path, config: Config, pr: github.PR, head: str, diagnostics: bool) -> str | None:
return github.merge_hold(pr.number, pr.labels) or (
None if diagnostics else _check_report_problem(_load_report(wt), wt, config, head)
)


def _readiness(
wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None,
*, workflow_wait: bool = False, announce_receipt: bool = False,
*, workflow_wait: bool = False, announce_receipt: bool = False, diagnostics: bool = False,
) -> github.Readiness:
if hold := github.merge_hold(pr.number, pr.labels):
return github.Readiness(False, (hold,))
if problem := _readiness_precheck(wt, config, pr, head, diagnostics):
return github.Readiness(False, (problem,))
if reviews is None:
reviews = _pr_reviews(config.repo, pr.number)
publishers = config.review_publishers or (github.login(),)
Expand All @@ -333,12 +339,6 @@ def _readiness(
),
publishers=publishers,
)
report = _load_report(wt)
receipt_problem = _check_report_problem(report, wt, config, head)
if receipt_problem:
result = github.Readiness(False, (*result.reasons, receipt_problem))
elif announce_receipt:
_print_receipt(wt, report, "accepted")
if config.merge_strategy == "mergify" and pr.state == "OPEN":
behind = github.behind_reason(pr, head if review else None)
reasons = result.reasons
Expand All @@ -356,6 +356,12 @@ def _readiness(
))
if pr.state == "OPEN" and pr.mergeable == "UNKNOWN":
result = dataclasses.replace(result, ready=False, reasons=(*result.reasons, MERGEABILITY_PENDING))
report = _load_report(wt)
receipt_problem = _check_report_problem(report, wt, config, head)
if receipt_problem:
result = github.Readiness(False, (*result.reasons, receipt_problem))
elif announce_receipt:
_print_receipt(wt, report, "accepted")
return result


Expand Down Expand Up @@ -395,6 +401,11 @@ def _current_check_report(wt: Path, config: Config, head: str) -> CheckReport |
return None if _check_report_problem(report, wt, config, head) else report


def _require_receipt(wt: Path, config: Config, head: str) -> None:
if problem := _check_report_problem(_load_report(wt), wt, config, head):
raise CliError(problem)


def _print_receipt(wt: Path, report: CheckReport, action: str) -> None:
"""Best-effort transcript identity; never authority or environment attestation."""
try:
Expand Down Expand Up @@ -1210,7 +1221,7 @@ def _pr_readiness(
"""PR plus readiness; readiness is None only for an already merged PR (allow_merged)."""
head = worktree.head(wt)
_require_task_branch(config, branch)
pr = _require_pr(config, branch, allow_merged=allow_merged)
pr = _require_pr(config, branch, allow_merged=allow_merged, list_only=True)
_require_pushed(pr, head)
if pr.state == "MERGED":
return pr, None
Expand Down Expand Up @@ -1312,6 +1323,7 @@ def cmd_ready(args: argparse.Namespace) -> int:
kicked = bool(waiting)
started = time.monotonic()
if waiting:
_require_receipt(wt, config, pr.head_sha)
github.mark_ready(config.repo, pr.number)
if args.wait is None:
pending = f"; {MERGEABILITY_PENDING}" if pr.mergeable == "UNKNOWN" else ""
Expand All @@ -1331,6 +1343,7 @@ def cmd_ready(args: argparse.Namespace) -> int:
assert readiness is not None
_prequeue_size_budget(wt, config, pr, readiness)
if readiness.ready and pr.is_draft and not kicked:
_require_receipt(wt, config, pr.head_sha)
github.mark_ready(config.repo, pr.number)
if args.wait is not None:
waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=True, started=started,
Expand Down Expand Up @@ -1520,6 +1533,7 @@ def _wait_for_checks(
return current, None, kicked
readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True)
if not kicked and _draft_checks_waiting(config, current, readiness):
_require_receipt(wt, config, current.head_sha)
github.mark_ready(config.repo, pr.number)
print("marked ready; " + "; ".join(readiness.reasons))
return _wait_for_checks(wt, config, pr, timeout, kicked=True, started=started,
Expand Down Expand Up @@ -1724,6 +1738,7 @@ def _merge_with_mergify(
return sha
confirmed = state is not None
if confirmed and not confirmed_marker:
_require_receipt(wt, config, pr.head_sha)

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: New receipt guard before mark_confirmed has no test and is applied inconsistently

The new _require_receipt before mergify.mark_confirmed only runs when the PR is already in the Mergify queue and has no confirmed marker. No test in this delta reaches that state. In the during-gates merge case, membership is None, so the run takes the request path, which was already guarded at line 1752. Also, this write does not admit anything: the PR is already queued. If the receipt is invalid, the command errors, but the PR stays in the queue and can still land. It is just left without the confirmed marker. The same marker write in _wait_for_mergify (line 1698) stays unguarded. Pick one rule and apply it to both: guard both marker writes, or guard neither and keep receipt checks only on admission writes (request and merge). Then add a parametrized case for the guarded path, for example membership returning a state with confirmed_marker=False and the receipt removed during gates.

mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue)
if not confirmed and confirmed_marker:
closed: list[github.GhError] = []
Expand All @@ -1734,6 +1749,7 @@ def _merge_with_mergify(
_prequeue_size_budget(wt, config, pr, readiness, project=admit_by is None)
if admit_by is not None and time.monotonic() > admit_by:
raise _AdmissionDeadline
_require_receipt(wt, config, pr.head_sha)
mergify.request(config.repo, pr.number, pr.head_sha, queue)
if deadline is not None:
return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), confirmed)
Expand Down Expand Up @@ -1791,6 +1807,7 @@ def cmd_merge(args: argparse.Namespace) -> int:
if admit_by is not None and time.monotonic() > admit_by:
print(f"timed out before merging PR #{pr.number}")
return 3
_require_receipt(wt, config, pr.head_sha)
sha = github.merge(config.repo, pr.number, config.merge_strategy, pr.head_sha)
if sha is None and args.wait is not None:
sha = _wait_for_merge(config, pr, max(0.0, deadline - time.monotonic()))
Expand Down Expand Up @@ -1884,7 +1901,7 @@ def cmd_status(args: argparse.Namespace) -> int:
print(f"review: {latest.kind} on {latest.head[:12]} ({latest.state.lower() or 'posted'})")
else:
print("review: none on this PR")
readiness = _readiness(wt, config, pr, head, reviews)
readiness = _readiness(wt, config, pr, head, reviews, diagnostics=True)
print(f"ready: {'yes' if readiness.ready else 'no'}")
for reason in readiness.reasons:
print(f" - {reason}")
Expand Down
13 changes: 7 additions & 6 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -668,13 +668,14 @@ def _confirm_branch_pr(repo: str, branch: str, endpoint: str, number: int, state
return pr


def pr_for_branch(repo: str, branch: str, *, open_only: bool = False) -> PR | None:
def pr_for_branch(repo: str, branch: str, *, open_only: bool = False, list_only: bool = False) -> PR | None:
"""Return the open PR, falling back to the most recent closed PR unless open_only."""
endpoint, matches = _commit_branch_prs(repo, branch)
open_matches = [row for row in matches if row["state"] == "open"]
if open_matches:
newest = max(open_matches, key=lambda row: (row["created_at"], row["number"]))
return _confirm_branch_pr(repo, branch, endpoint, newest["number"], "OPEN")
if not list_only:

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: list_only makes ready/merge find PRs differently from status and merge --cancel

list_only=True skips the commit-association lookup (_commit_branch_prs) that is still the main path for status (cli.py:1898), merge --cancel (cli.py:1775) and other _require_pr callers. After this change, ready/merge take the open PR from the head-filtered list, while the other commands take the newest commit-associated PR. These can disagree, for example when the list endpoint lags after a PR is opened or reopened. The diff adds no test of pr_for_branch(list_only=True) in test_github.py. Consider either moving all callers to one lookup or adding a test that pins the two-read contract and the open-before-closed fallback order.

endpoint, matches = _commit_branch_prs(repo, branch)
open_matches = [row for row in matches if row["state"] == "open"]
if open_matches:
newest = max(open_matches, key=lambda row: (row["created_at"], row["number"]))
return _confirm_branch_pr(repo, branch, endpoint, newest["number"], "OPEN")

# A closed association cannot rule out an open PR or newer closed history.
owner = repo.split("/", 1)[0]
Expand Down
120 changes: 60 additions & 60 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3097,54 +3097,52 @@ def test_ready_draft_with_open_blocking_finding_does_not_mark_ready(
assert all(c["argv"][:2] != ["pr", "ready"] for c in gh.calls)


@pytest.mark.parametrize("draft,condition,reason", [
(False, "missing", "run loopzero check at this head"),
*((False, condition, "check receipt") for condition in ("wrong-head", "failed", "dirty")),
(False, "wrong-commands", "check receipt's plan differs from the trusted workflow."),
(False, "legacy", "check receipt is missing its settings fingerprint."),
(False, "incompatible", "check receipt has an incompatible settings fingerprint."),
(False, "matching", None),
(True, "stale", "check receipt is for aaaaaaaaaaaa."),
(True, "red", "check receipt records a failed stage."),
(True, "dirty", "check receipt was recorded in a dirty worktree."),
(True, "commands", "check receipt's plan differs from the trusted workflow."),
*((True, condition, "check receipt is incomplete.") for condition in ("empty", "checkpoint")),
@pytest.mark.parametrize("command", ["ready", "merge"])

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: Rewritten receipt test drops the valid-receipt and recovery-hint cases

The old parametrization included (False, "matching", None), which checked that ready succeeds with a current receipt. It also asserted the full recovery text for legacy/incompatible ("Run loopzero check in this worktree at this head with the same current CLI ..."). The new test_delivery_requires_current_receipt only checks failures and a reason prefix. The 'Valid receipts still run the existing gates' acceptance point and the recovery guidance now depend on coverage elsewhere. Consider adding back a valid case that expects exit 0 and receipt accepted: for both ready and merge.

@pytest.mark.parametrize("condition,reason", [
*((case, "run loopzero check at this head") for case in ("missing", "during-gates", "transient")),
("head", "check receipt is for aaaaaaaaaaaa."),
("failed", "check receipt records a failed stage."), ("dirty", "check receipt was recorded in a dirty worktree."),
("plan", "check receipt's plan differs from the trusted workflow."),
("legacy", "check receipt is missing its settings fingerprint."),
("incompatible", "check receipt has an incompatible settings fingerprint."),
("empty", "check receipt is incomplete."), ("checkpoint", "check receipt is incomplete."),
])
def test_ready_requires_clean_successful_local_report_at_head(wt, gh, capsys, condition, head, draft, reason):
arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=draft, readiness={
"local_exit": int(condition == "failed"), "dirty": condition == "dirty",
})
def test_delivery_requires_current_receipt(wt, gh, capsys, head, monkeypatch, command, condition, reason):
head = commit_mergify_configuration(wt) if command == "merge" else head
monkeypatch.setattr(mergify, "configured", lambda *_: condition == "during-gates" or pytest.fail("remote gate read"))
arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=command == "ready")
gh.respond(" ".join(BRANCH_READ), {"object": {"sha": head}})
path = wt / ".loopzero/checks.json"
if condition == "missing":
report = json.loads(path.read_text())
if condition == "during-gates":
readiness = github.readiness

def replace_receipt(*args, **kwargs):
path.unlink()
return readiness(*args, **kwargs)

monkeypatch.setattr(github, "readiness", replace_receipt)
elif condition in {"missing", "transient"}:
path.unlink()
elif condition not in {"failed", "dirty", "matching"}:
report = json.loads(path.read_text())
if condition in {"wrong-head", "stale"}:
report["head"] = ("a" if draft else "0") * 40
elif condition == "wrong-commands":
report["results"].pop()
elif condition == "commands":
report["results"][0]["command"] = "changed"
elif condition == "empty":
report["results"] = []
elif condition == "checkpoint":
report["results"][1:] = [asdict(CheckResult("<checks incomplete>", 1, 0.0, ""))]
elif condition == "red":
report["results"][0]["exit_code"] = 1
elif condition == "legacy":
del report["settings_sha256"]
else:
report["settings_sha256"] = "0" * 64
if condition == "transient":
monkeypatch.setattr(github, "_retry_sleep", lambda _: None)
gh.respond(pr_list_key(), {"stdout": "", "exit_code": 1, "stderr": "HTTP 503"}, [{"number": 7}])

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: The transient case also unlinks the receipt, so it mixes two conditions

The transient case removes the receipt and also injects a 503 on the PR list. It checks that a retry happens before the receipt is rejected. It never checks that a transient error with a valid receipt still goes on to the remote gates. That is fine for the acceptance criteria, but the test name suggests broader coverage. Consider naming it missing-after-transient, or add a valid-receipt transient replay, so that a regression that drops the retry for valid receipts would be caught.

else:
results = report["results"]
report.update({
"head": {"head": "a" * 40}, "dirty": {"dirty": True},
"failed": {"results": [dict(results[0], exit_code=1), *results[1:]]},
"plan": {"results": results[:-1]}, "empty": {"results": []},
"legacy": {"settings_sha256": None}, "incompatible": {"settings_sha256": "0" * 64},
"checkpoint": {"results": [results[0], asdict(CheckResult("<checks incomplete>", 1, 0, ""))]},
}[condition])
path.write_text(json.dumps(report))

out, _ = expect_cli(capsys, int(reason is not None), "ready")
if reason:
assert f"not ready: {reason}" in out
if draft:
assert "receipt accepted:" not in out
if condition in {"legacy", "incompatible"}:
assert ("Run loopzero check in this worktree at this head with the same current CLI and effective "
"settings as ready, using a local coordinator for delegated stages." in out)
out, err = expect_cli(capsys, 1, command, *(["--wait"] if command == "merge" or condition == "during-gates" else []))
assert reason in out + err and "receipt accepted:" not in out
assert all(github._read_only(tuple(c["argv"])) for c in gh.calls)
if condition != "during-gates":
expected = [PR_LIST_READ, *LOOKUP_CALLS[1:]] if condition == "transient" else LOOKUP_CALLS[1:]
assert [c["argv"][:2] for c in gh.calls] == expected


@pytest.fixture
Expand All @@ -3155,8 +3153,8 @@ def check_environment(wt, gh, head, tmp_path):
return path, policy, ("--config", str(path))


@pytest.mark.parametrize("case", ["explicit", "ready", "merge", "inherited", "fixed"])
def test_ready_checks_effective_receipt_environment(gh, capsys, head, monkeypatch, case, check_environment):
@pytest.mark.parametrize("case", ["explicit", "ready", "merge", "fresh", "inherited", "fixed"])
def test_ready_checks_effective_receipt_environment(wt, gh, capsys, head, monkeypatch, case, check_environment):
config_path, config, args = check_environment
inherited = case in {"inherited", "fixed"}
if inherited:
Expand All @@ -3172,26 +3170,28 @@ def test_ready_checks_effective_receipt_environment(gh, capsys, head, monkeypatc
monkeypatch.setenv("CHECK_POLICY", "new")
else:
new_config = config.replace('CHECK_POLICY = "old"', 'CHECK_POLICY = "new"')
if case in {"ready", "merge"}:
arm_check_runs(gh, head, [{"name": "checks", "status": "in_progress"}])
if case in {"ready", "merge", "fresh"}:
arm_check_progress(gh, head, "pending")
command = "merge" if case == "fresh" else case

def change_policy(_seconds):
assert config_path.read_text() == config
config_path.write_text(new_config)
if case == "fresh":
cfg = cli._load_config(SimpleNamespace(config=config_path, command=command), wt, pin_checks=True)
cli._save_report(wt, cli.dataclasses.replace(cli._load_report(wt),
settings_sha256=cli.sandbox.settings_fingerprint(cfg, wt)))

monkeypatch.setattr(cli, "_sleep", change_policy)
expect_cli(capsys, 1, *args, case, "--wait",
stderr_contains=("workflow settings changed while waiting; run loopzero check",))
arm_check_runs(gh, head, [{"name": "checks", "status": "completed", "conclusion": "success"}])
hint = "retry with the current settings" if case == "fresh" else "run loopzero check"
expect_cli(capsys, 1, *args, command, "--wait", stderr_contains=(f"workflow settings changed while waiting; {hint}",))
arm_check_progress(gh, head, "success")
else:
config_path.write_text(new_config)
if case == "fixed":
expect_cli(capsys, 0, *args, "ready")
else:
expect_cli(capsys, 1, *args, "ready",
stdout_contains=("not ready: check receipt has an incompatible settings fingerprint.",))
if not inherited:
expect_cli(capsys, 1, *args, "check")
passing = case in {"fixed", "fresh"}
out, _ = expect_cli(capsys, int(not passing), *args, "ready")
assert passing or "not ready: check receipt has an incompatible settings fingerprint." in out
if not (passing or inherited):
expect_cli(capsys, 1, *args, "check")


def test_check_refuses_unverified_receipt_after_runner_retarget(wt, gh, capsys, head, tmp_path):
Expand Down Expand Up @@ -3519,7 +3519,7 @@ def membership(*_):
code, out, err = run(capsys, "merge", *(["--wait=1"] if wait else []))

calls = [c["argv"][:2] for c in gh.calls]
assert calls.count(LOOKUP_CALLS[0]) == 1
assert calls.count(LOOKUP_CALLS[0]) == 0
assert calls.count(detail.split()) == 2
if outcome == "merged":
assert (code, err) == (0, "") and out.splitlines()[-1] == merged_sha
Expand Down
Loading