Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

MergeSpan

MergeSpan is a GitHub App merge queue for one repository and one target branch. A non-draft pull request enters the queue by carrying the configured label (the default is queue). MergeSpan creates a temporary branch from the current base commit plus the pull request’s head, runs the repository’s configured checks against that exact candidate commit, and then squash-merges the pull request when the candidate is green and the base has not moved.

This page is the book landing page. Start with the Quick Start, or read How It Works for the full state machine.

Why merge queues exist

A merge queue exists to answer a question the branch protection UI cannot answer on its own: will this change pass the repository’s checks once it sits on top of every other change that was merged after the pull request was opened?

Without a queue, a pull request’s checks run against an old base. Two pull requests can each be green in isolation and then fail when both land. Common mitigations are heavy: enable strict up-to-date checks, merge serially by hand, or ask contributors to rebase and rerun until the base stops moving. MergeSpan’s job is to make that serialization automatic and evidence-based.

What MergeSpan does in one sentence

For a single base branch, MergeSpan builds the candidate commit (base tip + pull request head), waits for the configured checks on that candidate’s SHA, and squash-merges only if the candidate is green and the base has not moved.

Design constraints (v0.1)

v0.1 is deliberately narrow:

  • One repository, one base branch. Multiple target branches in one installation are out of scope. Separate repositories and branches get separate queues.
  • Squash merge only. There is no merge-method setting in v0.1.
  • No batching. One pull request is verified at a time; there is no merge batch or speculative batch validation.
  • No speculative parallel candidates. MergeSpan does not build speculative candidates for multiple queued pull requests in parallel; it serializes.
  • No fork pull requests. With same_repo_only = true (required by the v0.1 runtime), only same-repository heads are admitted. Fork heads are not queued.
  • No workflow writes. The App does not request the Workflows permission; it does not modify repository workflow files.
  • No Administration permission. MergeSpan does not request or use Administration.

Status and release

v0.1 is early software. The release workflow builds and publishes tagged artifacts, but no tagged release has been published yet. Until a tag exists, pin a commit SHA for non-production deployments. Both production Workers must wait for a release tag. See Versions and Upgrades for the release, upgrade, and rollback policy.

Documentation set

  • Quick Start — install the App, configure the repository, queue a pull request.
  • How It Works — the full pipeline, failure surfaces, recovery.
  • Configuration — every key, type, default, and exact error in .github/mergespan.toml.
  • GitHub App — required and optional permissions, event subscriptions, webhook contract.
  • Self-Hosting — Workers, ingress-only Worker, native systemd, and Docker.
  • Console — the dashboard surface: login, per-repository view, Reconcile, diagnostics, manual controls.
  • Migrate from Mergify — what maps, what to retire, and how to roll back.
  • Comparison — MergeSpan vs Mergify vs GitHub’s native merge queue.
  • Versions and Upgrades — release procedure, artifacts, build identity, upgrades, rollback, and backups.
  • Sandbox Notes — the historical deployment record: prerequisites, App contract, repository configuration, ruleset, and validation steps.

Source map

ConcernPath
Configuration parser and defaultscrates/core/src/config.rs
Queue reducer (candidate, checks, merge)crates/core/src/machine.rs
Durable coordinator (outbox, reconciliation)crates/engine/src/coordinator.rs
GitHub API client and webhook modelscrates/github/src/
Cloudflare Worker runtimeruntimes/cloudflare/src/
Ingress-only Workerruntimes/cloudflare-ingress/src/index.mjs
Native runtime (systemd/Docker)runtimes/native/src/
Static console assetsweb/
Deployment templatesdeploy/
Release workflow and shared checks.github/workflows/release.yml, .github/actions/ci-build/
Repository skillsskills/mergespan-pr/SKILL.md, skills/mergespan-usage/SKILL.md

Build the site locally

The documentation site is built with mdBook and Python 3:

./site/build.sh

The output is written to _site/; dist/ remains reserved for release artifacts. Preview the complete site with Python’s built-in server:

python3 -m http.server 8000 --directory _site

Open http://localhost:8000/ for the landing page and http://localhost:8000/docs/ for the handbook. The build includes link and Markdown checks.

Quick Start

This guide takes one repository from a fresh GitHub App and runtime to a queued pull request. It is written to be delegated verbally: run the steps in order. No webhook delivery is required at any point; Reconcile initializes a repository with zero config history and zero deliveries.

Installing the App on the repository is the enable/cutover action. Prepare the verification workflow, labels, and rulesets in step 2 first. If another merge queue is active, stop it before the installation in step 3; do not run two queues against the same base branch.

1. Deploy the runtime and create the GitHub App

  1. Create the GitHub App with the permissions and event subscriptions in GitHub App. Set its webhook URL to https://<worker-host>/webhook (active, JSON) and use the same secret as GITHUB_WEBHOOK_SECRET.
  2. Deploy the runtime from Self-Hosting. For the default Cloudflare Worker set:
    • GITHUB_APP_ID as a plain var;
    • GITHUB_APP_PRIVATE_KEY and GITHUB_WEBHOOK_SECRET as secrets;
    • the console OAuth bindings below.
  3. Do not install the App on the repository yet. Complete step 2 first so the repository is ready when installation enables MergeSpan.

For the console, the Worker needs GITHUB_APP_CLIENT_ID (plain var), GITHUB_APP_CLIENT_SECRET (secret), and SESSION_SECRET (secret, at least 32 bytes). The OAuth callback is https://<host>/auth/callback. The native runtime uses dashboard_origin, app_client_id, app_client_secret_file, and session_secret_file (or the default credential paths); see Self-Hosting.

Immediate errors at this stage:

  • GET /health is not 200: the runtime is not reachable; fix deployment before continuing.
  • /auth/* or /api/v1/* returns 503: the dashboard OAuth bindings are absent. Pages still serve, but sign-in and the API do not.

2. Prepare the repository before enabling

2.1 Add the verification workflow to the base branch

The workflow must run on push to mergespan/queue/** and skip the branch-creation push. A pull_request trigger alone does not verify the candidate. Use the exact shape in Configuration → Verification workflow requirements; the required check names are the caller-prefixed job names, for example verify / fast.

Merge the workflow to the base branch before queueing. The candidate is built from the base commit, so a workflow that exists only on a pull request head is not the base’s verification contract.

2.2 Create the labels

MergeSpan does not create labels. Create the names from the config (the defaults are queue and urgent), or reuse existing labels with those exact names:

gh label create queue --description "MergeSpan queue" --color 0E8A16
gh label create urgent --description "MergeSpan urgent" --color D93F0B

If a label already exists, keep it; do not create a duplicate. Adding a label that does not exist is rejected by GitHub and no queue entry is created.

2.3 Configure squash and rulesets

  • Repository settings: allow squash only (disable merge commits and rebase if you want the UI to enforce it).
  • Base branch ruleset: require a pull request, require the mergespan status check scoped to the MergeSpan App, leave strict up-to-date off, and use no bypass actors.
  • Require every check that must pass on the candidate by its exact name. With no config file, MergeSpan infers required_checks from the required status check contexts in the active rulesets that apply to main; the MergeSpan mergespan gate is excluded.
  • mergespan/queue/** ruleset: restrict creations, updates, and deletions to the MergeSpan App, with no human bypass.

Fileless inference reads rulesets only. Classic branch protection is not consulted, and MergeSpan does not request Administration read, change repository permissions, or change rulesets for you. If you only have classic branch protection, add a ruleset for the base branch. If the rulesets cannot be read, setup reports a failure and MergeSpan does not start.

If you are migrating from another queue and it is still merging, prepare the candidate-check requirements now but leave the mergespan gate requirement off until step 3. Inference ignores that gate; adding it early can block the old queue before you are ready to cut over.

See Sandbox Notes → Ruleset for the exact shape.

2.4 Optional: override the inferred configuration

If the defaults fit, you do not need a configuration file. The inferred defaults are base main, labels queue and urgent, timeout 60 minutes, same_repo_only = true, and the base ruleset’s candidate checks.

To override any value, add .github/mergespan.toml to the base branch:

base = "main"
queue_label = "queue"
urgent_label = "urgent"
required_checks = ["ci"]
timeout_minutes = 60
same_repo_only = true

An explicit file always wins over inference. If the file exists but is invalid, initialization stops and there is no fallback to inference: omitting required_checks is a TOML parse error, required_checks = [] is a validation error, and same_repo_only must be true. Merge the file to the base branch; it is read from the exact base commit, never from a branch name or the pull request head. See Configuration for every key and exact error.

Merge the workflow, labels, rulesets, and any config file to the base branch before installing the App. Installation starts processing; existing queue labels are not a safe staging area.

3. Install the App and enable MergeSpan

Before installing:

  • If Mergify, GitHub’s merge queue, or another queue is active on the base branch, disable/drain it first and wait for any in-flight merge to settle.
  • Remove queue and urgent (or your configured labels) from every open pull request so the new queue cannot pick one up before you are ready.

Then install the App on exactly the one target repository. This installation is the enable action; there is no separate on switch. A freshly installed App with no webhook deliveries is supported: Reconcile initializes it.

If you deferred the required mergespan gate while an old queue was still merging, add it now that the old queue is stopped. The gate must be scoped to the MergeSpan App.

After installation:

  • After sign-in, NotFound means the App is not installed on the repository or the signed-in user is not a collaborator.
  • Sign in as a collaborator with repository write or admin. write can Reconcile, dequeue, urgent, pause, and freeze; read can inspect but cannot mutate. GitHub maintain maps to admin and triage maps to write.

4. Sign in and inspect the initial setup

Open the console, sign in, and open the repository page. The setup evidence is on the repository’s Diagnostics page (also reachable from the setup banner).

repository_config has three possible outcomes:

  • explicit file valid: passed with the explicit configuration message;
  • file confirmed absent and inference valid: passed, stating that .github/mergespan.toml is absent, that the base was inferred from the active branch rules, and the exact required checks;
  • invalid file, or inference that cannot produce a safe list: failed with the reason and remediation.

A confirmed missing file is not “Not enabled” by itself: a fileless repository is a supported configuration. Do not add a file only to make the row green if inference already lists the checks you want.

When setup is not fully passed, the panel shows the full checklist. When everything passes, it keeps the base configuration evidence visible. Before setup is complete, you may see:

  • app_permissions and app_events: passed when the App matches GitHub App.
  • repository_config: passed for an explicit or inferred configuration, failed for an invalid explicit file or unusable inference.
  • config_loaded: unknown because no durable coordinator snapshot exists yet.
  • delivery_health: unknown with zero delivery attempts. This is not a failure and does not block initialization.
  • base_rules: passed if step 2.3 is applied.
  • base_bypass and queue_branch_rules: may be restricted because MergeSpan does not request Administration read; confirm those rules manually. A restricted result is not a failed setup.

The summary is Failed if any check failed, Unknown while evidence is missing, or Restricted if all readable checks passed but some need repository administrator confirmation. A fully green summary is not expected before the first candidate.

With the repository prepared in step 2, repository_config should be passed with either Base `main` configuration is valid: N required check(s), same_repo_only=true. for an explicit file or a message that .github/mergespan.toml is absent and the configuration was inferred from the active branch rules, with the exact required checks. If inference cannot produce a safe list, the row is failed with remediation instead of green. base_rules should be passed; config_loaded remains unknown until Reconcile; required_checks_observed may remain unknown until GitHub has check-run evidence; delivery_health remains unknown with zero deliveries.

5. Reconcile and verify the configuration loaded

On the repository page click Reconcile (write permission required). The click is asynchronous: the request is persisted first and the API returns accepted (HTTP 202); it does not mean initialization finished. On a later slice or alarm the runtime reads the base commit, then the explicit .github/mergespan.toml or the rulesets used for fileless inference, creates the coordinator, and scans queue-labeled pull requests. If a reconcile is already running or a merge is unresolved, the request waits; a failed pass is retried on a backoff and the Diagnostics page records the last result and next run.

Wait until Diagnostics shows a completed reconcile and config_loaded is passed with either the explicit loaded-configuration message or the inferred-configuration message (base, required-check count, and that the configuration came from active branch rules). The repository_config row lists the exact inferred check names. A 202 alone is not proof that the config loaded.

Immediate errors at this stage:

  • Any non-Reconcile write before initialization: HTTP 409 with MergeSpan has not received any events for this repository yet. Try Reconcile first.
  • Reconcile while the queue is safety-blocked: HTTP 409; resolve the safety pause first (resume requires admin).
  • Read-only session: HTTP 403; sign in with write or admin.
  • repository_config failed or an inference failure: Reconcile cannot initialize. Fix the explicit file or the base ruleset named in the message, then click Reconcile again. The setup diagnostic is the actionable evidence; config_loaded stays unknown.

Before labeling the test pull request, confirm the queue is empty: no queue/urgent labels and no active candidate.

6. Queue one test pull request and read the result

  1. Open a non-draft pull request from this repository targeting the configured base. Wait for its own CI to pass.
  2. Add the configured queue label (default queue): gh pr edit <number> --add-label queue, or comment @mergespan queue.
  3. Watch the mergespan check and the console. A green mergespan check is not, by itself, proof that a squash happened: the App can publish the gate as Success with Candidate verified; authorizing the guarded squash before the final freshness reads and merge. Confirm both:
    • GitHub shows the pull request merged with a merge commit; and
    • the console shows the Merged event with the merge SHA and post-merge evidence (or a post-merge mismatch pause).
  4. Only after that confirmation, clean up your local branch. If the check is Failure or the label was removed, read the newest mergespan[bot] comment; common reasons are in How It Works → What removes a pull request.

If the check is green but GitHub still shows the pull request open, wait and inspect the console; do not merge it yourself or re-add the label.

Next steps

  • How It Works — the full pipeline, failure surfaces, and recovery.
  • Configuration — every key, type, default, inference rule, and exact error.
  • GitHub App — permissions and event subscriptions.
  • Console — diagnostics, manual controls, and Reconcile.

How It Works

MergeSpan is a durable queue for one repository and one target branch. Each pull request passes through a small set of states before it lands:

labeled with queue → candidate built → required checks pass → merge freshness verified → squash merged → candidate branch deleted

The important design premise: MergeSpan does not trust webhooks to be authoritative. A webhook delivery is only a hint that makes MergeSpan fetch again from GitHub. Observations are the source of truth.

Notation

  • A — current commit of the base branch.
  • B — current head commit of the pull request.
  • C — candidate commit: base tip plus pull request head, committed on mergespan/queue/<number>.
  • check mergespan — the check run MergeSpan publishes on the pull request head (B), never on C itself.

Zero-event initialization (first run)

Before any webhook arrives, a repository has no durable state. From the Console, open the repository page and click Reconcile.

The exact sequence:

  1. The reconcile request is persisted before any network call, and the API answers accepted (HTTP 202). The response acknowledges the request only; initialization runs on a later slice. A repository with no coordinator may only be initialized by a Reconcile panel action; every other write is rejected as NotInitialized.
  2. On the next slice, the runtime calls connect:
    • Mint an installation token scoped to this repository.
    • Read main (the default base used at bootstrap) and .github/mergespan.toml at that exact commit, with ?ref=<sha>.
    • Construct a QueueSession and a Coordinator.
    • Require same_repo_only = true. A config without it fails SameRepoOnlyRequired.
  3. The first alarm performs discovery reconciliation: it lists open pull requests carrying the queue label and starts verification for each eligible one.

A freshly installed App with zero webhooks therefore reaches a running queue through the console. The webhook is not mandatory for initialization. See Console for the Reconcile flow.

Full ordering of stages

Each queued pull request moves through these stages in order.

1. Enqueue

The pull request must be open, not draft, target the configured base, and carry the queue label. Fork heads are never queued with same_repo_only = true.

  • Add the label with gh pr edit <number> --add-label queue.
  • Or comment @mergespan queue.
  • Urgent: comment @mergespan urgent. It adds urgent and queue if missing, then moves the pull request to the front. See Urgent preemption below.

MergeSpan records a Queued event with position. With urgent, the position is 1.

2. Candidate creation

MergeSpan creates mergespan/queue/<number> at the current base commit A, then pushes candidate C = A + B to the same ref. One queue entry produces two pushes:

  • Push A: branch creation.
  • Push C: candidate update.

The verification workflow should skip the creation push (github.event.created == false) and run only on C. A concurrency group per ref and created value prevents a late creation push from cancelling the candidate run. See Sandbox Notes → Verification workflow for the exact workflow shape.

On green, expected artifacts are:

  • branch mergespan/queue/<n>
  • candidate SHA C pushed once to that branch
  • required check runs on C
  • a mergespan check run on PR head B

3. Required checks

MergeSpan reads checks on C. A check counts only when:

  • it is one of required_checks,
  • its source is GitHubActions,
  • its head SHA is exactly C,
  • its status is Completed with conclusion Success.

Neutral, skipped, cancelled, timed out, stale, action required, or unknown conclusions do not count. If the same check name runs more than once, MergeSpan picks the newest by started_at_ms; ties favor a failed observation over success.

When all required checks pass, MergeSpan publishes ChecksPassed and moves to merge freshness verification.

4. Merge freshness verification

Before squashing, MergeSpan re-reads:

  • the pull request (must still be open, non-draft, target the base, still labelled queue, head SHA still B),
  • the base branch (must still be A),
  • the candidate branch (must still point at C, and C’s tree must still match the verified candidate tree).

Any mismatch cancels the current candidate and rebuilds: the candidate is re-created on the new base/head and verified again. This is the pre-build re-observation step.

5. Squash merge

MergeSpan squash-merges B with head pinned to B through the GitHub API. This is not atomic: GitHub’s merge API pins PR head B, not the base branch, so a concurrent merge can land first. MergeSpan re-reads PR and refs immediately before squashing, then reconciles:

  • The squash commit’s parent must be A and its tree must equal C.
  • A parent/tree mismatch pauses the queue and comments on the pull request. It is never reported as success.
  • A moved base requires a new candidate.

5. Squash merge

MergeSpan squash-merges B with head pinned to B through the GitHub API. This is not atomic: GitHub’s merge API pins PR head B, not the base branch, so a concurrent merge can land first. MergeSpan re-reads PR and refs immediately before squashing, then reconciles:

  • The squash commit’s parent must be A and its tree must equal C.
  • A parent/tree mismatch pauses the queue and comments on the pull request. It is never reported as success.
  • A moved base requires a new candidate.

6. Confirm merge, then cleanup

The mergespan check can be green (candidate verified) before the final freshness reads and the squash itself; green is not proof that anything merged. Cleanup happens only after GitHub reports the PR as merged and MergeSpan’s post-merge read confirms the merge SHA’s parent is A and its tree equals C:

  • MergeSpan cancels any workflow runs for C and deletes mergespan/queue/<n>. A missing branch (404) counts as success.
  • Cleanup completion releases the ref gate.
  • If the post-merge read mismatches, the queue is paused and the PR is commented; it is never reported as success. Investigate before re-queueing.

Urgent preemption

The urgent label moves a pull request to position 1 and interrupts the candidate being verified, unless the active candidate is already in Merging phase or belongs to the urgent pull request itself.

  • The interrupted pull request stays queued.
  • It is rebuilt later on the current base.
  • Urgent cannot cancel a squash merge already issued.
  • Use only when the user asks for it: it interrupts whoever is being verified.

What removes a pull request from the queue

ReasonObservable resultWhat to do
Required check failed on Cmergespan check Failure on B; queue label removed; comment links the failing runFix the failure, push, add queue again
Push to the pull request while queuedHead moved; queue label removed; comment with old and new headFinish all pushes, then add queue again
Base moved before mergeCandidate rebuilt; label may stay on queueKeep waiting
Validation exceeded timeout_minutesDequeued with timeout reason; label removedFind out why the check was slow before queueing again
Squash merge conflictDequeued with merge conflict reason; label removedMerge the base, resolve conflicts, push, add queue again
Squash refused / gate revocation failed closedDequeued with squash refusal reason; label removedInvestigate GitHub merge API status; re-queue after investigation
Pull request closed, converted to draft, retargeted, or queue label removedRemovedRe-queue once eligible again

Manual controls

The console exposes:

  • Reconcile — initializes a repository before any webhook, or re-scans queue labels after it is running. Also resumes a queue after configuration changes.
  • Pause — no new candidates, no merges. Queued pull requests keep their place.
  • Freeze — candidates are still verified; nothing is merged.
  • Dequeue — removes queue and urgent from one pull request. Cannot cancel a squash merge already issued.
  • Resume — operator action after investigating a fail-closed pause.

A paused or frozen queue shows its reason in the mergespan check summary or console state view. Do not remove the label or push to work around it.

Failure surfaces and actions at a glance

StageFailure surfaceSource of diagnosisAction
Configuration loadmissing or invalid .github/mergespan.toml; same_repo_only != true; base mismatchConsole setup check repository_config, config_loadedFix TOML on base branch; re-run Reconcile
App identitywrong App ID, missing private keyConsole setup app_permissions / app_eventsRestore documented App settings
Candidate creationbranch creation refused, branch head read failuremergespan check Failure; candidate branch missingRestart queue / Reconcile; verify App contents:write
Checks never appearcandidate branch exists but no check runsVerification workflow concurrency; created == false gateFix workflow trigger; see Sandbox Notes
Check failure / timeoutrequired check missing, neutral, or non-success on CLinked Actions run; check name, source, exact SHAFix CI; re-queue
Merge freshness mismatchbase moved, head pushed, candidate tree changedConsole events; check Failure summaryRe-queue when ready
Squash failureconflict or refusal from GitHub APImergespan check Failure; merge refusal messageResolve conflict or investigate; re-queue
Cleanup failurecandidate branch deletion refusedConsole outbox / diagnosticsRetry queue action; branch cleanup is best-effort for ref gate release

State invariants

  • Only one candidate is active per repository.
  • Commands are durable before any network call; a crash leaves an intent checkpoint that recovers on restart.
  • Deduplication is by X-GitHub-Delivery; the receipt, new state, and outbox rows are written in one SQLite transaction.
  • Observations carry monotonically increasing sequence numbers; stale reads are discarded.
  • While a merge is unresolved, reconciliation is suspended so a generic PR snapshot cannot end the candidate before post-merge parent/tree reconciliation runs.

Flowchart

The site renders this flowchart directly on GitHub (Mermaid is supported in READMEs). It is not a separate image; no external assets are loaded.

flowchart TD
    A[PR labelled queue] --> B[Create mergespan/queue/<n> at base A]
    B --> C[Push candidate C = A + B]
    C --> D[Required checks on C]
    D -- fail/timeout --> E[Remove label, comment, dequeue]
    D -- pass --> F[Re-read PR, base, candidate]
    F -- mismatch --> C
    F -- fresh --> G[Squash merge B]
    G -- parent/tree mismatch --> H[Pause queue, comment]
    G -- ok --> I[Delete candidate branch]

External links are not part of this flow; the Markdown links above stay relative to docs/ and resolve on GitHub as docs/<name>.md after navigation to docs/<name>.html.

Configuration

MergeSpan’s repository configuration is optional. It reads .github/mergespan.toml from the exact base commit at initialization and whenever it reloads the configuration, using ?ref=<base_sha>. The file is never read from a branch name or the pull request head.

The precedence is strict:

  1. Explicit file wins. If .github/mergespan.toml exists at the base commit, every value comes from that file.
  2. Confirmed absence is inferred. If the file is confirmed absent at the base commit, MergeSpan uses conservative defaults and infers the required candidate checks from the active branch rulesets on main.
  3. Invalid file halts. If the file exists but cannot be parsed or validated, initialization stops. MergeSpan never falls back to inference or defaults for an invalid file; fix the file and re-run Reconcile.

A 404 for the file is the only result that selects inference. A failed read, an unresolved ref, or an unreadable ruleset is unknown, not proof that the file is absent.

Inferred configuration (no file)

With no .github/mergespan.toml on the base commit, MergeSpan uses:

SettingInferred value
basemain
queue_labelqueue
urgent_labelurgent
timeout_minutes60
same_repo_onlytrue
required_checksExact required status check contexts from the active branch rulesets on main, excluding the MergeSpan mergespan gate.

required_checks inference works as follows:

  1. MergeSpan reads the effective branch rules for main, which layer every active ruleset that applies to the branch. It does not read classic branch protection, request Administration permission, or change any repository permission.
  2. It collects the exact context of each required status check across those rulesets, deduplicated. It does not guess, glob, or strip caller prefixes.
  3. It excludes the mergespan check that MergeSpan itself publishes on the pull request head. That gate is not a candidate check and can never pass on candidate C.
  4. Unbound contexts are treated as GitHub Actions check runs; contexts bound to GitHub Actions are kept the same way. They must pass from GitHub Actions on the exact candidate SHA; another source cannot satisfy them.
  5. Inference fails closed if the rules cannot be read or interpreted, if no required-status-check rule applies, if no useful check remains, or if a required check is explicitly bound to an App other than GitHub Actions (MergeSpan matches only GitHub Actions check runs). The setup check reports the failure and remediation; MergeSpan does not queue with an empty or partial check list.

Fileless inference always uses base main. To use another base, custom labels, a different timeout, or an explicit check list, add .github/mergespan.toml to the base branch. An explicit file is an override, not a requirement.

Keys (explicit file)

The parser uses deny_unknown_fields. Any key not listed below produces a parse error.

KeyTypeDefaultRequiredNotes
basestring"main"noBranch candidates are built from and merged into. v0.1 bootstraps from main; the config must declare base = "main" at first initialization. A different base is rejected with ConfigMismatch.
queue_labelstring"queue"noLabel that enqueues a pull request. Must not be empty. Must differ from urgent_label.
urgent_labelstring"urgent"noLabel that moves a pull request to the front and preempts the active candidate. Must not be empty. Must differ from queue_label.
required_checksarray[string]—yes in an explicit fileNo default in an explicit file: omitting the key is a TOML missing field parse error; [] passes parsing but fails validation with “must list at least one check”. In a fileless repository this list is inferred instead. Exact GitHub Actions check run names, matched by name, source GitHubActions, and exact candidate SHA. Must not contain empty strings or duplicates.
timeout_minutesinteger60noMaximum time to wait for all required checks on a candidate. Must be > 0. Expressed in minutes; the runtime multiplies by 60,000 ms with saturation.
same_repo_onlybooleanfalse (parser) / required true by runtimeno (parser) / yes (runtime)When true, only pull requests whose head branch lives in this repository are queued. The v0.1 runtime rejects any explicit config with false or omitted (SameRepoOnlyRequired). Inference sets it to true.

Example explicit file

base = "main"
queue_label = "queue"
urgent_label = "urgent"
required_checks = [
  "ci / fast",
  "ci / integration",
]
timeout_minutes = 60
same_repo_only = true

A minimal explicit override on main only needs the values you are changing plus same_repo_only = true:

required_checks = ["ci / fast", "ci / integration"]
same_repo_only = true

Exact errors (explicit file)

A missing file does not produce these errors; it selects inference. These come from Config::from_toml and Config::validate when the file exists.

TriggerError message (user-facing)
Unknown key in TOMLinvalid mergespan.toml: unknown field <key>, expected one of base, queue_label, urgent_label, required_checks, timeout_minutes, same_repo_only
base empty or whitespaceinvalid mergespan.toml: `base` must not be empty
queue_label empty or whitespaceinvalid mergespan.toml: `queue_label` must not be empty
urgent_label empty or whitespaceinvalid mergespan.toml: `urgent_label` must not be empty
queue_label == urgent_labelinvalid mergespan.toml: `queue_label` and `urgent_label` must differ
required_checks omittedTOML parse error containing missing field `required_checks` ; this happens before validation
required_checks = []invalid mergespan.toml: `required_checks` must list at least one check
required_checks contains empty stringinvalid mergespan.toml: `required_checks` must not contain an empty name
required_checks contains duplicateinvalid mergespan.toml: `required_checks` contains `<name>` more than once
timeout_minutes == 0invalid mergespan.toml: `timeout_minutes` must be greater than zero

Runtime bootstrap constraints (additional to parser validation)

ConditionResultWhere
config.base != base_ref (the branch read during bootstrap)ConfigMismatch { declared, expected }QueueSession::load
same_repo_only != true in an explicit fileSameRepoOnlyRequiredQueueSession::load
.github/mergespan.toml confirmed absent at the base commitinferred configuration, not an errorconfiguration load
Inference cannot produce a safe check listhard stop; setup failure and remediationconfiguration load / setup
File is not valid UTF-8Invalid("mergespan.toml is not valid UTF-8")load_config_at
File parse error (above)propagated from Config::from_toml; no inference fallbackload_config_at

The console setup check repository_config reports a fixed diagnostic rather than the parser’s full error text:

  • explicit valid file: passed, Base `main` configuration is valid: N required check(s), same_repo_only=true.
  • fileless inference succeeded: passed. The Base configuration row says .github/mergespan.toml is absent, that the base was inferred from the active branch rules, and lists the exact required checks. config_loaded later reports the inferred configuration with its base and check count, and notes that adding a file would pin it.
  • confirmed missing file with unusable inference: failed, .github/mergespan.toml is absent and the effective configuration could not be inferred from the base branch's GitHub rules: <reason>. The remediation is either an active base ruleset that requires at least one GitHub Actions check, or a valid explicit file with required_checks.
  • invalid or incomplete file: failed, .github/mergespan.toml on the base branch cannot be used: configuration is missing fields or is invalid.
  • explicit parser default left unchanged: same_repo_only is false on base `main`; MergeSpan requires true.

config_loaded stays UNKNOWN until a durable coordinator snapshot exists. A successful setup row is not proof that the queue initialized; Reconcile is.

Because branch rules are live and are not part of the base commit, an inferred configuration is re-derived before candidate creation and again immediately before the final merge gate. A changed ruleset therefore makes an in-flight candidate fail closed instead of merging under a stale check list; if inference becomes unusable, the queue blocks. An explicit configuration change while a candidate is active is deferred: the old configuration stays effective until the candidate finishes. After changing the file or the rulesets that inference reads, re-run Reconcile and confirm config_loaded before queueing more work. A running v0.1 queue cannot be retargeted in place: bootstrap is fixed to main, so a different base is a ConfigMismatch, not a live reload.

Verification workflow requirements

The required check names, explicit or inferred, must match the exact GitHub Actions check-run names produced on the candidate. With a reusable verification workflow, that means caller-prefix qualified names: if the workflow is called verify and its jobs are fast and integration, the required names are verify / fast and verify / integration.

The workflow must run on push to mergespan/queue/** with github.event.created == false:

on:
  push:
    branches: ["mergespan/queue/**"]
  pull_request:
    branches: [main]
concurrency:
  group: verify-pr-${{ github.ref }}-${{ github.event.created }}
  cancel-in-progress: true
jobs:
  verify:
    name: verify
    if: >-
      (github.event_name == 'push' &&
       github.event.created == false &&
       startsWith(github.ref, 'refs/heads/mergespan/queue/')) ||
      (github.event_name == 'pull_request' &&
       github.event.pull_request.head.repo.full_name == github.repository)
    uses: ./.github/workflows/verify.yml

Only the candidate push C (created == false) produces the required check runs. A same-repository pull request run is also allowed; fork pull requests are skipped because their head repository differs. See Sandbox Notes for the exact workflow used in the sandbox deployment.

Source map

FunctionFile
Config::from_toml / Config::validatecrates/core/src/config.rs
Configuration load and fileless inferencecrates/engine/src/queue_api.rs
Setup evidencecrates/engine/src/dashboard/setup.rs
Coordinator::new_with_source / on_config_with_sourcecrates/engine/src/coordinator.rs

GitHub App

MergeSpan requires a GitHub App installed on the target repository. This page documents the exact permissions, event subscriptions, webhook contract, and secrets.

Permissions

PermissionLevelRequiredPurpose
MetadataReadyesMandatory; every App has it.
ContentsRead & WriteyesCreate candidate branch/commit; squash merge.
Pull requestsRead & WriteyesRead PR state; merge.
IssuesRead & Writeyesqueue / urgent labels and PR comments.
ChecksRead & WriteyesCreate/read the mergespan check run on the PR head.
ActionsRead & WriteyesCancel candidate workflow runs.
WorkflowsNot requirednoDirect workflow writes were not tested in v0.1; the App does not request this.
AdministrationNo—Never requested.
MembersNo—Never requested.
OrganizationNo—Never requested.

These permissions map exactly to the GitHub API endpoints the runtime calls (see crates/github/src/endpoints.rs and queue_api.rs):

  • GET /repos/{owner}/{repo}/pulls/{number} — pull request details (Pull requests: read).
  • GET /repos/{owner}/{repo}/pulls — list open PRs on base (Pull requests: read).
  • PUT /repos/{owner}/{repo}/pulls/{number}/merge — squash merge (Pull requests: write).
  • GET /repos/{owner}/{repo}/git/refs/heads/... — branch heads (Contents: read).
  • POST /repos/{owner}/{repo}/git/refs — create candidate branch (Contents: write).
  • POST /repos/{owner}/{repo}/git/commits — create candidate commit (Contents: write).
  • DELETE /repos/{owner}/{repo}/git/refs/heads/mergespan/queue/<n> — cleanup (Contents: write).
  • GET /repos/{owner}/{repo}/contents/.github/mergespan.toml?ref=<sha> — read config (Contents: read).
  • GET /repos/{owner}/{repo}/commits/{sha}/check-runs — read checks on candidate (Checks: read).
  • POST /repos/{owner}/{repo}/check-runs — publish mergespan check (Checks: write).
  • POST /repos/{owner}/{repo}/issues/{number}/comments — comment on PR (Issues: write).
  • DELETE /repos/{owner}/{repo}/issues/{number}/labels/{name} — remove labels (Issues: write).
  • POST /repos/{owner}/{repo}/actions/runs/{id}/cancel — cancel candidate workflow (Actions: write).

Event subscriptions

The App must subscribe to these events (exact names, case-sensitive):

  • push
  • pull_request
  • check_run
  • check_suite
  • workflow_run
  • issue_comment

Missing subscriptions are surfaced in the console setup check app_events as FAILED with the missing event names.

Why each event

EventPurpose
pushCandidate creation/update on mergespan/queue/**; also base branch advance.
pull_requestLabel changes, open/close/ready/draft/retarget; the source of truth for queue eligibility.
check_runCandidate check status transitions; the primary validation signal.
check_suiteCompletion of the candidate’s check suite.
workflow_runCandidate workflow run lifecycle; used for cancellation.
issue_comment@mergespan command comments (queue, urgent, dequeue, refresh, help).

Webhook contract

  • URL: https://<worker-host>/webhook (or ingress Worker). Active, JSON.
  • Secret: The same value stored as GITHUB_WEBHOOK_SECRET in the Worker and in the App’s webhook settings.
  • Verification: The Worker verifies X-Hub-Signature-256 (HMAC-SHA256 over the exact raw body bytes). Missing signature → 401. Missing event → 400. Missing delivery ID → 400. Missing secret → 500. Body > 1 MiB → 413/400. Signature mismatch → 401.
  • Deduplication: X-GitHub-Delivery is deduplicated transactionally in SQLite. A replay returns the original acceptance status (202) and only adds a diagnostic attempt row; the state is never rewritten.
  • Filtering: Unsupported events (e.g., release, deployment) return 202 ignored. Ping returns 200 pong.
  • Internal marker: The alarm transport emits one non-secret structured marker {"event":"installation_token","result":"ok"} when an App-JWT installation-token exchange passes the client’s acceptance checks. Failures emit no marker. Observable with wrangler tail. No headers, tokens, or bodies are persisted.

Secrets

NameStorageNotes
GITHUB_APP_IDWorker var (plain text)Not a secret. The numeric App ID.
GITHUB_APP_PRIVATE_KEYWrangler secret (PEM)Full PEM including BEGIN/END lines and newlines. Never on command line, in shell history, wrangler.toml, repo, chat, PR/issue, or logs.
GITHUB_WEBHOOK_SECRETWrangler secretSame value in the App’s webhook settings. Never on command line, in history, repo, chat, PR/issue, or logs.
cd runtimes/cloudflare
wrangler secret put GITHUB_APP_PRIVATE_KEY   # paste the full PEM at the prompt
wrangler secret put GITHUB_WEBHOOK_SECRET    # or: ... < /path/outside/repo/secret

The native runtime reads both secrets from files via systemd LoadCredential= (or --app-private-key-file / --webhook-secret-file flags). They are never accepted in the environment, config file, command line, or stdout.

Installation scope

Install the App on exactly one repository per queue. The sandbox installation lists only mergespan-sandbox. The console discovers repositories through the App’s installations and lists only those the App is installed on and the user has access to. Do not install on the ModelRouter organization or all repositories; the cutover is a separate step (U6 in the sandbox record).

Source map

ConcernFile
App permissions / events validationcrates/engine/src/dashboard/setup.rs (app_permissions, app_events)
Webhook verification / hint extractioncrates/engine/src/hint.rs
API endpoints usedcrates/github/src/endpoints.rs
Installation token mintingcrates/github/src/auth.rs
Cloudflare webhook handlerruntimes/cloudflare/src/ingress.rs
Ingress-only Workerruntimes/cloudflare-ingress/src/index.mjs
Native runtime authruntimes/native/src/ingress.rs

Self-Hosting

MergeSpan has three runtime shapes:

  1. Cloudflare Worker (default) with SQLite-backed Durable Objects.
  2. Ingress-only Worker (optional split) that receives webhooks in front of the main Worker.
  3. Native Linux process via systemd or Docker, with one SQLite WAL database per repository.

All shapes expose only GET /health and POST /webhook publicly. Put a TLS proxy or Cloudflare Tunnel in front of the native listener; it never terminates TLS itself.

Cloudflare Workers

Prerequisites

  • A Cloudflare account on the Free plan. Use only Workers Free with SQLite-backed Durable Objects (new_sqlite_classes, one DO per repository). Do not add paid resources.

  • worker-build 0.9.0, pinned:

    cargo install worker-build --version 0.9.0 --locked
    
  • Wrangler: Wrangler 4.169.1 was checked locally and wrangler deploy --help documents --tag and --message as Worker Version metadata. The repository does not pin a global Wrangler version; record wrangler --version before deploying and do not upgrade during a release.

  • Rust toolchain pinned by rust-toolchain.toml.

  • The web/ directory (static console). wrangler deploy requires it; worker-build does not.

Deploy

cd runtimes/cloudflare
wrangler login
wrangler secret put GITHUB_APP_PRIVATE_KEY   # full PEM at the prompt
wrangler secret put GITHUB_WEBHOOK_SECRET    # same value as the App's webhook settings
wrangler deploy                              # [build] runs worker-build --release
curl -fsS "https://<worker-host>/health"

For a tagged production release, deploy the verified Worker package instead of building from main; see Deploy a tagged release (Worker). That package has no build step and embeds the tag commit.

The top-level Wrangler configuration is the default deployment: mergespan and mergespan-ingress, which follow main. Production is the separate mergespan-prod Worker and its mergespan-prod-ingress ingress, selected with -e production; deploy them only from a vX.Y.Z release tag, never from main. Production has its own Durable Object namespace and SQLite storage, and it needs its own vars and secrets — do not reuse the dev App’s values. The first-time production setup and commands are in Deploy a tagged release (Worker).

GITHUB_APP_ID is a non-secret identifier. Set it as a plain [vars] entry in runtimes/cloudflare/wrangler.toml.

The Worker also hosts the console: Workers Static Assets stores web/, while /auth/* and /api/v1/* run the runtime-neutral dashboard service. Dashboard bindings are optional; without them, pages still serve but auth/API answer 503:

BindingKindPurpose
GITHUB_APP_CLIENT_IDplain varOAuth client ID
GITHUB_APP_CLIENT_SECRETsecretOAuth client secret
SESSION_SECRETsecret, ≥ 32 bytesSession signing; also derives the internal dashboard relay key with purpose mergespan/dashboard-do/v1

The OAuth callback is https://<host>/auth/callback. The App uses only its mandatory Metadata repository permission (read) for the collaborator-permission check; no Administration permission.

Ingress-only Worker (optional split)

The split exists because the Rust/Wasm webhook path exceeded 10 ms CPU on fresh isolates. The JS entry has had no 1102 errors in live runs on Workers Free; measurements and acceptance rules are in runtimes/cloudflare-ingress/README.md.

Its Wrangler entry is a zero-npm JavaScript ES module at runtimes/cloudflare-ingress/src/index.mjs with only GET /health and POST /webhook. There is no build command, npm install, Durable Object class, SQLite store, GitHub orchestration, RSA signing, or dashboard route.

The REPOSITORY binding is a cross-script binding to the existing mergespan / RepositoryObject namespace. It adds no migration, route, or authentication bypass. The Durable Object still owns deduplication.

cd runtimes/cloudflare-ingress
wrangler secret put GITHUB_WEBHOOK_SECRET   # same value as the existing Worker
wrangler deploy
curl -fsS "https://<ingress-host>/health"

Only GITHUB_WEBHOOK_SECRET is needed; no App ID or private key. Deploy the existing mergespan Worker first, because the binding targets it. For production, use wrangler deploy -e production (and wrangler secret put GITHUB_WEBHOOK_SECRET -e production); its value must match mergespan-prod’s, not the default Worker’s. Rollback: delete the ingress Worker and point the App webhook back at the existing Worker’s /webhook; no data migration is involved.

The DO alarm transport emits one non-secret marker {"event":"installation_token","result":"ok"} only when an App-JWT installation-token response passes the GitHub client’s acceptance checks. Failures emit no marker. It is observable with wrangler tail, contains no token/header/body data, and does not enable paid features or change quotas/backstop.

Native Linux (systemd)

The same engine runs as one native Linux process outside Cloudflare: one locked data directory may hold any number of repositories, each with its own SQLite WAL database under repos/repo-<numeric id>.sqlite3, and a static musl binary for x86_64 or aarch64.

Deliveries are routed by the signed numeric repository ID; each queue re-arms independently, and an outbound await in one repository does not block ingress or work for another. It exposes only GET /health and POST /webhook; it is HTTP-only, so put a TLS proxy or Cloudflare Tunnel in front of 127.0.0.1:8080 and never expose the listener directly.

Build

rustup target add x86_64-unknown-linux-musl aarch64-unknown-linux-musl
cargo zigbuild --locked --release -p mergespan-runtime-native \
  --target x86_64-unknown-linux-musl

CI builds and verifies both targets. See Versions and Upgrades for build verification details.

Install

install -m 0755 target/x86_64-unknown-linux-musl/release/mergespan /usr/local/bin/mergespan
install -D -m 0644 deploy/mergespan.toml /etc/mergespan/mergespan.toml
install -m 0644 deploy/mergespan.service /etc/systemd/system/mergespan.service
# Put the PEM and webhook secret in the two LoadCredential= files, then:
systemctl daemon-reload && systemctl enable --now mergespan
curl -fsS http://127.0.0.1:8080/health

Credential values are read only from files: either the --app-private-key-file / --webhook-secret-file flags or, by default, github-app-private-key and github-webhook-secret inside $CREDENTIALS_DIRECTORY (systemd LoadCredential=). They are never accepted in the environment, config file, command line, or stdout. Diagnostics are one-line redacted JSON.

Files:

One deliberate difference from the Worker: when repository_owner/name are configured and a correctly signed delivery arrives for a different repository, the response is 403 instead of the Worker’s 502-for-a-DO-rejection, so GitHub does not retry a routing mismatch this process is configured to refuse. Without that optional binding, any repository the App delivers is served by its own queue.

Operational behavior matches the Worker where it matters: raw X-Hub-Signature-256 verification with a 1 MiB body cap, 202 only after the delivery and signal are committed in one SQLite transaction, deduplication by X-GitHub-Delivery, read-first recovery for an interrupted squash, and an advisory data-directory lock that makes a second live instance fail fast. SIGTERM stops accepting, drains bounded, and leaves a recoverable checkpoint; Restart=on-failure re-arms persisted outbox work.

Docker

CI builds the binary once per architecture and passes the same prebuilt binary to the Dockerfile; the image has no compiler or package manager.

On a Linux host with default Docker UID mapping, prepare the private bind mounts before the first run. The state directory must be writable by UID 65532. Install copies of the credential files outside the repository, readable only by that UID, and mount them read-only; do not make credentials world-readable. With rootless Docker or user namespace remapping, use the host UID/GID mapped to container 65532:65532 for ownership instead.

sudo install -d -m 0700 -o 65532 -g 65532 /var/lib/mergespan-docker /etc/mergespan-docker
sudo install -m 0400 -o 65532 -g 65532 /path/to/github-app-private-key.pem /etc/mergespan-docker/
sudo install -m 0400 -o 65532 -g 65532 /path/to/github-webhook-secret /etc/mergespan-docker/
docker build -f deploy/Dockerfile \
  --build-arg BINARY=mergespan-linux-amd64 \
  -t mergespan-native:local dist

docker run -d --name mergespan \
  --read-only --user 65532:65532 \
  -p 127.0.0.1:8080:8080 \
  --mount type=bind,src=/var/lib/mergespan-docker,dst=/var/lib/mergespan \
  --mount type=bind,src=/etc/mergespan-docker,dst=/etc/mergespan,readonly \
  mergespan-native:local \
  --app-id 123456 --data-dir /var/lib/mergespan \
  --listen 0.0.0.0:8080 \
  --app-private-key-file /etc/mergespan/github-app-private-key.pem \
  --webhook-secret-file /etc/mergespan/github-webhook-secret

Inside a container, bind 0.0.0.0:8080; the host-side publish above keeps the port on host loopback only (-p 127.0.0.1:8080:8080). Never publish it on 0.0.0.0. The image runs as nonroot and is HTTP only; put a TLS proxy or Cloudflare Tunnel in front.

State layout

One WAL database per repository under <data-dir>/repos/repo-<positive decimal id>.sqlite3 (no leading zeroes). Startup refuses unexpected files or orphaned SQLite sidecars in repos/. An unexpected legacy <data-dir>/mergespan.sqlite3 (or any other database-looking file outside repos/) makes the process refuse to start; it never adopts, overwrites, or migrates it.

Operational notes

  • One process owns one data directory. A second process fails the advisory flock and exits with status 3 instead of touching the database.
  • SIGTERM stops accepting new webhooks, drains in-flight work for a bounded time, and leaves a recoverable checkpoint. systemd Restart=on-failure handles crashes; the next process re-arms persisted outbox work.
  • SQLite runs in WAL mode with synchronous=FULL; keep the data directory on local disk, not a network filesystem.
  • /health is liveness only. It does not prove GitHub credentials or network reachability.
  • GET /health and POST /webhook are the only public routes. Everything else is a 404, matching the Cloudflare Worker.

Local validation (CI and release checks)

rustup target add wasm32-unknown-unknown
cargo fmt --all --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
node --test runtimes/cloudflare-ingress/test/webhook.test.mjs
cargo check --locked \
  -p mergespan-core \
  -p mergespan-engine \
  -p mergespan-github \
  -p mergespan-runtime-cloudflare \
  --target wasm32-unknown-unknown
cargo install worker-build --version 0.9.0 --locked
cd runtimes/cloudflare && worker-build --release

The release workflow’s validate job also runs bash .github/scripts/check-release-tag.test.sh, bash .github/scripts/fetch-origin.test.sh, bash .github/scripts/fetch-release-artifacts.test.sh, bash .github/scripts/fetch-previous-release.test.sh, bash .github/scripts/check-release-tools.test.sh, bash .github/scripts/release-evidence.test.sh and bash .github/scripts/reap-job-target.test.sh. Run those scripts after changing release logic, and run actionlint .github/workflows/*.yml and shellcheck .github/scripts/*.sh if installed.

Release-tag, release-evidence and restart/upgrade checks are separate and can be run locally (none creates a tag or calls GitHub):

bash .github/scripts/check-release-tag.test.sh
bash .github/scripts/fetch-release-artifacts.test.sh
bash .github/scripts/release-evidence.test.sh
cargo build --locked -p mergespan-runtime-native
NATIVE_BIN=target/debug/mergespan .github/scripts/checkpoint-smoke.sh
NATIVE_BIN=target/debug/mergespan .github/scripts/upgrade-smoke.sh historical
node .github/scripts/worker-checkpoint-smoke.mjs --tarball dist/mergespan-worker-X.Y.Z.tar.gz

The Worker harness needs a built release tarball and a local Miniflare install; if either is unavailable it reports BLOCKED rather than replacing the check with a /health probe. See Versions and Upgrades.

The native runtime deliberately has no wasm target; the wasm check selects the portable packages explicitly so the Worker validation is not weakened.

Native static validation additionally runs in CI: cargo zigbuild --release -p mergespan-runtime-native for x86_64-unknown-linux-musl and aarch64-unknown-linux-musl, then rejects any binary with PT_INTERP or DT_NEEDED; CI smoke-tests the prebuilt amd64 binary and verifies the distroless Dockerfile definition (CI does not build the image).

CI runs one job named ci on pull_request to main, with contents: read, on a fixed GitHub-hosted ubuntu-24.04 runner. Same-repository pull requests always run; a fork pull request runs only when the repository is public. The workflow references no secrets.

Every MergeSpan workflow runs on GitHub-hosted runners only; no self-hosted runner is attached to the repository. Public repositories skip the ci-build Actions caches, because a fork executes untrusted workspace code on the same hosted runner class and a cache key is not a secrecy boundary. Operators should also expire or purge pre-existing Actions caches if they may have been written from untrusted workspace or tool input; this repository does not perform that cleanup automatically.

The cache/toolchain/check/build steps live in .github/actions/ci-build and are shared with the release workflow, so the commands cannot drift; the ci job name, trigger, runner, permissions and required-check status are unchanged. The job still classifies docs/web/full changes first. It records the compressed Worker size in the job summary and fails above the 1 MB budget — a target, not a measurement.

The shared ci-build action’s cargo test --locked --workspace step also runs a short seeded merge-queue invariant sample (Full CI A: real coordinator transitions, randomized SHA/checks/base/parent/tree inputs) inside the normal PR budget; there is no separate short-test CI step. The longer sample is #[ignore]d so it never runs in the default cargo test --workspace; the explicit long command, reused by the scheduled full-ci-nightly workflow and by downstream CI workstreams, is:

cargo test --locked -p mergespan-engine --lib full_ci -- --ignored

Set MERGESPAN_FULL_CI_SEEDS / MERGESPAN_FULL_CI_STEPS to scale the long sample. full-ci-nightly runs on a clean standard GitHub-hosted runner with contents: read and no secrets, and has a 20 minute job budget.

Console

The MergeSpan console is a static single-page application served by the default Cloudflare Worker or the native runtime. It exposes per-repository state, events, diagnostics, setup checks, and operator controls. The ingress-only Worker does not serve the console.

Authentication

The console uses GitHub OAuth. Required bindings on the default Worker:

BindingKindNotes
GITHUB_APP_CLIENT_IDplain varOAuth client ID from the GitHub App settings.
GITHUB_APP_CLIENT_SECRETsecretOAuth client secret.
SESSION_SECRETsecret, ≥ 32 bytesSigns sessions and derives the internal dashboard relay key with purpose mergespan/dashboard-do/v1.

The OAuth callback is https://<host>/auth/callback. Without these bindings, pages still serve but /auth/* and /api/v1/* answer 503.

Permissions are resolved per request from GitHub and never inferred from the repository name or installation:

LevelAllows
readAll GET endpoints, including diagnostics and setup.
writeRead plus dequeue, urgent, reconcile, and state.json.
adminEverything, including resume.

GitHub’s maintain maps to admin; triage maps to write. A repository the App is not installed on, or where the user is not a collaborator, is reported as NotFound; the caller must not disclose whether the repository exists.

Repository discovery

Repository discovery uses at most 30 outgoing GitHub calls per page and reserves 10 for backend summaries (40 total, below the Workers Free 50-subrequest limit). Denied candidates count against the same budget. When work remains, GET /api/v1/repos returns a same-origin relative Link: </api/v1/repos?cursor=...>; rel="next" with a signed, expiring, user-bound cursor; the JSON body stays the RepoSummary[] array.

Pages and routes

The console serves four page routes via SPA fallback; every route returns index.html:

  • / — repository list.
  • /repos/:owner/:name — state, queue, active candidate, manual controls.
  • /repos/:owner/:name/events — append-only event timeline.
  • /repos/:owner/:name/diagnostics — deliveries, outbox, reconcile, raw state.

API routes live under /api/v1/. See crates/engine/src/dashboard/route.rs for the full routing table.

Reconcile

Reconcile is the one write that initializes a repository before any webhook arrives. From the repository page, click Reconcile:

  1. The request is persisted before any network call, and the API answers accepted (HTTP 202). That response acknowledges the request; it does not mean the repository is initialized yet. A repository with no coordinator may only be initialized by a Reconcile panel action; every other write is rejected as NotInitialized (HTTP 409 with message "MergeSpan has not received any events for this repository yet. Try Reconcile first.").
  2. On a later slice, the runtime attempts to load .github/mergespan.toml from the current base commit, create the coordinator, and scan queue-labeled pull requests through the same path as the first webhook. If another reconcile is already running or a merge is unresolved, the request waits rather than cancelling that work. A failed pass is retried on a backoff; the Diagnostics page records the last result and next scheduled run.
  3. A reconcile_requested event is recorded with the actor and request ID.

Reconcile is also used after configuration changes or to re-scan queue labels without waiting for the periodic reconciliation alarm. Reconcile is rejected with HTTP 409 while the queue is safety-blocked; resolve the pause first. Confirm completion from the Diagnostics Reconcile row and the config_loaded setup check, not from the 202 response alone.

Diagnostics

The diagnostics page exposes:

  • Deliveries — recent webhook delivery attempts with event, action, result, and timestamp.
  • Outbox — pending durable commands with phase, attempts, and last error.
  • Reconcile — last reconcile time, result, attempt count, and next scheduled run.
  • Build — running version and compiled full Git commit (unknown if the workspace had no Git metadata at build time).
  • State JSON — raw coordinator snapshot for advanced debugging.

Diagnostics are read-only (read permission). They do not expose secrets, tokens, or raw payloads.

Setup checks

The setup page runs a series of checks against the App, repository, and configuration:

CheckStatus sourceRemediation
app_permissionsGET /app permissions vs documented setRestore documented permissions manually; do not add Administration.
app_eventsGET /app event subscriptions vs required setAdd missing subscriptions in App settings.
repository_config.github/mergespan.toml on the base branchAdd the file if missing; fix invalid TOML and ensure same_repo_only = true.
required_checks_observedRecent candidate and base check runsConfirm CI reports the exact check names listed in config.
base_rulesBranch protection / ruleset on baseRequire squash only; add mergespan as required check; disable strict up-to-date.
config_loadedDurable snapshotReconcile if no snapshot exists.
delivery_healthRecent delivery attemptsCheck App webhook URL and Recent Deliveries.
manual_controlsRaw state flagsClear manual pause/freeze through the console once investigation is complete.
safety_pauseCoordinator pause reasonRead pause reason and expected/actual evidence; resolve it. Safety pause is not a manual control.
stuck_candidateActive candidate timeoutInspect candidate SHA and checks; let timeout dequeue or reconcile after fixing the underlying failure.

Setup checks are read-only and never mutate state. When the repository is readable and its base .github/mergespan.toml returns 404, the setup panel shows Not enabled and setup instructions instead of unrelated checks. The repository selector marks only repositories confirmed this way by a setup read in the current console session. Other read failures do not mean the file is absent. Unparseable TOML and a false same_repo_only are failures; config_loaded passes only after a Reconcile creates a durable coordinator snapshot.

A zero-delivery repository is supported: delivery_health is UNKNOWN with no attempts, not failed. required_checks_observed is UNKNOWN until GitHub has recent candidate or base check-run evidence, and bypass-list checks may be RESTRICTED without Administration read. The summary is failed if any check failed, otherwise unknown if any evidence is missing, otherwise restricted if any check needs administrator confirmation, and passed only when all checks pass. No first webhook is required; use Reconcile.

Manual controls

ActionPermissionEffect
ReconcilewriteInitialize or re-scan.
DequeuewriteRemove queue and urgent from one PR. Cannot cancel an issued squash.
UrgentwriteMove a queued PR to front and preempt active candidate.
PausewriteNo new candidates, no merges. Queued PRs keep their place.
FreezewriteCandidates still verified; nothing merged.
ResumeadminRelease a fail-closed safety pause after investigation.

Manual pause and freeze are independent of safety pauses. A safety pause is caused by post-merge mismatch or critical command failure; it requires investigation and cannot be cleared by the manual resume button alone.

Security headers

Every page and asset response carries CSP, nosniff, and referrer headers. The Worker serves assets through the ASSETS binding with run_worker_first = true so these headers are attached even when Workers Static Assets serves the file. The console loads no external assets; everything is bundled in web/.

Source map

ConcernFile
Dashboard servicecrates/engine/src/dashboard/service.rs
Build identitycrates/engine/src/build_info.rs (VERSION, GIT_COMMIT)
Routingcrates/engine/src/dashboard/route.rs
Policy / permissionscrates/engine/src/dashboard/policy.rs
Setup checkscrates/engine/src/dashboard/setup.rs
Static assetsweb/
Cloudflare dashboard integrationruntimes/cloudflare/src/dashboard/
Native dashboard integrationruntimes/native/src/dashboard.rs

Migrate from Mergify

This guide maps a Mergify merge-queue setup to MergeSpan v0.1. It is intentionally conservative: only behavior that exists in MergeSpan is mapped as an equivalent. Everything else is marked not supported and must stay in GitHub branch protection, rulesets, or CI rather than being translated into a queue feature that does not exist.

Installing the App on the repository is the cutover. MergeSpan has no separate enable switch: installation starts queue processing. Do not install it while Mergify is still merging. Prepare the verification workflow, labels, and rulesets first, drain Mergify, and clear its labels. A repository with no .github/mergespan.toml and no queue labels is not a safe staging state: fileless MergeSpan infers defaults and starts from the active base rulesets as soon as it is installed.

Do not run both queues at once. Mergify and MergeSpan both react to labels and merge pull requests. If both are active on the same base branch, either can merge a pull request the other is verifying. Disable one before enabling the other.

What maps directly

Mergify conceptMergeSpan equivalentNotes
One queue for a base branchOptional .github/mergespan.toml with basev0.1 supports one base branch (bootstrapped from main). Without the file, the base is inferred as main.
Queue entry label / conditionqueue_label (default queue)MergeSpan uses a label, not a condition expression. Fileless setups use queue.
merge_method: squashAlways squashv0.1 has no merge-method setting.
Required checks after the PR is up to daterequired_checks, or inferred from active base rulesetsExact GitHub Actions check names on candidate C. Without a config file, MergeSpan takes the required status check contexts from the active rulesets on main, excluding its own mergespan gate.
Queue priority via labelurgent_label (default urgent)Only a binary urgent label; no priority rule engine. Fileless setups use urgent.
Queue timeouttimeout_minutesApplies to candidate validation, not queue wait. Fileless default is 60 minutes.
Branch protection / ruleset check injectionManual rulesetsMergeSpan does not inject rules; configure rulesets yourself. Fileless inference reads rulesets only, not classic branch protection.

Optional explicit translation

The .github/mergespan.toml file is optional. If the default base, labels, timeout, and the base ruleset’s candidate checks are what you want, skip the file; MergeSpan infers them.

Add the file when you need a custom label, timeout, or explicit check list, or when you want the required checks pinned independently of the ruleset. An explicit file always wins over inference. If the file exists but is invalid, MergeSpan halts; it does not fall back.

# .mergify.yml (illustrative)
queue_rules:
  - name: default
    queue_conditions:
      - base = main
      - label = queue
    merge_conditions:
      - check-success = ci
    merge_method: squash

becomes this explicit override, if you need one:

# .github/mergespan.toml
base = "main"
queue_label = "queue"
urgent_label = "urgent"
required_checks = ["ci"]
timeout_minutes = 60
same_repo_only = true

The merge_method: squash line has no equivalent because squash is the only method. Do not copy queue_conditions expressions; only the label maps. Reviews, file-path conditions, author conditions, and other expressions do not map.

What does not map (v0.1)

Mergify featureStatus in MergeSpan v0.1What to do instead
Multiple queue_rules per repositoryNot supportedUse one repository/base per queue, or split repositories.
Multiple target bases in one installationNot supportedOne queue per repository/base.
Batching (batch_size, merge batches)Not supportedMergeSpan verifies one PR at a time.
Parallel/speculative checksNot supportedSerial verification only.
merge_method: merge, rebase, fast-forward, merge-batchNot supportedSquash only.
priority_rules / rich priority expressionsNot supportedOnly the urgent label, applied manually.
auto_merge_conditionsNot supportedAdd the queue label (manually, via @mergespan queue, or via your own workflow).
pull_request_rules actions (comment, label, close, rebase, update, delete_head_branch, etc.)Not supportedKeep equivalent GitHub Actions or branch protection. MergeSpan does not run a general rule engine.
merge_protections / custom merge protectionsNot supportedEncode requirements as required checks or ruleset rules.
commands_restrictionsNot supportedComment commands require repository write access; there is no per-user allowlist.
Fork pull request queueingNot supported (runtime requires same_repo_only = true)Fork PRs stay out of the queue.
Queue branch prefix customizationNot supportedFixed mergespan/queue/<number>.
Mergify dashboard analytics / wait-time historyPartialMergeSpan has an event timeline and statistics view, not a migration of Mergify data.

Mergify’s public documentation describes queue rules, batching, and merge methods in Using Queue Rules and Merge Strategies. Use those pages when auditing which of your existing features have no MergeSpan equivalent.

Which old guards and bypass actors to retire

Mergify’s recommended setup asks for a bypass actor with the exempt mode on every ruleset that applies to the base or queue branches, because some merge methods update the base branch directly. MergeSpan does not need that bypass:

  • Base branch ruleset: no bypass actors. MergeSpan merges through the pull request API with the App’s mergespan check; a human or another App must not bypass the required check.
  • mergespan/queue/** ruleset: restrict creations, updates, and deletions to the MergeSpan App. This is an ownership restriction on temporary branches, not a bypass on the base branch.
  • Remove Mergify’s bypass actor from every ruleset where it was added. If you keep Mergify installed for rollback, disable its queue behavior; do not leave its bypass active while MergeSpan is the queue.
  • Retire guard workflows whose only job is to emulate queue serialization or to gate merges for Mergify. If a workflow performs real validation, keep it and list its check name in required_checks (or require it on the base ruleset so inference picks it up). If it only waits on a queue label/comment or posts a duplicate status, remove it after MergeSpan is live.
  • Turn off “Require branches to be up to date before merging” on the base branch. MergeSpan validates the candidate itself; strict mode would invalidate the PR head whenever the base moves.
  • Stop using auto-merge for these pull requests. gh pr merge --auto bypasses MergeSpan’s candidate check. This is an operational rule, not a repository setting MergeSpan can enforce.

Migration sequence

  1. Inventory .mergify.yml:
    • every queue_rules entry,
    • every merge_method,
    • batch_size / parallel settings,
    • priority_rules,
    • pull_request_rules that queue or merge,
    • merge_protections.
  2. Decide what MergeSpan can own. Keep only one queue rule’s label and checks. Move every condition MergeSpan cannot express into branch protection, rulesets, or CI.
  3. Prepare the repository before installing MergeSpan:
    • Add the verification workflow to the base branch. It must run on push to mergespan/queue/** with github.event.created == false; see Configuration → Verification workflow requirements.
    • Create the labels you will use (default queue and urgent), or confirm they exist with the exact names.
    • Prepare the base branch ruleset: require a pull request, allow squash only, leave strict up-to-date off, and use no bypass actors. Require each candidate check by its exact name. These required status check contexts are the fileless required_checks; the mergespan gate is excluded.
    • Prepare the mergespan/queue/** ruleset: restrict creations, updates, and deletions to the MergeSpan App; no human bypass.
    • Optionally add .github/mergespan.toml with the verified labels, checks, and same_repo_only = true, then merge it to the base branch. If you skip the file, inference uses base main and the ruleset contexts.
    • Merge all of this to the base branch. These are pushes while Mergify may still be watching; ensure its queue behavior is disabled or cannot enqueue the preparatory changes.
  4. Drain and stop Mergify before installation:
    • Disable automatic queueing / remove queue_rules from the active Mergify config, or disable the Mergify app for this repository.
    • Wait until no Mergify queue entry is active; if a merge is in flight, let it settle.
    • Remove both configured labels (queue and urgent, or your custom names) from every open pull request so MergeSpan cannot pick them up at installation.
  5. Install MergeSpan and cut over:
    • Install the App on the repository with the permissions and events in GitHub App. This installation is the enable action.
    • Add or confirm the base ruleset’s required mergespan check scoped to the MergeSpan App. If it was already added in step 3, confirm it is the MergeSpan App’s check.
    • A fileless install is supported and uses the inferred configuration from step 3. It is not a “dry run”: do not install with Mergify still active or with queue labels left behind.
  6. Initialize and verify setup: from the Console, click Reconcile so the repository initializes without waiting for a webhook. Setup must show either the explicit configuration or the inferred configuration with its source and exact required checks. If it shows an inference failure, fix the named ruleset/check and recheck; do not add a file blindly. Verify config_loaded before labeling anything.
  7. Verify with one non-draft pull request:
    • add the configured queue label (default queue);
    • expect a mergespan check, mergespan/queue/<n>, checks on C, squash merge, branch deletion;
    • check the console event timeline.
  8. Retire the old guards and bypass actors listed above only after step 7 succeeds and no MergeSpan candidate branches remain.
  9. Rollback plan ready (next section) before you rely on the queue for critical merges.

Safe rollback to Mergify

If MergeSpan misbehaves, roll back without leaving two queues active:

  1. Stop MergeSpan processing first: pause MergeSpan in the console (no new candidates, no merges). Do not delete the runtime state or candidate branches; they are the recovery source.
  2. Clear MergeSpan state before resuming Mergify:
    • settle any in-flight squash (wait for it to complete or fail; do not start Mergify on the same PR);
    • explicitly dequeue any parked candidate (@mergespan dequeue or remove queue/urgent manually);
    • verify the queue is stopped and labels are cleared in the console;
    • only then resume the old queue (enable Mergify’s previous configuration, including its bypass actor if your rulesets require it).
  3. Remove queue labels only from pull requests you are handing back. Do not remove labels from a pull request whose squash is already in flight; wait for the merge to settle.
  4. Confirm no MergeSpan candidate is active in the console. If one is verifying, either let it finish or pause and wait; do not start Mergify on the same PR.
  5. Re-enable Mergify with its previous configuration, including its bypass actor if your rulesets require it.
  6. Remove MergeSpan’s required check from the base branch ruleset and remove the mergespan/queue/** ownership rule only after no candidate branches remain. Keeping the ruleset while MergeSpan is paused is harmless; removing it too early lets other actors write to queue branches.
  7. Keep MergeSpan installed but paused during the observation window. Re-enabling it later requires only unpausing; reinitializing is not required because the durable state remains. Uninstalling the App is a cutover, not a pause: it stops observation, so clear queue labels before doing it.
  8. Do not reinstall the App or delete the database as a diagnostic. The database, labels, and branches are the recovery source.

Rollback limits

  • A squash merge already issued cannot be cancelled by dequeue or by pausing. Check the pull request state before switching queues.
  • MergeSpan does not migrate Mergify history, analytics, or queue positions.
  • If you remove the mergespan required check while candidate branches still exist, GitHub may allow a human to merge a pull request that MergeSpan was verifying. Remove the check only after the pause is observed and no candidate is active.
  • If Mergify’s old bypass actor is restored, make sure the base branch’s required mergespan check is removed first; otherwise Mergify may be blocked by a check only MergeSpan satisfies.

References

Comparison

This page compares MergeSpan v0.1 with Mergify and GitHub’s native merge queue. It is written for readers evaluating the options, not for marketing. Where MergeSpan lacks a feature, it says so.

At a glance

CapabilityMergeSpan v0.1GitHub native merge queueMergify
Squash mergeYes (only method)Yes (merge, rebase, squash)Yes (merge, rebase, squash, fast-forward, merge-batch)
Batched / grouped pull requestsNoYes (merge groups)Yes (configurable batches)
Parallel speculative candidatesNoYes (up to the build-concurrency limit)Yes
Multiple target bases in one configurationNo (one repository/base; bootstraps from main)Per repository/branch setupMultiple queue rules per repository
Priority / urgent handlingBinary urgent label, manualNot a queue featurePriority rules
Two-step / custom CIRepository CI only; no queue-injected workflowmerge_group CI requiredTwo-step CI support
Pause / freeze from a UIYes (console)Repository rules/settingsYes (dashboard, CLI, API)
Fork pull requestsNever queued (same_repo_only = true)Repository settingConfigurable
Self-hostingWorkers, ingress Worker, native systemd/DockerGitHub-hosted onlyCloud SaaS
Hosted offer / install buttonNoBuilt into GitHubCommercial SaaS
Atomic merge guaranteeNoNo atomic compare-and-swap eitherNot claimed here

MergeSpan v0.1 in detail

MergeSpan is deliberately narrower than both alternatives:

  • One queue per repository and base branch. v0.1 bootstraps from main and requires the configuration’s base to match at initialization. Multiple target bases in one installation are not supported.
  • Squash only. There is no merge-method option. Merge commits, rebase merges, fast-forward merges, and batch merges are not implemented.
  • No batching. Each queued pull request is verified alone on its candidate SHA. There is no grouping of multiple pull requests into one candidate or one CI run.
  • No fork pull requests. The runtime refuses any configuration with same_repo_only unset or false, so only same-repository heads are admitted.
  • No speculative parallel checks. The queue serializes: one active candidate at a time. This trades throughput for simplicity and predictable resource use on small queues.
  • No general rule engine. Labels and comment commands are the only triggers. There are no pull_request_rules, path filters, author conditions, review requirements, or merge-protection expressions.
  • Not atomic. GitHub’s merge API does not provide compare-and-swap on the base branch. MergeSpan re-reads the PR, base, and candidate immediately before merging, then reconciles the squash commit’s parent and tree. A concurrent merge can still land first; reconciliation detects and pauses on the mismatch.
  • No hosted service. MergeSpan is self-hosted. There is no install button and no hosted queue to sign up for.
  • Console is read-mostly. It offers Reconcile, dequeue, urgent, pause, freeze, and resume. It is not a general dashboard for repository automation.

What MergeSpan does well

  • Exact candidate checks. Required checks must be GitHub Actions runs with the exact candidate SHA and Success conclusion. It does not accept neutral, skipped, or stale results.
  • Read-before-write recovery. Candidate creation, merge, and cleanup start with fresh reads; an interrupted squash is recovered read-first and never retried as a blind PUT.
  • Fail-closed pauses. A post-merge parent/tree mismatch pauses the queue and comments; it is never reported as success.
  • Low operational surface. One SQLite database per repository, no external database, no queue analytics pipeline, no paid observability requirement.
  • No external assets. The console bundles all JS/CSS; it does not load third-party scripts or fonts.

What MergeSpan deliberately does not claim

  • It does not claim atomicity or a CAS primitive.
  • It does not claim to replace Mergify’s rule engine, batching, or multi-repository workflows.
  • It does not claim a hosted service or a one-click install.
  • It does not claim performance numbers in v0.1. The sandbox record contains measurements for the ingress Worker only, not a general throughput benchmark.

GitHub’s native merge queue

GitHub’s native merge queue is built into repository settings and rulesets. It supports merge groups, configurable merge methods (merge, rebase, squash), build concurrency, and “only merge non-failing pull requests” behavior. It requires CI workflows to trigger on merge_group, and it cannot be enabled with branch protection patterns that use wildcard characters.

See GitHub’s official documentation:

MergeSpan differs in that it is an App and can run on self-hosted infrastructure, but it gives up batching, multiple merge methods, and multiple base branches.

Mergify

Mergify is a commercial merge-queue and automation service. Its queue supports queue rules, merge methods, batching, priority rules, two-step CI, and parallel checks. It also has a general rule engine for pull-request automation. These capabilities come with a hosted service and configuration surface that MergeSpan v0.1 does not replicate.

See Mergify’s official documentation:

MergeSpan’s migration guide describes which Mergify concepts map and which must remain in GitHub branch protection or CI: Migrate from Mergify.

When to choose what

SituationFit
You need a self-hosted queue with exact candidate checks and a small serial workloadMergeSpan v0.1
You need batches, multiple merge methods, or multi-branch queuesGitHub native or Mergify
You need fork pull requests in the queueGitHub native or Mergify (MergeSpan never queues forks)
You need a hosted queue with priority rules and analyticsMergify or GitHub native
You need to avoid a hosted dependency and can run Workers or a Linux processMergeSpan v0.1
You need atomic merge semanticsNone of the three provide a base compare-and-swap; verify behavior with your own integration test

Official sources

Versions and Upgrades

Release status

Check the tags page and the releases page for the current list, or run git ls-remote --tags origin and gh release list --limit 100. Until a release tag exists, non-production deployments may pin a specific commit SHA and record the version and commit reported by the console diagnostics page. Both mergespan-prod and mergespan-prod-ingress must wait for a stable release tag, never an RC. The tag-driven release workflow is present on main; the first published tag will be the first release. This tree’s workspace version is 0.1.0; a release tag for this tree is v0.1.0, and its release candidates are v0.1.0-rc.1, v0.1.0-rc.2, and so on.

This documentation describes the code at main. It does not invent version numbers or release dates beyond the workspace version checked into this tree.

Version and build identity

The release version has one source of truth: [workspace.package] version in the root Cargo.toml. Every crate and runtime inherits it with version.workspace = true, so the native binary, Worker and dashboard report the same version. Diagnostics also report the full Git commit compiled into the build.

crates/engine/build.rs resolves the repository’s actual HEAD at compile time and embeds the full commit; crates/engine/src/build_info.rs exposes it as GIT_COMMIT and the workspace version as VERSION. The commit is unknown when the workspace is not the Git top-level or has no Git metadata. Both the native runtime and the Worker depend on this crate, so one build script gives both artifacts the same identity. GET /health remains a liveness-only response and does not carry version or commit data.

Release procedure

  1. Change [workspace.package] version with a normal pull request. Use a 0.x minor bump for any breaking Durable Object storage or configuration-format change. Run cargo check --workspace without --locked to refresh Cargo.lock, review the lockfile diff to confirm only workspace package versions changed, then commit the updated lockfile with the pull request.

  2. Merge the pull request to main with the repository’s squash-merge policy.

  3. Create and push the release candidate from a clean local main that contains the squash commit:

    git fetch origin --tags
    git switch main
    git pull --ff-only origin main
    git tag -a vX.Y.Z-rc.1 -m "MergeSpan vX.Y.Z-rc.1"
    git push origin vX.Y.Z-rc.1
    

    The workspace version stays the plain X.Y.Z; the -rc.N marker lives only in the Git tag, the release name and the release evidence. Lightweight tags are peeled correctly, but an annotated tag is the repository convention. The peeled commit must be on origin/main.

  4. Wait for the release workflow to build and publish the RC as a GitHub prerelease. An RC is never deployed to mergespan-prod or mergespan-prod-ingress. Fix forward with rc.N+1; do not move or delete an RC tag that has been pushed.

  5. After the RC is published and tested, tag the same squash commit for the stable release:

    git tag -a vX.Y.Z -m "MergeSpan vX.Y.Z"
    git push origin vX.Y.Z
    

    The stable tag does not rebuild. It promotes the original RC assets after resolving the unique successful RC tag-push run for that commit.

  6. The tag push runs .github/workflows/release.yml. It never deploys anything and never changes repository settings, rulesets, secrets, runners or Workers.

Release candidates

A release candidate is vX.Y.Z-rc.N. The workspace version stays the plain X.Y.Z, so an RC and its stable release are built from the same source version and carry the same six asset names (mergespan-linux-amd64, mergespan-linux-arm64, mergespan-worker-X.Y.Z.tar.gz, and one .sha256 each). The RC number never changes the artifact names or the version compiled into the binary.

The tag checker understands both forms and reports channel (stable or rc), prerelease (true/false), and rc_number for an RC. It fails closed on an RC tag unless the caller sets RELEASE_ALLOW_RC=1; the release workflow sets it only for a pushed RC and a read-only dispatch validation of an existing RC tag. The stable path never receives it.

An RC tag push runs:

  1. the same shared ci-build checks as the required CI job, with release caches disabled;
  2. A’s explicit long invariant suite, cargo test --locked -p mergespan-engine --lib full_ci -- --ignored;
  3. the native checkpoint restart smoke against the freshly built dist/mergespan-linux-* binary that matches the Linux runner architecture;
  4. the Worker checkpoint restart smoke against the freshly built dist/mergespan-worker-X.Y.Z.tar.gz with pinned Miniflare;
  5. when a previous stable release exists, the real old-asset continuation: the published previous release’s matching Linux binary seeds a checkpoint and the RC binary continues it, and the previous Worker package seeds Durable Object SQLite state that the RC package reads. The same run must have passed the long Full CI A suite before the upgrade artifact may claim I1-I4. If the previous asset is missing, cannot run, or the evidence is absent, the upgrade gate is BLOCKED; it is never reported as a pass. The Worker smoke itself prints I3/I4 as BLOCKED for its harness; those invariants come from A’s suite, not from that smoke.

The RC then writes release-evidence.json and its independent .sha256, uploads them with 7-day retention, verifies the six original assets again, and publishes the tag as a prerelease with gh release create --verify-tag --generate-notes --prerelease --latest=false only after every gate succeeds.

Stable promotion

A stable tag vX.Y.Z requires exactly one successful, published, same-commit RC. There is no stable rebuild and no first-release exception: SKIP(no previous stable) only skips the historical upgrade proof, not the RC requirement. The stable path:

  1. queries the complete paginated release list and resolves the unique successful .github/workflows/release.yml tag-push run for the stable commit whose head_branch is vX.Y.Z-rc.N; multiple matching RC runs, a dispatch run, an expired run, a failed run, or a missing published prerelease is BLOCKED;
  2. downloads that run’s original release-bundle and release-evidence artifacts for the exact attempt, verifying each archive’s SHA-256 against the Actions artifact API (the release page checksums are never a trust source);
  3. verifies the evidence digest, the exact repository/workflow/run/attempt/ commit/tag metadata, the 7-day retention window, the six-file set and every asset byte, and—when a previous stable exists—the upgrade evidence from the same RC run;
  4. copies those unchanged six files into the stable publish directory and re-runs the six-asset structural verification without building;
  5. refreshes origin with the job token and re-reads the stable tag immediately before publishing, requiring it to still peel to the stable commit and remain on origin/main;
  6. publishes those exact bytes with gh release create --verify-tag --generate-notes --title vX.Y.Z.

A missing or ambiguous RC, a wrong commit, a fork/other workflow, a failed or expired run, an artifact digest mismatch, a moved tag, a non-qualified manifest, or a configured previous stable without real upgrade evidence all fail closed. A missing previous-stable continuation is BLOCKED, never green.

Published tags are immutable by policy: never move or delete a vX.Y.Z tag after it is published. The close-to-publish refresh is a best-effort check, not an atomic tag lock. If a tag was moved or deleted, or a release must be retried after its assets were published, publish a new version and tag; do not reuse the old one. Re-running the workflow for an unchanged tag is only for a failed run before publication.

Manual dispatch, branch validation and runner trust

Manual dispatch has two read-only modes. Neither has contents: write; neither creates a tag, a release or any other remote write. Dispatch is accepted only from the repository default branch (main) and the exact same-repository branch ci/full-ci-c, both pinned by the workflow only. A dispatch validation runs no secrets, no publish/tag job and no write token, and its evidence carries provenance: dispatch-validation / event: workflow_dispatch, so it is never accepted as stable or RC release provenance.

# A: no-tag validation from the approved CI branch (dry-run evidence)
gh workflow run release.yml --ref ci/full-ci-c -f mode=build -f run_attempt=1

# A: no-tag validation from main (same read-only mode)
gh workflow run release.yml --ref main -f mode=build

# A: validate an existing RC tag without publishing it
gh workflow run release.yml --ref main -f mode=build -f tag=vX.Y.Z-rc.1

# B: validate an earlier no-tag run by its explicit run id/attempt.
#    No tag input: this mode never names or creates a release.
#    The expected source commit is this dispatch run's own github.sha, so run
#    B from the same commit that produced run A.
gh workflow run release.yml --ref ci/full-ci-c -f mode=promote \
  -f run_id=123456789 -f run_attempt=1

The no-tag build runs the full shared checks, A’s long suite, both runtime smokes + packaging, writes channel: dry-run / provenance: dry-run evidence and uploads the bundle and evidence. The RC-tag build is validation-only for evidence purposes. The promote mode downloads the earlier run’s artifacts for the exact attempt, verifies the Actions artifact ZIP digests, the independent evidence digest, the manifest, the six assets’ bytes, the complete release history and (when a previous stable exists) the upgrade gate. It expects the current dispatch/checkout commit (github.sha of the promote run), the same repository/workflow/event/branch, and the 7-day retention window; a run that names any other source SHA is rejected. It never builds, publishes or creates a release. Its success does not authorize a stable release.

No-tag dispatch evidence never qualifies for a real publish: the RC publish re-verifies with --require-push and the stable path requires a published RC tag-push run. Do not pass tag in promote mode. A same-repository pull-request dry run remains a safe subset: it never publishes, does not run release-only gates, and does not use release build caches. Fork pull requests are excluded from the release workflow.

Runner and publishable-bytes prerequisite. Caches are disabled for a release/RC build (cache: false), and the build puts its Rust output, worker-build binary and downloaded tools in a job-local directory so it cannot reuse a pre-existing worker-build or target from a shared writable HOME or the workspace. Normal CI keeps its existing cache behavior.

Disk use of the uncached build. The isolated path is also the long path: shared checks, A’s long suite, both native musl builds, Worker packaging and both restart smokes run in one job. It therefore does not retain intermediates past their consumer. In this job-local tree only, cargo incremental state is off and the dev/test profile carries no debug info (nothing reads it; the installed binaries and staged dist/ assets are the outputs), each worker-build phase compiles into its own target directory, and .github/scripts/reap-job-target.sh removes only those generated target directories once their consumer has finished (each native cross-target tree as its binary is staged into dist/, the Worker target and downloaded tools after build/ is written, and the debug/test target after the long suite). The script is inert unless CARGO_TARGET_DIR is exactly this run’s generated $RUNNER_TEMP/release-tools-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT/target, so cached PR CI keeps its workspace target and Actions caches unchanged. If an uncached attempt still fails with ENOSPC, the job prints df/du headroom before Worker packaging so a runner-capacity limit is distinguishable from job-tree growth; raising a disk limit or switching runners is an operator action, not a workflow fix.

All jobs run on the fixed GitHub-hosted ubuntu-24.04 runner. A tag-push release no longer requires a dedicated clean runner; the build and both publish jobs all use that same hosted runner. A no-tag run has no publish privileges and its output is not publishable evidence.

Old-release continuation. When a previous stable exists, the upgrade step downloads the exact baseline filenames derived from that tag’s plain X.Y.Z version (mergespan-linux-<arch>, its .sha256, mergespan-worker-X.Y.Z.tar.gz, its .sha256) and verifies each exact checksum before executing or opening the file. It never uses a glob or a sidecar for another file. The same-asset restart continuation still runs. The upgrade artifact records A’s long-suite result as i1..i4 and the real runtime result as runtime_i1..runtime_i4; A’s green suite alone is never reported as PROVEN when the real runtime harness only has I1/I2 (I3/I4 remain BLOCKED for the Worker smoke). An absent old asset, a failed checksum, a failed continuation or partial runtime proof is BLOCKED, never green.

The workflow must be on the default main branch before its dispatch entry is generally available; the approved branch is additionally allowed by the workflow’s exact allowlist and is never a release source.

Release artifacts and verification

Release assets are exactly six files, and an RC uses the same names as its stable release (<version> is always the plain workspace X.Y.Z):

  • mergespan-linux-amd64 and mergespan-linux-arm64 — static ELF64 binaries.
  • mergespan-worker-<version>.tar.gz — the built Worker package.
  • one .sha256 file for each of the three artifacts.

Choose the Worker tarball for Cloudflare and the matching mergespan-linux-* binary for a native systemd or Docker deployment. The three artifacts and their checksums are the complete release asset set.

release-evidence.json and its .sha256 are workflow artifacts used to qualify the release; they are not release assets, so the six-name rule does not change.

The Worker package contains build/index.js, build/index_bg.wasm, build/package.json, build/worker/shim.mjs, the complete web/ dashboard asset directory, a README.md, and a generated wrangler.toml copied from runtimes/cloudflare/wrangler.toml with its [build] table removed and [assets] directory set to web. It is a deployment artifact, not a source tree: it has no crates/, runtimes/, Cargo.toml, Cargo.lock or CI files. Extract it and deploy it with the pinned Wrangler CLI; do not run cargo or worker-build inside it.

The release workflow verifies the published artifact set before publishing:

  • The asset set is exactly the six names above, with no extras, and every file is non-empty.
  • Each .sha256 file names its matching artifact and passes sha256sum -c --strict.
  • Both Linux binaries are ELF64 and contain no PT_INTERP or DT_NEEDED entries.
  • The Worker archive contains the required build and web files, has no source-tree directories or files, and its wrangler.toml has the correct entry point, assets directory, and no [build] command.
  • The validated full commit is embedded in both Linux binaries, the Worker wasm, and the package README.md.

The native binaries are the same artifacts used by systemd or the distroless Dockerfile in deploy/README.md. After downloading an asset set, verify it with the matching .sha256 files before deploying.

Release evidence

Two independent records bind a set of assets to the exact run and commit that produced it:

  • release-evidence.json, a canonical manifest written by .github/scripts/release-evidence.py from the release build; and
  • release-evidence.json.sha256, the independent digest of that manifest.

Runtime checks such as .github/scripts/checkpoint-smoke.sh prove behaviour; they do not prove provenance and are not release evidence.

The manifest is deliberately not a signature. Trust comes from cross-checking it against the Actions run metadata fetched from this repository’s API, and from the independent digest:

{
  "schema": 3,
  "repository": "owner/repo",
  "workflow_path": ".github/workflows/release.yml",
  "run_id": 123,
  "run_attempt": 1,
  "event": "push",
  "tag": "v0.1.0-rc.1",
  "version": "0.1.0",
  "channel": "rc",
  "commit": "<40 or 64 lowercase hex>",
  "generated_at": "2026-12-02T12:00:00Z",
  "assets": {
    "mergespan-linux-amd64": "<sha256>",
    "mergespan-linux-amd64.sha256": "<sha256>",
    "mergespan-linux-arm64": "<sha256>",
    "mergespan-linux-arm64.sha256": "<sha256>",
    "mergespan-worker-0.1.0.tar.gz": "<sha256>",
    "mergespan-worker-0.1.0.tar.gz.sha256": "<sha256>"
  },
  "qualification": {
    "long_tests": true,
    "native_checkpoint": true,
    "worker_checkpoint": true
  },
  "provenance": "tag-push",
  "head_branch": "v0.1.0-rc.1"
}

A real release may only consume a manifest whose:

  • repository, workflow path, run ID, run attempt, conclusion and event match a completed successful run of the designated .github/workflows/release.yml;
  • push run’s tag, head commit and head_branch match the release; a workflow_dispatch manifest carries provenance: dispatch-validation and is a validation source only, never promotion evidence;
  • commit equals the full commit being released (40 or 64 lowercase hex);
  • all three qualification flags are true for a published RC/stable asset set;
  • six-asset map, independent digest, per-asset checksum files and the actual asset bytes all agree;
  • timestamps are inside the Actions retention window (7 days by default);
  • the provenance value is consistent with the event and branch (a tag-push manifest whose provenance is dispatch, or the reverse, is rejected).

Anything else is rejected: wrong commit, wrong event, a different/fork workflow, a failed run, an older run, a digest mismatch, extra or missing assets, corrupt bytes, a malformed tag, or a release query that failed. A no-tag workflow_dispatch runs the same dry-run validation but is never eligible for a real release.

A stable tag is verified with the promotion subcommand, not verify. It requires the unique successful same-commit RC tag-push run, a published prerelease for that RC, the exact attempt’s original artifacts, a manifest digest, the independent Actions artifact digest for both the bundle and the evidence archive, the six byte-identical assets, and—when a previous stable exists—upgrade evidence produced by that same RC run. verify remains the audit command for a completed run’s own evidence and rejects stable tags. Stable tags never rebuild: the exact RC bytes are copied and published.

Upgrade evidence

upgrade-evidence.json and its .sha256 are separate from the release manifest. They bind:

  • the previous published stable tag;
  • the candidate version and commit;
  • native_resume and worker_resume (real old-asset continuation);
  • i1, i2, i3, i4 (A’s long invariant suite at the candidate commit);
  • runtime_i1 through runtime_i4, the real runtime harness result. The Worker smoke currently proves runtime I1/I2 only and reports I3/I4 BLOCKED, so a normal RC upgrade artifact stays BLOCKED rather than claiming PROVEN;
  • the exact source run and attempt that produced the evidence, and a 7-day timestamp.

The RC build downloads the previous release, verifies its published transport checksums, and runs the real previous binary/Worker package as the seed and the RC asset as the continuation. If the previous asset is missing, cannot run, or the long suite did not run in that same attempt, the result is BLOCKED, never a pass. A first stable release has no previous stable, so only this historical proof is skipped; the same-commit RC requirement still applies.

Dispatch and Full CI B

The two manual-dispatch modes (build/evidence and promote with an explicit RC run id) are read-only. They have no contents: write, cannot tag, cannot create a release, and their workflow_dispatch evidence is never accepted as stable promotion provenance. Build without a tag produces channel: dry-run evidence; build with an RC tag is a validation source only; promote stops before publishing.

Full CI B (the sandbox E2E trial) is shared development information. It is not a required check, not release evidence, and never authorizes an RC or stable publication. The release gate consumes only the release evidence and upgrade evidence described above.

.github/scripts/release-evidence.test.sh and .github/scripts/fetch-release-artifacts.test.sh exercise every accept/reject case with synthetic fixtures; they create no tag, call no GitHub API and change no release. .github/scripts/checkpoint-smoke.sh, .github/scripts/worker-checkpoint-smoke.mjs and .github/scripts/upgrade-smoke.sh prove runtime continuation separately and are not provenance evidence.

Workflow wiring

The workflow is wired as one source of truth:

  • validate checks the tag/version, runs all release helper tests, queries the complete release list, and chooses the mode. Tag pushes and RC validation require vX.Y.Z / vX.Y.Z-rc.N to match the plain workspace version and be on origin/main.
  • build runs the shared ci-build action with cache: false, A’s ignored long suite when not a pull request, packages the six assets, runs the native and Worker checkpoint smokes on those assets, writes and uploads the release evidence, and (after a previous stable) writes the upgrade evidence. The upgrade artifact is only green when the same attempt ran the long suite and the real old assets continued successfully.
  • verify checks the uploaded six assets and the release evidence, qualifying the bundle against the asset bytes and the run’s own evidence.
  • publish-rc re-verifies the assets and qualification, refuses an existing release, re-fetches and re-reads the RC tag immediately before publishing, enforces the upgrade gate from the current run when a previous stable exists, and creates a prerelease with --latest=false.
  • publish-stable does no build. It resolves the unique same-commit published RC, downloads the original artifacts for the exact attempt with API digest verification, validates the six assets and the upgrade evidence, copies the bytes, re-reads the stable tag immediately before publishing, and publishes only those exact files.
  • promote-check performs the same stable promotion validation with an explicit run id but no contents write and no publication.

The ci job name, trigger, runner, permissions and required-check behavior are unchanged; release-only work lives in release.yml.

Deploy a tagged release (Worker)

The two Wrangler configurations each define a default and a production Worker:

DirectoryDefault (top level)Production (-e production)
runtimes/cloudflaremergespanmergespan-prod
runtimes/cloudflare-ingressmergespan-ingressmergespan-prod-ingress, bound to mergespan-prod

The default Workers follow main. Deploy them from a normal main branch with a plain wrangler deploy. Only the production Workers are release targets, and they are deployed only from a tagged vX.Y.Z commit, never from main and never from an untagged commit. The production Workers have their own Durable Object namespace and SQLite storage; the first production deploy creates new storage and does not read or migrate the default Worker’s data.

Configure the production bindings before the first production deploy. Do not reuse the default/dev App’s values:

  • Plain vars: set the production GITHUB_APP_ID and, for dashboard login, GITHUB_APP_CLIENT_ID in [env.production.vars] in runtimes/cloudflare/wrangler.toml. They are not secrets. A plain wrangler deploy deletes Worker vars that are not in the configuration, so if you manage these in the Cloudflare dashboard instead, add --keep-vars to every production deploy.

  • Worker secrets, entered at Wrangler prompts:

    cd runtimes/cloudflare
    wrangler secret put GITHUB_APP_PRIVATE_KEY -e production
    wrangler secret put GITHUB_WEBHOOK_SECRET -e production
    wrangler secret put GITHUB_APP_CLIENT_SECRET -e production
    wrangler secret put SESSION_SECRET -e production
    
  • Ingress secret: only GITHUB_WEBHOOK_SECRET, with the same value as mergespan-prod’s webhook secret (not the dev Worker’s):

    cd runtimes/cloudflare-ingress
    wrangler secret put GITHUB_WEBHOOK_SECRET -e production
    

The dashboard-related vars and secrets are optional: without them pages still serve, but auth/API answer 503. The production GitHub App’s callback is https://<mergespan-prod host>/auth/callback; its webhook URL is the production ingress /webhook or, as a fallback, mergespan-prod’s /webhook.

Deploy from a clean tagged worktree so the generated build identity is the tag commit:

git fetch origin --tags
git switch --detach vX.Y.Z

cd runtimes/cloudflare
wrangler deploy -e production --tag vX.Y.Z --message "MergeSpan vX.Y.Z"

# Deploy the ingress only after the production Worker. It has no build step.
cd ../cloudflare-ingress
wrangler deploy -e production --tag vX.Y.Z --message "MergeSpan ingress vX.Y.Z"

Alternatively, extract the verified Worker package (which has no build step) and deploy its production environment. The artifact version is the plain workspace version; unlike the tag, it has no leading v:

tar -xzf mergespan-worker-X.Y.Z.tar.gz
cd mergespan-worker-X.Y.Z

Set the production GITHUB_APP_ID and, for dashboard login, GITHUB_APP_CLIENT_ID in [env.production.vars] in the extracted wrangler.toml (they are plain vars, not secrets). If you set them in the Cloudflare dashboard instead, add --keep-vars to the deploy command so Wrangler does not delete them.

wrangler deploy --dry-run -e production   # validate without uploading
wrangler deploy -e production --tag vX.Y.Z --message "MergeSpan vX.Y.Z"

wrangler deploy selects the target from the checked-in configuration and -e; without -e production it targets the default mergespan Worker. Never omit the environment for a production release. --tag and --message attach Worker Version metadata only; they do not select a Worker, change routing, bypass rules or make wrangler deploy idempotent. The source [build] command still runs worker-build --release from the tagged source; the extracted package has no build command. Verify the pinned CLI supports these flags before relying on them: Wrangler 4.169.1 documents both for wrangler deploy.

For native deployments, replace the binary or rebuild the container using the matching mergespan-linux-* artifact from the same tag.

Storage schema

The durable coordinator state uses an explicit schema version:

#![allow(unused)]
fn main() {
pub const SCHEMA_VERSION: u32 = 1;
}

(crates/engine/src/coordinator.rs)

On load, Coordinator::from_state rejects any checkpoint whose schema field does not equal SCHEMA_VERSION:

#![allow(unused)]
fn main() {
if state.schema != SCHEMA_VERSION {
    return Err(StateError::Schema {
        found: state.schema,
        expected: SCHEMA_VERSION,
    });
}
}

There is no automatic migration between schema versions in v0.1. A future version that bumps SCHEMA_VERSION will need either:

  • a documented manual migration path (export/import), or
  • an in-place migration function added to from_state.

Neither exists today. Upgrading across a schema-version bump without a published migration procedure will make existing checkpoints unreadable. Back up the SQLite database (Worker DO storage or native repos/repo-*.sqlite3) before upgrading.

Same-version restarts and the current v1 storage format are covered by two separate local harnesses. Do not report one as the other:

  • Restart and deduplication smoke: .github/scripts/checkpoint-smoke.sh starts the real native binary on a loopback listener, sends one correctly signed synthetic pull_request webhook, requires the SQLite delivery receipt and persisted coordinator/outbox, then SIGTERMs, restarts the same binary on the same data directory and replays the exact delivery. It requires one receipt, a processed attempt, a surviving checkpoint and a duplicate attempt. It proves restart recovery and delivery deduplication; it does not prove merge-queue invariants I1-I4, which stay in A’s full_ci suite. If a previous artifact cannot be run in the available environment, mark that evidence BLOCKED and do not publish; run it on Linux CI instead of substituting a weaker check.
  • Historical read: crates/engine/tests/fixtures/upgrade/checkpoint-v1.json is a frozen v1 checkpoint. cargo test --locked -p mergespan-engine --lib upgrade and cargo test --locked -p mergespan-runtime-native --test runtime historical_v1_checkpoint prove the current engine and a real native SQLite checkpoint still read it. The fixture is never regenerated; a later schema bump must either keep reading it or add an explicit migration. This tree reads it and rejects any newer schema with StateError::Schema instead of resetting.

NATIVE_BIN=target/debug/mergespan WORKER_TARBALL=dist/mergespan-worker-0.1.0.tar.gz .github/scripts/upgrade-smoke.sh all runs all three cases; without a built Worker tarball the worker case reports BLOCKED. A previous-version check is a subset: point NATIVE_BIN at the earlier release’s mergespan-linux-* artifact and NEXT_BIN at the RC binary, with the same (or a copy of the) data directory. The earlier artifact must be run on Linux (the release binaries are static Linux ELF); a macOS host can only run a locally built debug binary. The WAN-severed, loopback-only environment is the intended one: the smoke signs its own webhook, never requires a GitHub response, and any outbound attempt fails without changing durable state.

Worker checkpoint evidence

.github/scripts/worker-checkpoint-smoke.mjs loads an extracted mergespan-worker-X.Y.Z.tar.gz package in local Miniflare/workerd with a persistent Durable Object SQLite directory and the same RepositoryObject class/repository ID across restarts. It sends a correctly signed synthetic webhook (not /health), uses an outbound adapter that recognizes only local synthetic responses and fails every unrecognized request, and checks:

  • a signed delivery leaves a receipt and pending checkpoint in the DO SQLite database;
  • the same state directory, class and repository ID survive a full Miniflare restart; an exact delivery replay deduplicates without a second receipt;
  • a distinct delivery after restart is still processed;
  • the frozen v1 pre-merge checkpoint (runtimes/cloudflare/tests/fixtures/upgrade/checkpoint-v1-merge.json) resumes the persisted candidate/alarm read-first and issues no second merge PUT;
  • a synthetic merge whose squash tree differs, and one whose parent differs, both pause with post_merge_mismatch instead of reporting success (I1 through the Worker path).

Build the package first (cd runtimes/cloudflare && worker-build --release, then VERSION=X.Y.Z bash .github/scripts/package-worker.sh) and run:

WORKER_TARBALL=dist/mergespan-worker-X.Y.Z.tar.gz \
  .github/scripts/upgrade-smoke.sh worker

MINIFLARE_MODULE can point at an installed miniflare package. The same-package restart/deduplication case and the frozen historical checkpoint case are reported separately. If Miniflare is not available the harness reports BLOCKED; it never substitutes a /health or package-structure check. I3 (convergence after inputs stop) and I4 (specific dequeue reasons) are also reported BLOCKED for this harness because it does not implement a full check/merge state double; those remain covered by A’s full_ci suite, not by this local smoke.

Native runtime startup refusal

The native runtime refuses to start if it finds an unexpected legacy database file outside the per-repository layout:

  • <data-dir>/mergespan.sqlite3 (legacy single-database layout)
  • orphaned SQLite sidecars in repos/ without a matching repository database

It never adopts, overwrites, or migrates these files. This is a deliberate safety measure; see runtimes/native/src/service.rs for the exact checks.

Store migrations (idempotent column additions)

SqlStore::open applies idempotent schema migrations via MIGRATION_COLUMNS (crates/engine/src/store.rs). These are additive column additions only; they do not change semantics or drop data. They run on every open and are safe to re-run.

Upgrade procedure

These steps apply whether you deploy a verified release asset or, for a non-production target, a pinned commit. Because there is no automatic schema migration in v0.1:

  1. Back up the durable state:
    • Cloudflare Worker: export the Durable Object’s SQLite storage or rely on Cloudflare’s backup policy.
    • Native: copy <data-dir>/repos/*.sqlite3 and -wal/-shm files while the process is stopped.
  2. Stop the runtime.
  3. Deploy the new binary, Worker bundle, or verified release asset.
  4. Start the runtime.
  5. Verify with one non-draft pull request and the console diagnostics page. Confirm the reported version and commit match the artifact you deployed.
  6. Keep the backup until you have observed at least one successful merge cycle.

If the new version introduces a SCHEMA_VERSION bump and no migration procedure is documented, do not upgrade. Wait for the migration guide.

Downgrade and rollback

Roll back code by redeploying the previous clean tag:

git switch --detach vA.B.C
cd runtimes/cloudflare
wrangler deploy -e production --tag vA.B.C --message "rollback to MergeSpan vA.B.C"

For the production ingress, run wrangler deploy -e production in runtimes/cloudflare-ingress after the production Worker. Roll back the default mergespan/mergespan-ingress Workers with a plain wrangler deploy from the chosen main commit.

For native deployments, replace the binary or rebuild the container using the earlier mergespan-linux-* artifact. wrangler rollback [version-id] restores a previous Worker version, but neither rollback path reverts Durable Object SQLite storage or a deployed storage migration. MergeSpan state, deduplication records and the outbox stay at the newer format. Check code/storage compatibility before rolling back a release that changed Durable Object storage or configuration formats; restore data separately if the older code cannot read the newer storage.

Downgrading to an older version that expects a lower SCHEMA_VERSION will fail on load with StateError::Schema. There is no downgrade path in v0.1. If you must downgrade across a schema version, restore from backup.

Rolling a stable release back to the exact RC it was qualified from is a code no-op: both tags point at the same commit and therefore the same storage format. Rolling back to an earlier RC/stable is not automatically safe; the current code must still read that checkpoint (historical_v1_checkpoint is the frozen baseline for v1) or you must restore a database backup. Do not deploy an older binary over newer Durable Object or native SQLite state merely because the release tag still exists.

For 0.x releases, treat any breaking Durable Object storage or configuration-format change as a minor bump, and state the incompatibility explicitly in the release notes. --generate-notes derives notes from merged pull request titles and will not explain a storage or configuration incompatibility by itself.

What changes between versions

Across releases, expect changes in these areas to require attention:

  • Configuration keys: the parser uses deny_unknown_fields. Adding a key in a newer version means older versions reject the config. Removing a key means newer versions use the default.
  • App permissions / events: the console setup checks validate against the documented set. A permission change requires updating both the App settings and the documentation.
  • Candidate branch naming: fixed at mergespan/queue/<number>. A change would break rulesets and verification workflows.
  • Check name: fixed at mergespan. A change would break required-check configurations and branch protection.
  • Webhook hint shape: the ingress Worker and Rust ingress share a wire contract. Changes require coordinated updates to both.
  • Console API routes: /api/v1/* routes are versioned by prefix. Breaking changes would require a new major version or a compatibility layer.

Source map

ConcernFile
Workspace versionCargo.toml ([workspace.package] version)
Build identitycrates/engine/build.rs, crates/engine/src/build_info.rs
Schema version constantcrates/engine/src/coordinator.rs (SCHEMA_VERSION)
Schema validation on loadcrates/engine/src/coordinator.rs (Coordinator::from_state)
Store migrationscrates/engine/src/store.rs (MIGRATION_COLUMNS, SqlStore::open)
Native startup refusalruntimes/native/src/service.rs
Release workflow.github/workflows/release.yml
Shared CI/release checks.github/actions/ci-build/action.yml
Tag/version checker.github/scripts/check-release-tag.sh and its test
Release evidence.github/scripts/release-evidence.py and its test; .github/scripts/fetch-release-artifacts.sh and its fixture test
Restart/dedupe smoke.github/scripts/checkpoint-smoke.sh, .github/scripts/upgrade-smoke.sh, .github/scripts/worker-checkpoint-smoke.mjs
Historical v1 checkpointscrates/engine/tests/fixtures/upgrade/checkpoint-v1.json, runtimes/cloudflare/tests/fixtures/upgrade/checkpoint-v1-merge.json
Release helpers.github/scripts/fetch-origin.sh, package-worker.sh, verify-release-assets.sh
Diagnostics build fieldscrates/engine/src/dashboard/service.rs, crates/engine/src/dashboard/model.rs

Sandbox Notes

This page preserves the historical sandbox deployment record that was originally embedded in the project README. It is kept because the exact ordering, App contract, repository configuration, ruleset, and validation steps are still useful when standing up a new sandbox. It is not a hosted-service offer and does not imply a published release.

The original README’s project-status paragraph is obsolete in two respects:

  • v0.1 now has a console Reconcile path that initializes a repository with zero webhook deliveries; the first webhook is no longer mandatory (86ebfc2, “fix(dashboard): let Reconcile initialize a repository”).
  • No standalone product status or hosted offer is claimed here. This page records sandbox scenarios only.

Items originally marked pending T2 / T3 are preserved verbatim for provenance. They were historical verification gates; re-verify before relying on them.

1. Sandbox prerequisites (U1–U3)

IDNeededDone when
U1Cloudflare account (Free) and wrangler loginwrangler whoami shows the account
U2Private sandbox repository bigtomcat6/mergespan-sandboxrepository exists
U3GitHub App named MergeSpan, private key, webhook secret, installed only on the sandbox repositoryinstallation lists only mergespan-sandbox

Do not deploy the Worker, send webhooks, or run a live queue test before all three are true. Never install the App on ModelRouter or on all repositories; the ModelRouter cutover is U6.

2. GitHub App contract

Create the App with:

  • Webhook URL https://<worker-host>/webhook, active, JSON.
  • The same webhook secret that is stored as GITHUB_WEBHOOK_SECRET (section 5).

The Worker exposes:

  • POST /webhook — GitHub webhooks; verifies X-Hub-Signature-256 and deduplicates X-GitHub-Delivery.
  • GET /health — unauthenticated liveness only; returns 200 when the Worker is reachable. Not a readiness or end-to-end test.

Permissions (expected; pending T3 §5.7)

PermissionLevelUse
MetadataReadmandatory
ContentsRead & writecreate candidate branch/commit; squash merge
Pull requestsRead & writeread PR state; merge
IssuesRead & writequeue/urgent labels and PR comments
ChecksRead & writecreate/read the mergespan check run
ActionsRead & writecancel candidate workflow runs
WorkflowsNot requiredT3 §5.5 tested only the candidate/merge path for a PR changing .github/workflows/**; direct workflow writes were not tested

No Administration, Members, or organization permissions.

Events (expected; pending T3 §5.7)

push, pull_request, check_run, check_suite, workflow_run, issue_comment.

issue_comment was added for the @mergespan comment commands (queue, urgent, dequeue, refresh, help). The console setup check app_events treats it as required. A repository with comment commands but no issue_comment subscription will not receive command hints.

3. Sandbox repository

Config — .github/mergespan.toml

base = "main"
queue_label = "queue"
urgent_label = "urgent"
required_checks = [
  "verify / fast (internal Go + locked Bun TUI)",
  "verify / integration (offline full-Core fault/security suite)",
]
timeout_minutes = 60
same_repo_only = true
  • required_checks are exact GitHub Actions check-run names from push suites bound to the candidate branch and SHA. Only completed success counts, not neutral or skipped.
  • This runtime bootstraps from main; its configuration is read from the exact base commit, never from the candidate.
  • same_repo_only = true is required in v0.1 (the parser defaults it to false): only PR heads from this repository are queued; fork heads are not.
  • urgent jumps the queue and interrupts the candidate being verified; the interrupted PR is re-queued.
  • v0.1 supports squash only; there is no merge-method option.

Verification workflow

The verification workflow must run on push to mergespan/queue/**, not only on pull_request. MergeSpan first creates mergespan/queue/<n> at base A and then pushes candidate C as an update to the same ref, so one queue entry produces two pushes. Skip the creation push and keep it out of the candidate run’s concurrency group:

on:
  push:
    branches: ["mergespan/queue/**"]
  pull_request:
    branches: [main]
concurrency:
  # created=true is the branch-creation push A; give it its own group so it
  # cannot cancel the C run for the same ref. A later C push still cancels the
  # older C run.
  group: verify-pr-${{ github.ref }}-${{ github.event.created }}
  cancel-in-progress: true
jobs:
  verify:
    name: verify
    # Push runs only the non-creation candidate push. A pull_request run is
    # allowed only when the PR head is in this repository; comparing the base
    # repository would let fork PRs through.
    if: >-
      (github.event_name == 'push' &&
       github.event.created == false &&
       startsWith(github.ref, 'refs/heads/mergespan/queue/')) ||
      (github.event_name == 'pull_request' &&
       github.event.pull_request.head.repo.full_name == github.repository)
    uses: ./.github/workflows/verify.yml
  • Candidate push C runs (created == false); creation push A is skipped. Only C produces the required check runs.
  • A same-repository PR runs; a fork PR is skipped because its head repository differs. On a pull_request event, github.event.repository.full_name is the base repository, so it cannot make that distinction.
  • The concurrency group keeps a late A run from cancelling C. cancel-in-progress still replaces an obsolete C run when the candidate ref is pushed again.
  • Keep the caller and called job names unchanged: the required names carry the caller prefix, for example verify / fast (...) and verify / integration (...).

Push runs are exempt from the head-repository check: the ref already belongs to this repository, and created == false is the extra gate. The sandbox keeps both triggers; the ModelRouter migration branch uses push only.

Ruleset — sandbox only

main:

  • Require a pull request before merging; allow squash only.
  • Required status check mergespan, source limited to the MergeSpan App.
  • Strict off: leave “Require branches to be up to date before merging” disabled. MergeSpan validates the candidate itself; strict would invalidate the PR head whenever main moves.
  • No bypass actors.

mergespan/queue/**:

  • Restrict creations, updates, and deletions to the MergeSpan App; no human bypass. MergeSpan owns these branches and deletes them after every candidate.

Pending T3 §5.6: the App-issued check must satisfy the required check without bypass, and humans must not be able to merge without it. Do not apply these rulesets to ModelRouter.

4. Deploy on Workers Free

Use only Cloudflare Workers Free with SQLite-backed Durable Objects (new_sqlite_classes, one DO per repository). Do not add paid resources. Pending T2 §4: Free-plan limits and Alarm behavior.

cd runtimes/cloudflare
wrangler login          # U1
wrangler deploy         # [build] runs worker-build --release
curl -fsS "https://<worker-host>/health"

Ingress-only Worker (optional split)

Webhooks can be received by a separate ingress-only Worker. Its Wrangler entry is a zero-npm JavaScript ES module (runtimes/cloudflare-ingress/src/index.mjs) with only GET /health and POST /webhook; there is no build command, npm install, Durable Object class, SQLite store, GitHub orchestration, RSA signing, or dashboard route. The REPOSITORY binding is a cross-script binding to the existing mergespan / RepositoryObject namespace, so it adds no migration, route, or authentication bypass. The Durable Object still owns deduplication, and /internal/notify, status/body-cap behavior are unchanged. See runtimes/cloudflare-ingress/README.md for the exact wire contract and the deliberate JS safe-integer rejection above 2^53 - 1.

The split is used because the Rust/Wasm webhook path exceeded 10 ms CPU on fresh isolates. The JS entry has had no 1102 errors in live runs on Workers Free (max 9.1 ms in the latest 200-delivery run); the measurements and the acceptance rule are in runtimes/cloudflare-ingress/README.md. The sandbox App’s webhook URL points at the ingress Worker. The default Worker keeps serving /webhook as the fallback, so pointing the App back at it is the rollback.

cd runtimes/cloudflare-ingress
wrangler secret put GITHUB_WEBHOOK_SECRET   # same value as the existing Worker
wrangler deploy
curl -fsS "https://<ingress-host>/health"

Only GITHUB_WEBHOOK_SECRET is needed; no App ID or private key. Deploy the existing mergespan Worker first, because the binding targets it. Rollback is to delete the ingress Worker and point the App webhook back at the existing Worker; no data migration is involved.

The DO alarm transport emits one non-secret marker {"event":"installation_token","result":"ok"} only when an App-JWT installation-token response passes the GitHub client’s acceptance checks (see runtimes/cloudflare/src/token_marker.rs and FetchTransport::send in runtimes/cloudflare/src/runtime/orchestration.rs). Failures emit no marker. It is observable with wrangler tail, contains no token/header/body data, and does not enable paid features or change quotas/backstop.

Toolchain:

  • worker-build 0.9.0, pinned: cargo install worker-build --version 0.9.0 --locked.
  • wrangler: Wrangler 4.169.1 was checked locally and wrangler deploy --help documents --tag and --message as Worker Version metadata. The repository does not pin a global Wrangler version; record wrangler --version before deploying and do not upgrade during a release.
  • wasm-bindgen / wasm-opt: follow the versions required by worker-build 0.9.0; pending T2’s build-chain result.
  • GITHUB_APP_ID is a non-secret identifier: set it as a plain [vars] entry in runtimes/cloudflare/wrangler.toml.

4b. Native deployment (systemd / Docker)

The same engine also runs as one native Linux process outside Cloudflare: one locked data directory may hold any number of repositories, each with its own SQLite WAL database under repos/repo-<numeric id>.sqlite3, and a static musl binary for x86_64 or aarch64. Deliveries are routed by the signed numeric repository ID; each queue re-arms independently and an outbound await in one repository does not block ingress or work for another. It exposes only GET /health and POST /webhook; it is HTTP-only, so put a TLS proxy or Cloudflare Tunnel in front of 127.0.0.1:8080 and never expose the listener directly.

Build the static binary (CI builds and verifies both targets):

rustup target add x86_64-unknown-linux-musl aarch64-unknown-linux-musl
cargo zigbuild --locked --release -p mergespan-runtime-native \
  --target x86_64-unknown-linux-musl

Run it on a host:

install -m 0755 target/x86_64-unknown-linux-musl/release/mergespan /usr/local/bin/mergespan
install -D -m 0644 deploy/mergespan.toml /etc/mergespan/mergespan.toml
install -m 0644 deploy/mergespan.service /etc/systemd/system/mergespan.service
# Put the PEM and webhook secret in the two LoadCredential= files, then:
systemctl daemon-reload && systemctl enable --now mergespan
curl -fsS http://127.0.0.1:8080/health

Credential values are read only from files: either the --app-private-key-file / --webhook-secret-file flags or, by default, github-app-private-key and github-webhook-secret inside $CREDENTIALS_DIRECTORY (systemd LoadCredential=). They are never accepted in the environment, config file, command line, or stdout. Diagnostics are one-line redacted JSON.

deploy/ contains the copyable (0BSD) systemd unit, config example, a distroless/static nonroot Dockerfile that copies the same prebuilt binary, and perf-smoke.sh for a separate Linux performance host (idle RSS, health/webhook latency and SIGTERM drain; no publishing). See deploy/README.md for the full procedure.

One deliberate difference from the Worker: when repository_owner/name are configured and a correctly signed delivery arrives for a different repository, the response is 403 instead of the Worker’s 502-for-a-DO-rejection, so GitHub does not retry a routing mismatch this process is configured to refuse. Without that optional binding, any repository the App delivers is served by its own queue.

Operational behavior matches the Worker where it matters: raw X-Hub-Signature-256 verification with a 1 MiB body cap, 202 only after the delivery and signal are committed in one SQLite transaction, deduplication by X-GitHub-Delivery, read-first recovery for an interrupted squash, and an advisory data-directory lock that makes a second live instance fail fast. SIGTERM stops accepting, drains bounded, and leaves a recoverable checkpoint; Restart=on-failure re-arms persisted outbox work.

5. Secrets

Two values are secrets: GITHUB_APP_PRIVATE_KEY and GITHUB_WEBHOOK_SECRET. GITHUB_APP_ID is not a secret.

NameStorage
GITHUB_APP_IDWorker var (plain text)
GITHUB_APP_PRIVATE_KEYWrangler secret
GITHUB_WEBHOOK_SECRETWrangler secret; the same value in the App’s webhook settings
cd runtimes/cloudflare
wrangler secret put GITHUB_APP_PRIVATE_KEY   # paste the full PEM at the prompt
wrangler secret put GITHUB_WEBHOOK_SECRET    # or: ... < /path/outside/repo/secret
  • Input through the prompt or a local file on stdin (< file). Never put a secret on the command line or in shell history, wrangler.toml, the repo, chat, a PR/issue, or logs.
  • Keep secret files outside the repository; do not commit .dev.vars or .env.
  • The PEM must include the BEGIN/END lines and keep its newlines.
  • Enter the same webhook secret in the GitHub App settings; do not send it through chat.
  • wrangler tail is safe only if the implementation does not log secrets, headers, or whole payloads.

6. Security limits and fail-closed behavior

GitHub has no base CAS. The merge API’s sha pins PR head B, not the base branch. There is no atomic compare-and-swap on main. MergeSpan re-reads the PR and main immediately before merging, then reconciles: the squash commit’s parent must be A and its tree must equal candidate C. A concurrent merge can still land first; reconciliation detects the mismatch and pauses that queue. Do not describe the merge as atomic.

Check success is not a lock. Any actor with write/merge permission can merge the PR once the required check is green, and other Apps with checks: write can create check runs. MergeSpan verifies check name, source, exact candidate SHA, and candidate generation before merging, and rejects stale events, but it cannot stop another actor from merging first.

Same-repository code is trusted code. Candidate C contains the repository’s own workflows and scripts, so running it executes repository-controlled code with the job’s credentials and network access. same_repo_only = true blocks fork heads; it does not sandbox same-repository contributors. Only rely on it for repositories whose writers are trusted.

Fail closed. A moved base requires a new candidate; a stale head or ineligible PR cannot merge. The outbox publishes the App-owned ruleset gate immediately before the guarded squash, then re-reads PR and refs. An unknown squash result permits read-back only; the Worker attempts to revoke the green gate and pauses if the result cannot be confirmed. After merging, a parent/tree mismatch pauses the queue and comments on the PR; it is never reported as success. Failed checks, timeouts, or conflicts dequeue the PR, remove queue, and comment with a failing-check link when available.

Diagnose a pause without wiping state:

  1. Read the PR comment and the mergespan check run on the PR head.
  2. Inspect mergespan/queue/<n> and check runs on its SHA: gh api repos/<owner>/<repo>/commits/<sha>/check-runs.
  3. Check the App’s Recent Deliveries for delivery IDs and response codes.
  4. Use wrangler tail for structured logs.
  5. DO SQLite state, labels, and branches are the recovery source: do not delete them or reinstall the App as a diagnostic. To stop one PR, remove queue; to retry an ordinary dequeue, re-add it. A hard pause is not cleared by re-labeling; there is no public resume endpoint. If GitHub was unavailable during revocation, verify the PR’s gate manually before allowing merges again.

7. Local validation

These mirror the ci job; local runs do not need U1–U3.

rustup target add wasm32-unknown-unknown
cargo fmt --all --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
node --test runtimes/cloudflare-ingress/test/webhook.test.mjs
cargo check --locked \
  -p mergespan-core \
  -p mergespan-engine \
  -p mergespan-github \
  -p mergespan-runtime-cloudflare \
  --target wasm32-unknown-unknown
cargo install worker-build --version 0.9.0 --locked
cd runtimes/cloudflare && worker-build --release

The release workflow’s validate job also runs bash .github/scripts/check-release-tag.test.sh, bash .github/scripts/fetch-origin.test.sh, bash .github/scripts/fetch-release-artifacts.test.sh, bash .github/scripts/fetch-previous-release.test.sh, bash .github/scripts/check-release-tools.test.sh, bash .github/scripts/release-evidence.test.sh and bash .github/scripts/reap-job-target.test.sh. Run those scripts after changing release logic, and run actionlint .github/workflows/*.yml and shellcheck .github/scripts/*.sh if installed. Tagged artifacts, deployment, and rollback are documented in Versions and Upgrades. Release evidence, the RC tag rules and the restart/upgrade harness are also documented there; bash .github/scripts/release-evidence.test.sh covers the provenance checks without creating a tag.

The native runtime deliberately has no wasm target; the wasm check selects the portable packages explicitly so the Worker validation is not weakened.

Native static validation additionally runs in CI: cargo zigbuild --release -p mergespan-runtime-native for x86_64-unknown-linux-musl and aarch64-unknown-linux-musl, then rejects any binary with PT_INTERP or DT_NEEDED; CI smoke-tests the prebuilt amd64 binary and verifies the distroless Dockerfile definition (CI does not build the image).

CI runs one job named ci on pull_request to main, with contents: read, on the fixed GitHub-hosted ubuntu-24.04 runner. Same-repository pull requests always run; a fork pull request runs only when the repository is public. The workflow references no secrets.

Fork pull requests execute untrusted workspace code on the same hosted runner class, so public repositories skip the ci-build Actions caches: a cache key is not a secrecy boundary. Release/publishing jobs additionally pass cache: false so no executable artifact comes from a cache writable by another run. Operators should still expire or purge pre-existing Actions caches if they may have been written from untrusted workspace or tool input; this repository does not perform that cleanup automatically.

The cache/toolchain/check/build steps live in .github/actions/ci-build and are shared with the release workflow, so the commands cannot drift; the ci job name, trigger, runner, permissions and required-check status are unchanged. The job still classifies docs/web/full changes first. It records the compressed Worker size in the job summary and fails above the 1 MB budget — a target, not a measurement.

The shared ci-build action’s cargo test --locked --workspace step also runs a short seeded merge-queue invariant sample (Full CI A: real coordinator transitions, randomized SHA/checks/base/parent/tree inputs) inside the normal PR budget; there is no separate short-test CI step. The longer sample is #[ignore]d so it never runs in the default cargo test --workspace; the explicit long command, reused by the scheduled full-ci-nightly workflow and by downstream CI workstreams, is:

cargo test --locked -p mergespan-engine --lib full_ci -- --ignored

Set MERGESPAN_FULL_CI_SEEDS / MERGESPAN_FULL_CI_STEPS to scale the long sample. full-ci-nightly runs on a clean standard GitHub-hosted runner with contents: read and no secrets, and has a 20 minute job budget.

8. Live sandbox test (not run)

After U1–U3, deployment, ruleset, and config:

  1. Open a non-draft PR to main; add queue.
  2. Expect a mergespan check run on the PR head, branch mergespan/queue/<n>, and the verification workflow on the candidate SHA.
  3. On green, the gate may still be before the final freshness reads and squash: do not clean up from the check alone. Confirm GitHub shows the PR merged with the expected parent/tree and the console Merged event, then expect candidate branch deletion.
  4. Then exercise the v0.1 scenarios: two queued PRs, failed check, push while queued, urgent interruption, close while verifying, main advance before merge, merge conflict, webhook replay, and redeploy mid-check.

Zero-event initialization (supersedes “first webhook required”)

A freshly installed App with no webhook deliveries can still initialize a repository:

  1. Install the App on the repository.
  2. Add .github/mergespan.toml with same_repo_only = true to the base branch and merge it.
  3. Open the console and click Reconcile.
  4. The runtime reads .github/mergespan.toml from the current base commit, creates the coordinator, and scans queue-labeled pull requests through the same path as the first webhook.

This is verified in runtimes/native/src/service.rs (dashboard_reconcile_initializes_a_repository_before_any_webhook) and crates/engine/src/durable.rs (a_later_slice_initializes_the_coordinator_and_scans_queue_labels). The first webhook is no longer mandatory for a fresh repository.

9. Sandbox scenario checklist

  • Zero-event brand-new repo, freshly installed App, no .github/mergespan.toml: Reconcile rejects or fails with repository_config setup check; add config and re-run.
  • Freshly installed App, config present, no webhooks: Reconcile succeeds; candidate scans run.
  • Wrong App permissions or missing event: console setup app_permissions / app_events fails with missing items.
  • Candidate creation refused: mergespan check Failure; check App contents:write.
  • Verification workflow missing created == false gate: creation push A triggers a check run; candidate C run may be cancelled.
  • Required check name mismatch: check never observed; candidate times out.
  • Push while queued: external_push_dequeue removes label and comments old/new head.
  • Urgent while validating: maybe_preempt requeues active; urgent moves to front.
  • Urgent while merging: preemption ignored; urgent waits.
  • Base advances while verifying: requeue_active with ReadinessChanged.
  • Squash conflict: settle_merge with FailureKind::MergeConflict dequeues.
  • Squash parent/tree mismatch: pause_post_merge pauses queue and comments.
  • Webhook replay: duplicate delivery receipt; state unchanged.
  • Redeploy mid-check: persisted outbox recovers; next alarm re-arms.
  • Native legacy database file: startup refuses; no migration.