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

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.