From 806404db66b65f8adf46eaaa85d9e0f71801e695 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:11:03 +0100 Subject: [PATCH 1/4] Honor merge-authority holds in hosted eligibility Co-Authored-By: Codex --- .github/workflows/eligibility.yml | 9 ++++++--- docs/ARCHITECTURE.md | 3 +++ src/loopzero/cli.py | 5 ++--- src/loopzero/eligibility.py | 2 ++ src/loopzero/github.py | 9 ++++++--- tests/test_cli.py | 30 +++++++++++++++++++++++++++++- tests/test_hosted.py | 25 +++++++++++++++++++++++-- 7 files changed, 71 insertions(+), 12 deletions(-) diff --git a/.github/workflows/eligibility.yml b/.github/workflows/eligibility.yml index 46b4faf6..a85b85ba 100644 --- a/.github/workflows/eligibility.yml +++ b/.github/workflows/eligibility.yml @@ -1,7 +1,7 @@ name: review eligibility on: pull_request_target: - types: [opened, synchronize, reopened, edited, ready_for_review, converted_to_draft] + types: [opened, synchronize, reopened, edited, ready_for_review, converted_to_draft, labeled, unlabeled] workflow_run: workflows: [review event] types: [completed] @@ -20,12 +20,15 @@ jobs: # job would fail closed (no MERGIFY_API_KEY) and publish a failure, never a pass. source-eligibility: # Skip closed PRs and title/body edits before a runner is allocated. Draft churn - # waits for readiness; conversion to draft still invalidates prior eligibility. + # waits for readiness except when conversion or a hold change needs a refresh. if: >- github.event_name != 'pull_request_target' || ( github.event.action != 'closed' && - (!github.event.pull_request.draft || github.event.action == 'converted_to_draft') && + (!github.event.pull_request.draft || github.event.action == 'converted_to_draft' || + github.event.action == 'labeled' || github.event.action == 'unlabeled') && (github.event.action != 'edited' || github.event.changes.base != null) && + ((github.event.action != 'labeled' && github.event.action != 'unlabeled') || + github.event.label.name == 'hold') && github.event.pull_request.user.login != 'mergify[bot]' && !startsWith(github.event.pull_request.head.ref, 'mergify/merge-queue/')) # Skipped events stay out of the group and cannot replace a pending refresh. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2a3213d0..7aba89be 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -280,6 +280,9 @@ review publication; the existing reviewer selector and delivery gates still appl [GitHub transport](../src/loopzero/github.py) owns API access and changed-only PR writes. [Hosted dispatch](../src/loopzero/hosted.py) and [eligibility](../src/loopzero/eligibility.py) evaluate trusted review evidence. +Local readiness and hosted source and candidate eligibility reject PRs with +merge-authority holds. Adding or removing a hold refreshes source eligibility +even when the head stays the same. Merge admission rechecks the live hold. [Mergify](MERGIFY.md) describes optional source-preserving queue integration; [candidate validation](../src/loopzero/candidate.py) belongs at that boundary. Candidate lineage reads wait on zero or multiple live batch matches with exponential diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index c77fed41..68b131e9 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -290,9 +290,8 @@ def _readiness( wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None, *, workflow_wait: bool = False, announce_receipt: bool = False, ) -> github.Readiness: - if "hold" in pr.labels: - reason = f"PR #{pr.number} {github.MERGE_HOLD_MESSAGE}" - return github.Readiness(ready=False, reasons=(reason,)) + if hold := github.merge_hold(pr.number, pr.labels): + return github.Readiness(False, (hold,)) if reviews is None: reviews = _pr_reviews(config.repo, pr.number) publishers = config.review_publishers or (github.login(),) diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 981c0bed..37383a17 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -161,6 +161,8 @@ def evaluate(repo: str, number: int, head: str, base: str, pr = github.pr_view(repo, number) if pr.head_sha != head: return github.Readiness(False, ("source head changed; refresh eligibility",)) + if hold := github.merge_hold(pr.number, pr.labels): + return github.Readiness(False, (hold,)) reviews, page = [], 1 while True: batch = github.api_get(f"repos/{repo}/pulls/{number}/reviews?per_page=100&page={page}") diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 9ecaffd1..e805e1da 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -498,7 +498,10 @@ def _api(endpoint: str, payload: dict, method: str = "POST", path.unlink(missing_ok=True) -MERGE_HOLD_MESSAGE = "has a merge-authority hold; ask the decisions owner to release it" +def merge_hold(number: int, labels: tuple[str, ...]) -> str | None: + if "hold" in labels: + return f"PR #{number} has a merge-authority hold; ask the decisions owner to release it" + return None def _pr_labels(data: dict) -> tuple[str, ...]: @@ -1328,8 +1331,8 @@ def merged_sha( if isinstance(sha, str) and re.fullmatch(r"[0-9a-f]{40}", sha): return sha elif not view["merged"] and view.get("state") == "open": - if check_hold and "hold" in _pr_labels(view): - raise GhError(argv, f"PR #{number} {MERGE_HOLD_MESSAGE}") + if check_hold and (hold := merge_hold(number, _pr_labels(view))): + raise GhError(argv, hold) return None # An open PR's merge_commit_sha is only a test merge. if not view["merged"] and view.get("state") == "closed": raise ClosedUnmerged(argv, "PR closed without a verified merge or invalid merge evidence") diff --git a/tests/test_cli.py b/tests/test_cli.py index e76013e8..03102cba 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -17,7 +17,7 @@ import pytest -from loopzero import cli, config, github, mergify +from loopzero import cli, config, github, hosted, mergify from loopzero._proc import Completed, build_env from loopzero.types import CheckReport, CheckResult, ReviewResult from tests.conftest import git, init_git_repo @@ -2485,6 +2485,34 @@ def test_hold_blocks_ready_and_merge(wt, gh, capsys, monkeypatch, command, check assert any(c["argv"][:2] == ["pr", "ready"] for c in gh.calls) == (command == "ready") +def test_hold_label_refresh_matches_local_readiness(wt, gh, head, tmp_path, monkeypatch, capsys): + trusted = tmp_path / "trusted" + trusted.mkdir() + (trusted / "workflow.toml").write_text(WORKFLOW + f'review_publishers = ["{LOGIN}"]\n') + event = trusted / "event.json" + monkeypatch.setenv("GITHUB_REPOSITORY", REPO) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) + gh.respond(f"api repos/{REPO}/statuses/{head}", {}) + + for action, labels, expected in ( + ("labeled", [{"name": "hold"}], 1), ("unlabeled", [], 0), + ): + arm_approved_ready_pr(gh, head, wt, isDraft=False, labels=labels) + gh.respond(f"api repos/{REPO}/pulls/7", rest_pr_json( + pr_json(headRefOid=head, isDraft=False, labels=labels))) + event.write_text(json.dumps({"action": action, "pull_request": {"number": 7}})) + code, out, _ = run(capsys, "ready") + assert code == expected + assert ("merge-authority hold" in out) == bool(labels) + with monkeypatch.context() as hosted_env: + hosted_env.chdir(trusted) + assert hosted.main() == expected + capsys.readouterr() + payload = json.loads(gh.calls[-1]["--input"]) + assert gh.calls[-1]["argv"][1] == f"repos/{REPO}/statuses/{head}" + assert payload["state"] == ("failure" if labels else "success") + + @pytest.mark.parametrize("wait,elapsed,conclusion,expected", [ (0, 0, None, 3), (1, 0, "failure", 1), (1, 0.25, "success", 0), (1, 6, "success", 3), ]) diff --git a/tests/test_hosted.py b/tests/test_hosted.py index e15e7912..b8799e46 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -130,6 +130,7 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, er @pytest.mark.parametrize("case,error,message", [ ("valid", None, ""), ("policy", hosted.LoopZeroError, "no review recorded"), + ("hold", hosted.LoopZeroError, "source #101: PR #101 has a merge-authority hold"), ("merged", CandidateError, "not open"), ("race", CandidateRaceError, "metadata changed"), ("malformed", CandidateError, "invalid payload"), @@ -139,11 +140,24 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, er ("stale", hosted.LoopZeroError, "head is no longer current"), ("untrusted", CandidateError, "head event was not sent"), ]) -def test_candidate_publication_and_event_controls(tmp_path, monkeypatch, case, error, message): +def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatch, case, error, message): event = candidate_event() event["action"] = "edited" if case == "metadata" else event["action"] event["sender"]["id"] = 1 if case == "untrusted" else event["sender"]["id"] values = candidate_payloads(event) + if case in {"valid", "hold"}: + gh = FakeGh(fake_bin, tmp_path) + gh.respond("api graphql", threads_json()) + for number, sha in [(101, "1" * 40), (102, "2" * 40), (900, "c" * 40)]: + path = f"/repos/owner/repo/pulls/{number}" + values[path] = fixtures.rest_pr_json(pr_json( + number=number, headRefOid=sha, isDraft=False, + labels=[{"name": "hold"}] if case == "hold" and number == 101 else [], + )) | values[path] + values[f"{path}/reviews?per_page=100&page=1"] = [{ + "state": "APPROVED", "commit_id": sha, "user": {"login": "trusted-publisher"}, + "body": f"\nreview: **approve**", + }] if case == "stale": values["/repos/owner/repo/pulls/900"]["head"]["sha"] = "d" * 40 if case == "malformed": @@ -175,14 +189,18 @@ def publish(*args): raise RuntimeError("publication details must not replace attestation error") monkeypatch.setattr(github, "commit_status", publish) evaluated = [] + real_evaluate = hosted.eligibility.evaluate def evaluate(repo, number, head, base, publishers): evaluated.append((repo, number, head, base, publishers)) + if case in {"valid", "hold"}: + return real_evaluate(repo, number, head, base, publishers) if case == "interrupt": raise KeyboardInterrupt() reasons = (github.MISSING_REVIEW_REASON,) if case == "policy" else () return github.Readiness(not reasons, reasons) - monkeypatch.setattr(github, "pr_view", lambda *_: SimpleNamespace(head_sha=("d" if case == "head" else "c") * 40)) + if case not in {"valid", "hold"}: + monkeypatch.setattr(github, "pr_view", lambda *_: SimpleNamespace(head_sha=("d" if case == "head" else "c") * 40)) monkeypatch.setattr(hosted.eligibility, "evaluate", evaluate) monkeypatch.setattr("loopzero.mergify.api_get", lambda repo, suffix: candidate_status() if (repo, suffix) == ("owner/repo", "/merge-queue/status?branch=main") else None) @@ -210,11 +228,14 @@ def evaluate(repo, number, head, base, publishers): def test_privileged_workflow_runs_only_the_trusted_default_branch_package(): workflow = (Path(__file__).parents[1] / ".github/workflows/eligibility.yml").read_text() assert "pull_request_target:" in workflow + events = next(line for line in workflow.splitlines() if line.strip().startswith("types:")) + assert "labeled" in events and "unlabeled" in events source, candidate = workflow.split("\n source-eligibility:\n", 1)[1].split( "\n candidate-eligibility:\n", 1 ) assert " environment:" not in source assert "${{ secrets.MERGIFY_API_KEY }}" not in source + assert "github.event.label.name == 'hold'" in source assert "environment:\n name: mergify-metadata\n deployment: false" in candidate assert "MERGIFY_API_KEY: ${{ secrets.MERGIFY_API_KEY }}" in candidate for job in (source, candidate): From ea3e50d17a6c2f0a6812029d4f8fb8f45fe69db9 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:16:33 +0100 Subject: [PATCH 2/4] Document the coordinator route for remote check receipts Architecture-Review: unchanged; the coordinator still owns receipt production and readiness still verifies the fingerprint. Co-Authored-By: Codex --- SETUP.md | 23 +++++++++++++++++++++++ docs/ARCHITECTURE.md | 7 +++++++ tests/test_cli.py | 22 ++++++++++++++++++++++ 3 files changed, 52 insertions(+) diff --git a/SETUP.md b/SETUP.md index 557f4782..30258c12 100644 --- a/SETUP.md +++ b/SETUP.md @@ -339,6 +339,29 @@ access to the configured GitHub repository even before a PR exists. See the [workflow diagram](docs/WORKFLOW.md#1-from-idea-to-merged) and [Blockers](core/CONTRACT.md#blockers) for the rest of the workflow. +### Check receipts with remote execution + +Run the current `loopzero check` coordinator from the task worktree with +the same effective settings used by `loopzero ready`. To execute stages +remotely, configure an operator-trusted `[checks].runner` that implements the +[stage protocol](docs/ARCHITECTURE.md#check-stage-runners). The local coordinator +writes the receipt. + +Without a stage adapter, run the whole check locally. Use a local slot if the +host requires one. On miki, run this from the task worktree. + +```sh +HEAVY_SLOT_REMOTE_HOSTS="$HOME/.cache/intelflo-scratch/locks/no-remote-hosts.json" "$HOME/.cache/intelflo-scratch/locks/heavy-slot.sh" loopzero check +``` + +A whole-job remote worker writes its own receipt. Ready can use it only if it +passes the existing checks for a clean, passing receipt at the exact head, +with the current ordered commands and matching settings fingerprint. An older +worker can omit the fingerprint. A current worker can produce a different +fingerprint, for example when its inherited `PATH` differs. GitHub required +CI supplies separate evidence. The [owner queue route](core/CONTRACT.md#blockers) +applies only under its documented conditions. + ## Removing an abandoned task worktree For a merged PR, retry cleanup from a durable directory with diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 661a86f4..b2b29b9a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -501,4 +501,11 @@ Receipts that use saved stage results bind the current head and check settings. For delegated checks, both the receipt and the stage key bind the runner's launch path, resolved executable path and executable bytes. Unavailable runner identity prevents receipt reuse. + +A worker running the entire check is itself the coordinator and writes a +receipt with its own effective settings. Transferring it preserves the +fingerprint, if present. Local readiness applies the same receipt predicate +as for any other coordinator. See [check receipts with remote execution](../SETUP.md#check-receipts-with-remote-execution) +for the operator route. + CI and merge-queue candidates run fresh without a local worktree receipt. diff --git a/tests/test_cli.py b/tests/test_cli.py index 3cd7131b..2df334eb 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3058,6 +3058,28 @@ def change_policy(_seconds): assert run(capsys, *args, "check")[0] == 1 +@pytest.mark.parametrize("worker", ["legacy", "different-path", "matching"]) +def test_ready_checks_transferred_whole_job_receipt(wt, gh, capsys, head, tmp_path, monkeypatch, worker): + arm_approved_ready_pr(gh, head, wt, readiness={"local_exit": None}, isDraft=False) + with monkeypatch.context() as worker_env: + if worker == "different-path": + worker_env.setenv("PATH", str(tmp_path / "worker-bin"), prepend=":") + assert run(capsys, "check")[0] == 0 + + receipt = wt / ".loopzero/checks.json" + payload = json.loads(receipt.read_bytes()) + if worker == "legacy": + # Older producers serialize these results without a settings fingerprint. + del payload["settings_sha256"] + # Whole-job transport preserves the producer's fields. + receipt.write_text(json.dumps(payload)) + assert run(capsys, "ready")[0] == (0 if worker == "matching" else 1) + + if worker != "matching": + assert run(capsys, "check")[0] == 0 + assert run(capsys, "ready")[0] == 0 + + @pytest.mark.parametrize("base_sensitive", [False, True]) def test_wait_snapshot_handles_trusted_base_advance(wt, repo, base_sensitive): if base_sensitive: From d74665f11b4d74887e06a54c0fc1970c29819804 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:16:33 +0100 Subject: [PATCH 3/4] Fail check when a delegated runner leaves an unverified receipt Architecture-Review: unchanged; the coordinator still owns receipt production and readiness still verifies the fingerprint. Co-Authored-By: Codex --- src/loopzero/cli.py | 5 +++++ tests/test_cli.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 515d3da7..9ac94a05 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -628,6 +628,11 @@ def cmd_check(args: argparse.Namespace) -> int: print(f"check result discarded: checked HEAD {report.head}, current HEAD {current_head}", file=sys.stderr) return 1 + if report.ok and report.settings_sha256 is None: + print("check stages passed but the receipt is unverified; rerun loopzero check from the task " + "worktree with a stable, readable configured runner before running ready", file=sys.stderr) + _refresh_pr_checks(wt, config) + return 1 if report.ok and not report.dirty: _print_receipt(wt, report, "produced") _refresh_pr_checks(wt, config) diff --git a/tests/test_cli.py b/tests/test_cli.py index 3cd7131b..9ddb9ca3 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3058,6 +3058,43 @@ def change_policy(_seconds): assert run(capsys, *args, "check")[0] == 1 +def test_check_refuses_unverified_receipt_after_runner_retarget(wt, gh, capsys, head, tmp_path): + runner = tmp_path / "runner" + original = tmp_path / "runner-a" + replacement = tmp_path / "runner-b" + stage = ( + f"#!{sys.executable}\n" + "import json, sys\n" + "frame = json.load(sys.stdin)\n" + "del frame['env']\n" + "frame.update(exit_code=0, duration_s=0, not_started=False, tail='')\n" + ) + for target, extra in ( + (original, f"from pathlib import Path\np = Path({str(runner)!r})\n" + f"p.unlink()\np.symlink_to({str(replacement)!r})\n"), + (replacement, ""), + ): + target.write_text(stage + extra + "print(json.dumps(frame))\n") + target.chmod(0o755) + runner.symlink_to(original) + publish_workflow(wt, WORKFLOW.replace("[checks]", f"[checks]\nrunner = {json.dumps([str(runner)])}")) + arm_approved_ready_pr(gh, head, wt, readiness={"local_exit": None}, isDraft=False) + + code, out, err = run(capsys, "check") + assert code == 1 + assert "receipt produced:" not in out and "PASS" not in out + assert "stages passed but the receipt is unverified" in err + assert "rerun loopzero check from the task worktree with a stable, readable configured runner" in err + report = cli._load_report(wt) + assert report.head == head and not report.dirty and report.ok + assert report.settings_sha256 is None + assert run(capsys, "ready")[0] == 1 + + code, out, _ = run(capsys, "check") + assert code == 0 and "receipt produced:" in out + assert run(capsys, "ready")[0] == 0 + + @pytest.mark.parametrize("base_sensitive", [False, True]) def test_wait_snapshot_handles_trusted_base_advance(wt, repo, base_sensitive): if base_sensitive: From 4fcf2301361b78908004f7a6d61a482ef75e028e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:19:51 +0100 Subject: [PATCH 4/4] Place the whole-job receipt cases after the check environment tests Co-Authored-By: Codex --- tests/test_cli.py | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 2df334eb..bf6c9382 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3058,28 +3058,6 @@ def change_policy(_seconds): assert run(capsys, *args, "check")[0] == 1 -@pytest.mark.parametrize("worker", ["legacy", "different-path", "matching"]) -def test_ready_checks_transferred_whole_job_receipt(wt, gh, capsys, head, tmp_path, monkeypatch, worker): - arm_approved_ready_pr(gh, head, wt, readiness={"local_exit": None}, isDraft=False) - with monkeypatch.context() as worker_env: - if worker == "different-path": - worker_env.setenv("PATH", str(tmp_path / "worker-bin"), prepend=":") - assert run(capsys, "check")[0] == 0 - - receipt = wt / ".loopzero/checks.json" - payload = json.loads(receipt.read_bytes()) - if worker == "legacy": - # Older producers serialize these results without a settings fingerprint. - del payload["settings_sha256"] - # Whole-job transport preserves the producer's fields. - receipt.write_text(json.dumps(payload)) - assert run(capsys, "ready")[0] == (0 if worker == "matching" else 1) - - if worker != "matching": - assert run(capsys, "check")[0] == 0 - assert run(capsys, "ready")[0] == 0 - - @pytest.mark.parametrize("base_sensitive", [False, True]) def test_wait_snapshot_handles_trusted_base_advance(wt, repo, base_sensitive): if base_sensitive: @@ -3121,6 +3099,28 @@ def test_ready_matches_effective_inherited_check_environment( assert code == 1 and "not ready: check receipt has an incompatible settings fingerprint." in out +@pytest.mark.parametrize("worker", ["legacy", "different-path", "matching"]) +def test_ready_checks_transferred_whole_job_receipt(wt, gh, capsys, head, tmp_path, monkeypatch, worker): + arm_approved_ready_pr(gh, head, wt, readiness={"local_exit": None}, isDraft=False) + with monkeypatch.context() as worker_env: + if worker == "different-path": + worker_env.setenv("PATH", str(tmp_path / "worker-bin"), prepend=":") + assert run(capsys, "check")[0] == 0 + + receipt = wt / ".loopzero/checks.json" + payload = json.loads(receipt.read_bytes()) + if worker == "legacy": + # Older producers serialize these results without a settings fingerprint. + del payload["settings_sha256"] + # Whole-job transport preserves the producer's fields. + receipt.write_text(json.dumps(payload)) + assert run(capsys, "ready")[0] == (0 if worker == "matching" else 1) + + if worker != "matching": + assert run(capsys, "check")[0] == 0 + assert run(capsys, "ready")[0] == 0 + + def test_ready_ignores_forged_markers(wt: Path, gh: FakeGh, capsys, head) -> None: arm_approved_pr_with_check_result(gh, head, wt, "success", reviews=[rev(head, "primary", login="stranger"), rev(head, "primary", commit="1" * 40)]) code, out, _ = run(capsys, "ready")