Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Finish reviewed PRs after verified CI without a manual handoff (#666)

Deec43b8fa9eab4
diff --git a/AGENTS.md b/AGENTS.md
index 8e6847ae4..cb1be7c50 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -22,11 +22,13 @@ validation and shipping, use [docs/validation-and-release.md](docs/validation-an
validation cycle. Verify published versions and checksums, then report completion.
Desktop's `--wait` follows the exact tag/SHA through the workflow's six-artifact
verification; reuse that receipt instead of repeating the downloads manually.
-- Prepare the PR and review while checks run. Once CI has a run ID, start
- `scripts/record-ci-validation.py RUN_ID --scope SCOPE --pr PR_NUMBER --wait` to
- collect its evidence as soon as that attempt passes; retain routine
- results in its ignored receipt and the PR body instead of another documentation
- commit. Resolve any source differences explicitly before reusing that evidence.
+- Prepare the PR and review while checks run. For an authorized merge after review
+ and required non-CI checks, use `make merge-pr` with the reviewed head/main SHAs,
+ CI run/scope, and `--merge` (see the validation guide). It collects CI evidence,
+ rechecks the source, merges, and verifies the resulting tree. For evidence only,
+ use `scripts/record-ci-validation.py RUN_ID --scope SCOPE --pr PR_NUMBER --wait`.
+ Retain routine results in the ignored receipt and PR body instead of another
+ documentation commit. Resolve source differences explicitly before reusing evidence.
- For an authorized Desktop release, start `make release-desktop ARGS="--prepare"`
from the final pushed PR branch alongside validation and review. It prepares
verified packages without publishing; merge and release only after checks pass.
diff --git a/Makefile b/Makefile
index f6aea2cae..51f744870 100644
--- a/Makefile
+++ b/Makefile
@@ -4,13 +4,18 @@
# make install-cli ARGS="--no-restart"
# make release-cli ARGS="--dry-run"
-.PHONY: validate desktop-test cli-test install-cli upload-cli-install-sh release-cli release-backend release-desktop release-web remote-machine upload-circle device-test
+.PHONY: validate merge-pr desktop-test cli-test install-cli upload-cli-install-sh release-cli release-backend release-desktop release-web remote-machine upload-circle device-test
## validate: bounded independent checks with logs and a source/timing receipt.
## See docs/validation-and-release.md. ARGS="path/to/plan.json".
validate:
python3 scripts/validate-change.py $(ARGS)
+## merge-pr: wait for required CI and verify an already-reviewed PR; add --merge to squash it.
+## See docs/validation-and-release.md for reviewed source arguments and non-CI checks.
+merge-pr:
+ python3 scripts/merge-validated-pr.py $(ARGS)
+
## desktop-test: bounded VM tests, host-sized workers and recorded startup recovery.
## ARGS="test/affected_test.dart --workers 2"; omit paths for the full VM suite.
desktop-test:
diff --git a/docs/validation-and-release.md b/docs/validation-and-release.md
index dc4add13e..0d9445589 100644
--- a/docs/validation-and-release.md
+++ b/docs/validation-and-release.md
@@ -363,6 +363,37 @@ Report the combined coverage and any retries explicitly. This is not an
uninterrupted passing suite, and it is not permission to retry assertion failures
until they disappear.
+## Merge an already-reviewed PR
+
+Once code review and required non-CI checks are complete and merging is authorized,
+start this command while the selected CI run is still running:
+
+```bash
+make merge-pr ARGS="PR_NUMBER --run RUN_ID --scope SCOPE --reviewed-head HEAD_SHA --reviewed-base MAIN_SHA --merge"
+```
+
+Use full commit SHAs. The clean local checkout must be the reviewed head and include
+that reviewed `main` commit. Prepare the PR description with its check scope and CI
+run link first. The command waits for that attempt, verifies the same jobs/artifacts
+as the evidence collector, then rechecks the PR and the live `main` ref before one
+squash-merge request. GitHub must report the PR ready; the request includes the exact
+reviewed head and does not bypass branch rules or enable auto-merge/queueing.
+
+Omit `--merge` for a read-only preview. Logs, CI evidence, per-phase timings and the
+merge outcome are saved under `.harness/validation/*-merge-*/`. `--wait-timeout`
+defaults to 900s; `--timeout` gives preflight and post-CI operations 90s each. The
+command records its intended mutation before sending it. If a response is lost, it
+inspects the same PR without replaying the merge request.
+
+A changed head, dirty checkout, moved main, failed CI or blocked merge stops the
+command. Review new source differences and reuse only applicable evidence, as above;
+the command does not decide that impact or replace native checks and code review.
+After a merge, it verifies the actual Git tree against the tested tree. A different
+tree is recorded as `merged_source_review_required` (exit 3), so resolve that source
+review before release. An unconfirmed write is recorded as `merge_not_confirmed`;
+inspect the same PR before further action. This command does not create release tags
+or dispatch release workflows.
+
## Complete the authorized release
Once required checks pass, merge, verify the resulting source, and tag that source
diff --git a/scripts/merge-validated-pr.py b/scripts/merge-validated-pr.py
new file mode 100644
index 000000000..14c142580
--- /dev/null
+++ b/scripts/merge-validated-pr.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+"""Wait for required CI, then preview or perform an already-reviewed squash merge.
+
+The caller selects required checks and completes code/native review first.
+Only --merge writes to GitHub; this command never publishes a product release.
+"""
+import argparse
+from datetime import datetime, timezone
+import importlib.util
+import json
+from pathlib import Path
+import re
+import subprocess
+import sys
+import time
+
+spec = importlib.util.spec_from_file_location("ci_evidence", Path(__file__).with_name("record-ci-validation.py"))
+ci = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(ci)
+
+
+def git(root, *args):
+ return subprocess.check_output(["git", *args], cwd=root, stderr=subprocess.PIPE, timeout=15, text=True).strip()
+
+
+def preflight(client, root, number, head, base, ready=False):
+ pr = client.api(f"pulls/{number}")
+ if (pr.get("number") != number or pr.get("state") != "open" or pr.get("draft") is not False
+ or pr.get("merged") is not False or pr.get("head", {}).get("sha") != head
+ or pr.get("base", {}).get("ref") != "main"
+ or pr.get("base", {}).get("repo", {}).get("full_name", "").lower() != client.repository.lower()):
+ raise ValueError("PR is not the open, reviewed head targeting this repository's main")
+ # PR base.sha can lag a new main commit. Read the actual ref, not its snapshot.
+ ref = client.api("git/ref/heads/main")
+ if (ref.get("ref") != "refs/heads/main" or ref.get("object", {}).get("type") != "commit"
+ or ref["object"].get("sha") != base):
+ raise ValueError("main moved since review; inspect the new source before merging")
+ if git(root, "rev-parse", "HEAD") != head or git(root, "status", "--porcelain", "--untracked-files=normal"):
+ raise ValueError("the local checkout must remain clean at the reviewed head")
+ git(root, "merge-base", "--is-ancestor", base, head)
+ if ready and (pr.get("mergeable") is not True or pr.get("mergeable_state") != "clean"):
+ raise ValueError("GitHub does not report this PR ready to merge; no rules are bypassed")
+ return {"head": head, "base": base, "tree": git(root, "rev-parse", f"{head}^{{tree}}"),
+ "url": pr["html_url"]}
+
+
+def confirm_merge(client, number, head, expected_tree, response):
+ # A successful write can outlive an HTTP timeout. Observe the same PR;
+ # never submit the mutation twice or assume that a timeout rejected it.
+ for attempt in range(5):
+ pr = client.api(f"pulls/{number}")
+ if pr.get("merged") is True:
+ sha = pr.get("merge_commit_sha", "")
+ if (pr.get("number") != number or pr.get("head", {}).get("sha") != head
+ or pr.get("base", {}).get("ref") != "main"
+ or pr.get("base", {}).get("repo", {}).get("full_name", "").lower() != client.repository.lower()
+ or not re.fullmatch(r"[0-9a-f]{40}", sha)):
+ raise ValueError("merged PR identity differs from the reviewed source")
+ if response and response.get("merged") is True and response.get("sha") != sha:
+ raise ValueError("merge response and actual PR commit disagree")
+ commit = client.api(f"git/commits/{sha}")
+ if commit.get("sha") != sha:
+ raise ValueError("merge commit lookup returned another source")
+ tree = commit.get("tree", {}).get("sha")
+ if not re.fullmatch(r"[0-9a-f]{40}", tree or ""):
+ raise ValueError("merge commit is missing its source tree")
+ return dict(commit=sha, tree=tree, same_tested_tree=tree == expected_tree,
+ merged_at=pr.get("merged_at"), parents=[p["sha"] for p in commit.get("parents", [])])
+ if pr.get("state") == "closed" or attempt == 4:
+ break
+ time.sleep(1)
+ raise ValueError("merge outcome not confirmed; inspect this same PR before any further action")
+
+
+def finish(client, root, number, run_id, scope, head, base, output, *, merge=False, wait_timeout=900, timeout=90):
+ output.mkdir(parents=True, exist_ok=False)
+ record = dict(schema=1, kind="validated-pr-merge", repository=client.repository,
+ pr=number, run_id=run_id, scope=scope, reviewed_head=head, reviewed_base=base,
+ merge_authorized=merge, started_at=ci.utc_now(), status="not_merged", phases={})
+ evidence = None
+
+ def save():
+ temporary = output / "receipt.tmp"
+ temporary.write_text(json.dumps(record, indent=2) + "\n")
+ temporary.replace(output / "receipt.json")
+
+ def phase(name, action):
+ started = time.monotonic()
+ detail = record["phases"][name] = {"started_at": ci.utc_now()}
+ save()
+ try:
+ return action()
+ finally:
+ detail.update(finished_at=ci.utc_now(), duration_seconds=round(time.monotonic() - started, 3))
+ save()
+
+ try:
+ client.deadline = time.monotonic() + timeout
+ record["reviewed_source"] = phase("preflight", lambda: preflight(client, root, number, head, base))
+ client.deadline = time.monotonic() + wait_timeout
+ observed = phase("waiting", lambda: ci.wait_for_run(client, run_id))
+ client.deadline = time.monotonic() + timeout
+ evidence_dir = output / "ci"
+ evidence_dir.mkdir()
+ evidence = phase("collection", lambda: ci.collect(client, root, run_id, scope, head,
+ evidence_dir, number, expected_run=observed))
+ (evidence_dir / "receipt.json").write_text(json.dumps(evidence, indent=2) + "\n")
+ (evidence_dir / "validation.md").write_text(ci.markdown(evidence))
+ if evidence["status"] != "passed":
+ raise ValueError("CI evidence requires source review; no merge requested")
+ if phase("final_source_check", lambda: preflight(client, root, number, head, base, ready=True)) != record["reviewed_source"]:
+ raise ValueError("reviewed source changed before merge")
+ record["status"] = "ready"
+ save()
+ if merge:
+ record.update(status="merge_requested", merge_requested_at=ci.utc_now())
+ save() # Retain the exact intended mutation before sending it.
+ response = None
+ try:
+ response = phase("merge_request", lambda: client.command(
+ "api", "--method", "PUT", f"repos/{client.repository}/pulls/{number}/merge",
+ "-f", f"sha={head}", "-f", "merge_method=squash"))
+ record["merge_response"] = response
+ except (OSError, RuntimeError, subprocess.SubprocessError, ValueError) as error:
+ record["merge_request_error"] = str(error)
+ # Inspection gets a fresh bounded budget even if the write timed out.
+ client.deadline = time.monotonic() + min(timeout, 30)
+ record["merge"] = phase("verification", lambda: confirm_merge(
+ client, number, head, evidence["source"]["tested_tree"], response))
+ record["status"] = "merged" if record["merge"]["same_tested_tree"] else "merged_source_review_required"
+ except (OSError, RuntimeError, ValueError, KeyError, TypeError, subprocess.SubprocessError, ci.zipfile.BadZipFile) as error:
+ record["error"] = str(error)
+ record["status"] = "merge_not_confirmed" if "merge_requested_at" in record else "not_merged"
+ record["finished_at"] = ci.utc_now()
+ save()
+ lines = [f"PR #{number}: **{record['status']}**.",
+ f"Reviewed head `{head}`; reviewed main `{base}`."]
+ if "error" in record:
+ lines.append(record["error"])
+ if "merge" in record:
+ result = record["merge"]
+ lines.append(f"Merged commit `{result['commit']}`; tested tree matches: `{result['same_tested_tree']}`.")
+ if evidence is not None:
+ lines += ["", ci.markdown(evidence)]
+ (output / "merge.md").write_text("\n".join(lines) + "\n")
+ return record
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("pr", type=int)
+ parser.add_argument("--run", type=int, required=True)
+ parser.add_argument("--scope", choices=ci.SCOPES, required=True)
+ parser.add_argument("--reviewed-head", required=True, help="full commit SHA already reviewed, including required non-CI checks")
+ parser.add_argument("--reviewed-base", required=True, help="full main SHA included in the reviewed head")
+ parser.add_argument("--repo", default="autonomous-ai/openharness")
+ parser.add_argument("--merge", action="store_true", help="perform the authorized squash merge after verification; default: preview only")
+ parser.add_argument("--wait-timeout", type=float, default=900)
+ parser.add_argument("--timeout", type=float, default=90, help="budget for preflight and, separately, post-CI operations")
+ parser.add_argument("--output", type=Path)
+ args = parser.parse_args()
+ if (args.pr < 1 or args.run < 1
+ or any(not re.fullmatch(r"[0-9a-f]{40}", sha) for sha in [args.reviewed_head, args.reviewed_base])
+ or any(not 0 < value < float("inf") for value in [args.wait_timeout, args.timeout])
+ or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*", args.repo)):
+ parser.error("supply positive IDs/budgets, full reviewed SHAs, and a valid repository")
+ root = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")).resolve()
+ output = args.output or root / ".harness/validation" / (datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ") + f"-merge-{args.pr}")
+ record = finish(ci.Client(args.repo, 0), root, args.pr, args.run, args.scope, args.reviewed_head,
+ args.reviewed_base, output, merge=args.merge, wait_timeout=args.wait_timeout, timeout=args.timeout)
+ print(f"{record['status']}: {output / 'merge.md'}")
+ if "error" in record:
+ print(record["error"], file=sys.stderr)
+ return {"merged": 0, "ready": 0, "merged_source_review_required": 3}.get(record["status"], 1)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/tests/test_merge_validated_pr.py b/scripts/tests/test_merge_validated_pr.py
new file mode 100644
index 000000000..a09ba5202
--- /dev/null
+++ b/scripts/tests/test_merge_validated_pr.py
@@ -0,0 +1,241 @@
+import copy
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+from unittest import mock
+
+spec = importlib.util.spec_from_file_location("merge_pr", Path(__file__).resolve().parents[1] / "merge-validated-pr.py")
+merger = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(merger)
+
+
+class MergeTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name) / "source"
+ self.root.mkdir()
+ self.git("init", "-q")
+ self.git("config", "user.name", "Fixture")
+ self.git("config", "user.email", "[email protected]")
+ (self.root / "source.txt").write_text("base\n")
+ self.git("add", ".")
+ self.git("commit", "-qm", "base")
+ self.base = self.git("rev-parse", "HEAD")
+ (self.root / "source.txt").write_text("reviewed\n")
+ self.git("commit", "-qam", "reviewed")
+ self.head = self.git("rev-parse", "HEAD")
+ self.tree = self.git("rev-parse", "HEAD^{tree}")
+ self.output = Path(self.tmp.name) / "result"
+ self.client = FakeClient(self)
+ self.patch(merger.ci, "print", create=True)
+ self.patch(merger.time, "sleep")
+
+ def git(self, *args):
+ return subprocess.check_output(["git", *args], cwd=self.root, stderr=subprocess.PIPE, text=True).strip()
+
+ def patch(self, obj, name, **kwargs):
+ patcher = mock.patch.object(obj, name, **kwargs)
+ value = patcher.start()
+ self.addCleanup(patcher.stop)
+ return value
+
+ def finish(self, merge=True):
+ result = merger.finish(self.client, self.root, 5, 123, "process", self.head, self.base,
+ self.output, merge=merge)
+ self.assertEqual(json.loads((self.output / "receipt.json").read_text()), result)
+ return result
+
+ def test_preview_verifies_full_evidence_without_mutating_github(self):
+ result = self.finish(merge=False)
+ self.assertEqual(result["status"], "ready")
+ self.assertFalse(result["merge_authorized"])
+ self.assertEqual(self.client.writes, [])
+ self.assertTrue((self.output / "ci/validation.md").is_file())
+ self.assertEqual(result["reviewed_source"]["tree"], self.tree)
+
+ def test_merge_sends_exact_head_once_and_verifies_actual_tree(self):
+ result = self.finish()
+ self.assertEqual(result["status"], "merged")
+ self.assertTrue(result["merge"]["same_tested_tree"])
+ self.assertEqual(result["merge"]["commit"], self.client.merged_sha)
+ self.assertEqual(self.client.writes, [("api", "--method", "PUT", "repos/owner/repo/pulls/5/merge",
+ "-f", f"sha={self.head}", "-f", "merge_method=squash")])
+ self.assertIn("merge_request", result["phases"])
+ self.assertIn("verification", result["phases"])
+
+ def test_wrong_pr_draft_target_or_head_stops_before_ci_or_mutation(self):
+ original = copy.deepcopy(self.client.pr)
+ for change in [dict(number=6), dict(state="closed"), dict(draft=True), dict(merged=True),
+ dict(head=dict(sha="b" * 40)),
+ dict(base=dict(ref="other", repo=dict(full_name="owner/repo"))),
+ dict(base=dict(ref="main", repo=dict(full_name="other/repo")))]:
+ self.client.pr = dict(original, **change)
+ with self.subTest(change=change), self.assertRaises(ValueError):
+ merger.preflight(self.client, self.root, 5, self.head, self.base)
+ self.assertEqual(self.client.writes, [])
+ self.assertEqual(self.client.run_reads, 0)
+
+ def test_live_main_movement_is_detected_even_when_pr_base_snapshot_is_stale(self):
+ self.client.actual_base = self.head
+ result = self.finish()
+ self.assertEqual(result["status"], "not_merged")
+ self.assertIn("main moved", result["error"])
+ self.assertEqual(self.client.writes, [])
+
+ def test_untracked_work_or_different_local_head_cannot_merge(self):
+ (self.root / "unreviewed.txt").write_text("change\n")
+ with self.assertRaisesRegex(ValueError, "local checkout"):
+ merger.preflight(self.client, self.root, 5, self.head, self.base)
+ (self.root / "unreviewed.txt").unlink()
+ self.git("commit", "--allow-empty", "-qm", "later")
+ with self.assertRaisesRegex(ValueError, "local checkout"):
+ merger.preflight(self.client, self.root, 5, self.head, self.base)
+
+ def test_reviewed_head_must_include_reviewed_main(self):
+ unrelated = self.git("commit-tree", self.tree, "-m", "unrelated")
+ self.base = self.client.actual_base = unrelated
+ result = self.finish()
+ self.assertEqual(result["status"], "not_merged")
+ self.assertEqual(self.client.writes, [])
+
+ def test_failed_ci_and_missing_required_jobs_block_merge(self):
+ self.client.run["conclusion"] = "failure"
+ result = self.finish()
+ self.assertEqual(result["status"], "not_merged")
+ self.assertEqual(self.client.writes, [])
+ self.output = self.output.with_name("missing-job")
+ self.client.run["conclusion"] = "success"
+ self.client.jobs = []
+ result = self.finish()
+ self.assertIn("missing jobs", result["error"])
+ self.assertEqual(self.client.writes, [])
+
+ def test_ci_for_a_different_tree_is_retained_but_cannot_merge(self):
+ self.client.run["head_sha"] = self.base
+ self.client.jobs[0]["head_sha"] = self.base
+ result = self.finish()
+ self.assertEqual(result["status"], "not_merged")
+ self.assertEqual(self.client.writes, [])
+ evidence = json.loads((self.output / "ci/receipt.json").read_text())
+ self.assertEqual(evidence["status"], "source_review_required")
+
+ def test_movement_after_ci_verification_is_rechecked_before_write(self):
+ original = merger.preflight
+
+ def moved(*args, **kwargs):
+ if kwargs.get("ready"):
+ self.client.actual_base = self.head
+ return original(*args, **kwargs)
+
+ self.patch(merger, "preflight", side_effect=moved)
+ result = self.finish()
+ self.assertEqual(result["status"], "not_merged")
+ self.assertIn("main moved", result["error"])
+ self.assertEqual(self.client.writes, [])
+
+ def test_unknown_or_blocked_github_mergeability_never_bypasses_rules(self):
+ for state in ["unknown", "blocked", "unstable", "dirty"]:
+ self.output = Path(self.tmp.name) / state
+ self.client.pr["mergeable_state"] = state
+ result = self.finish()
+ self.assertEqual(result["status"], "not_merged")
+ self.assertEqual(self.client.writes, [])
+
+ def test_lost_merge_response_is_resolved_by_reading_the_same_pr(self):
+ self.client.behavior = "timeout_after_merge"
+ result = self.finish()
+ self.assertEqual(result["status"], "merged")
+ self.assertIn("merge_request_error", result)
+ self.assertEqual(len(self.client.writes), 1)
+
+ def test_unconfirmed_request_is_retained_and_never_submitted_twice(self):
+ self.client.behavior = "timeout_before_merge"
+ result = self.finish()
+ self.assertEqual(result["status"], "merge_not_confirmed")
+ self.assertIn("inspect this same PR", result["error"])
+ self.assertIn("merge_requested_at", result)
+ self.assertEqual(len(self.client.writes), 1)
+
+ def test_different_merged_tree_requires_review_instead_of_false_success(self):
+ self.client.merged_tree = self.git("rev-parse", f"{self.base}^{{tree}}")
+ result = self.finish()
+ self.assertEqual(result["status"], "merged_source_review_required")
+ self.assertFalse(result["merge"]["same_tested_tree"])
+ self.assertEqual(len(self.client.writes), 1)
+
+ def test_changed_head_or_target_during_write_cannot_claim_tested_merge(self):
+ for behavior in ["retarget_during_merge", "head_change_during_merge", "wrong_response_sha"]:
+ with self.subTest(behavior=behavior):
+ self.output = Path(self.tmp.name) / behavior
+ self.client = FakeClient(self)
+ self.client.behavior = behavior
+ result = self.finish()
+ self.assertEqual(result["status"], "merge_not_confirmed")
+ self.assertEqual(len(self.client.writes), 1)
+
+ def test_bad_artifact_stops_before_merge_and_preserves_failure_receipt(self):
+ self.patch(merger.ci, "collect", side_effect=merger.ci.zipfile.BadZipFile("bad artifact"))
+ result = self.finish()
+ self.assertEqual(result["status"], "not_merged")
+ self.assertEqual(result["error"], "bad artifact")
+ self.assertEqual(self.client.writes, [])
+
+
+class FakeClient:
+ repository = "owner/repo"
+
+ def __init__(self, fixture):
+ self.fixture, self.actual_base = fixture, fixture.base
+ self.deadline, self.run_reads = 0, 0
+ self.writes, self.behavior = [], "success"
+ self.merged_sha, self.merged_tree = "c" * 40, fixture.tree
+ self.pr = dict(number=5, state="open", draft=False, merged=False, mergeable=True, mergeable_state="clean",
+ html_url="https://github.com/owner/repo/pull/5", head=dict(sha=fixture.head),
+ base=dict(sha=fixture.base, ref="main", repo=dict(full_name=self.repository)))
+ self.run = dict(id=123, repository=dict(full_name=self.repository), path=".github/workflows/ci.yml",
+ head_sha=fixture.head, run_attempt=1, status="completed", conclusion="success",
+ html_url="https://github.com/owner/repo/actions/runs/123",
+ created_at="2026-10-03T00:00:00Z", updated_at="2026-10-03T00:01:00Z")
+ self.jobs = [dict(id=1, name="process-checks", run_id=123, run_attempt=1, head_sha=fixture.head,
+ status="completed", conclusion="success", steps=[],
+ started_at="2026-10-03T00:00:01Z", completed_at="2026-10-03T00:01:00Z")]
+
+ def api(self, path):
+ if path == "pulls/5":
+ return copy.deepcopy(self.pr)
+ if path == "git/ref/heads/main":
+ return dict(ref="refs/heads/main", object=dict(type="commit", sha=self.actual_base))
+ if path == "actions/runs/123":
+ self.run_reads += 1
+ return copy.deepcopy(self.run)
+ if path == f"git/commits/{self.merged_sha}":
+ return dict(sha=self.merged_sha, tree=dict(sha=self.merged_tree), parents=[dict(sha=self.actual_base)])
+ raise AssertionError(path)
+
+ def pages(self, path, key):
+ assert key == "jobs", key
+ return copy.deepcopy(self.jobs)
+
+ def command(self, *args, binary=False):
+ self.writes.append(args)
+ before = json.loads((self.fixture.output / "receipt.json").read_text())
+ assert before["status"] == "merge_requested" and before["reviewed_head"] == self.fixture.head
+ if self.behavior == "timeout_before_merge":
+ raise subprocess.TimeoutExpired("gh", 30)
+ self.pr.update(merged=True, state="closed", merge_commit_sha=self.merged_sha,
+ merged_at="2026-10-03T00:01:10Z")
+ if self.behavior == "timeout_after_merge":
+ raise subprocess.TimeoutExpired("gh", 30)
+ if self.behavior == "retarget_during_merge":
+ self.pr["base"]["ref"] = "other"
+ if self.behavior == "head_change_during_merge":
+ self.pr["head"]["sha"] = "b" * 40
+ return dict(sha="f" * 40 if self.behavior == "wrong_response_sha" else self.merged_sha, merged=True, message="merged")
+
+
+if __name__ == "__main__":
+ unittest.main()