jig-harness/jig
M10

Environments & deploy

PR gates → verify → deploy → promote; ephemeral envs; test-data factory
1 · The idearead this first

“It merged” and “it works where users are” are different facts, and shipping as if they were the same is how a green merge becomes a production incident. Merging means a change is on the main line and its per-diff checks were green; it says nothing about whether the integrated system — on the real branch, with everything else that landed this hour — stands up. Without an architecture that keeps these two facts apart, teams either deploy too eagerly (every merge reaches users, and a bad one gets there before anyone looks) or too fearfully (deploys are a rare, manual, scary event). This module is the pipeline shape that separates them: verify what merged, mark it explicitly, deploy only the marked thing, and let a human make the final call to production. It also covers the environment kit that makes verification honest — disposable preview environments and a seeded, isolated, resettable test-data factory.

Invariantthe rule, independent of any tool

The delivery pipeline keeps “merged” and “verified” as separate facts: PR gates run on every pull request and inform a human merge; post-merge verification runs on the integrated default branch and advances an explicit verified pointer (a branch or tag) only on success; a watchdog decides why that pointer lags, heals a dropped trigger within a budget of attempts and fails on the faults a person must repair, so a stalled verifier pages someone instead of silently shipping stale code; deploys ship only what verified points at, never a mutable branch or :latest; and promotion to production is a manual, gated human action that cannot auto-fire. A promotion ships the exact commit and artifact its gates approved, built once and passed from job to job, and is complete only when the live environment reports that identity. Preview environments are disposable and cheap; test data is seeded, tenant-isolated, and resettable. Every resource the pipeline creates has a reaper keyed to its owner, with its expiry set when it is created; which changes have reached which environment is read from version-control ancestry, never kept by hand; and a check against an environment that is deliberately behind confirms the environment’s currency first, dropping its cell rather than reporting a false red or a false green. External preconditions are declared as intended state and checked read-only on a schedule under their consuming identity. Unreadable, pending and expired exceptions never pass; findings keep one current issue until recovery.

Everything below is that tool-independent statement made mechanical; concrete per-provider wiring lives in mappings.md.

2 · The practicewhat each level asks of your repository

M10 Lite — minimum useful

the environments and the deploy path are written down (a deploy runbook exists, environments are named and described), and PR gates run on every pull request. Enforcement may be convention; the verify/deploy split may still be informal.

What the audit checks at Lite convention-only is enough must be mechanically enforced
  1. The deployable environments and the path from merge to production are written down once (a deploy runbook / CI-architecture doc), so where code goes and how it gets there is not tribal knowledge.
    environments-and-deploy-documentedWhat the audit looks for (2)
    • a doc names the environments and describes the merge -> verify -> deploy -> promote path
    • a deploy runbook exists (how a release actually happens)
  2. Per-PR gates run on every pull request before merge, and the pipeline states that a green merge is not yet a production-ready fact.
    pr-gates-run-before-mergeWhat the audit looks for (2)
    • PR-scoped checks run on every pull request (informing the human merge)
    • the architecture doc distinguishes 'merged' from 'verified'

M10 Standard — production teams

CI separates PR gates from post-merge verification; a verified pointer advances only on passing verification (mechanically, in CI); production deploys ship only verified artifacts, with the gated commit passed from job to job; artifacts are built once and promoted by digest; the watchdog runs on a schedule, counting only code-bearing lag; every resource the pipeline creates has a scheduled, owner-keyed reaper that reports by default; the promotion gap is computed from ancestry on a schedule; and a page that lists the pipelines, where one is kept, is generated or checked, never hand-kept; external preconditions are declared and checked live under their consuming identities, with expiring waivers.

What the audit checks at Standard convention-only is enough must be mechanically enforced
  1. CI has a distinct post-merge verification stage that runs on the integrated default branch, separate from the per-PR gates.
    verification-separated-from-pr-gatesWhat the audit looks for (3)
    • a workflow triggered on push to the default branch runs the heavier verification suite
    • it is separate from the pull_request gate workflow
    • a suite runs per change only when a merge or the verified pointer waits for it; slow suites neither waits for run on a schedule or on demand
  2. An explicit `verified` pointer (a branch or tag) is advanced only by the post-merge verification stage passing — never by a merge alone.
    verified-pointer-advances-on-verificationWhat the audit looks for (2)
    • a verified branch/tag exists and is moved by a verification job on success
    • nothing else advances it (merge does not move it)
  3. Deploy jobs ship what the `verified` pointer points at, not a mutable branch or a moving tag (expected-absent for a library-shaped repo, which publishes rather than deploys environments).
    deploys-verified-artifacts-onlyWhat the audit looks for (3)
    • deploy jobs check out / download the verified pointer or its artifact
    • no deploy job targets main / HEAD / :latest for a real environment
    • every job after the first in a promotion takes the commit from an upstream job's output (needs.<job>.outputs.<sha>, a dotenv variable), never fetching a branch or the verified pointer by name again; the promote-safety lint's rule (c) is green over the deploy workflows, and the other jobs of a promotion (migrate, verify), which the lint does not examine, are inspected by hand
  4. What reaches production is the artifact verification approved, built once and addressed by digest, with per-environment settings supplied at deploy time rather than compiled in (expected-absent for a library-shaped repo, which publishes rather than deploys environments).
    artifacts-built-once-promoted-by-digestWhat the audit looks for (3)
    • deploy commands or deployment manifests name the artifact by its content digest (an image as image@sha256:..., a web bundle by its content hash), and a check rejects a movable name, such as a tag, where a digest belongs
    • promotion re-tags or copies the verified artifact; no production job rebuilds it
    • per-environment configuration reaches the artifact at deploy time (a runtime config file such as env.js, environment variables, a ConfigMap), not as a build-time constant
  5. A scheduled watchdog fails when the `verified` pointer lags the default-branch tip beyond a threshold, counting only code-bearing changes, so a stalled verifier pages someone instead of silently shipping stale code.
    freshness-watchdog-runsWhat the audit looks for (3)
    • a scheduled job computes the pointer's lag (in commits or in time) and fails past a threshold, or decides by cause (watchdog-decides-by-cause)
    • the lag counts only commits that change a path verification builds or tests (a path filter on the range, or the cause mode's code-ahead check); a documentation-only tip does not fail it
    • its failure is wired to a page and/or an automatic heal (a dispatch of verification)
  6. Every resource the delivery system creates (a preview deployment, an ephemeral environment, a test tenant, a per-worktree data namespace) has a scheduled reaper keyed to the resource's owner that reads an expiry written at creation; a destructive reaper reports by default, acts only on an explicit opt-in, and refuses production (expected-absent for a library-shaped repo that creates no environments, tenants or namespaces).
    created-resources-have-reapersWhat the audit looks for (4)
    • each create step (a preview deploy, an environment spawner, a tenant factory, a namespace create) writes an owner and an expiry at creation (an annotation, a comment, a registry row), or the host keeps the resource by age
    • a scheduled workflow or job per resource kind removes what has expired, lost its creator or exceeds a keep-newest count, and fails on a listing error rather than reading it as nothing to do
    • the reaper's default is a report (--dry-run); it acts only when a repository variable or a dispatch input opts in, and refuses the production environment or namespace before anything is rendered
    • one owner's reaper touches only that owner's resources; a resource without an owner or expiry is reported, never reaped
  7. Which changes have reached which environment is computed from version-control ancestry between the environments' pointers, on a schedule and whenever a pointer moves, and published as a report and a metric; no tracker field tracks it by hand (expected-absent for a library-shaped repo with a single release line and no environments).
    promotion-gap-from-ancestryWhat the audit looks for (4)
    • a scheduled job, also triggered by a push to each pointer branch, lists the work items the commits in <lower pointer>..<higher pointer> name in their subjects and trailers, per environment pair
    • it refuses to report when the lower pointer is not an ancestor of the higher one, and fails on an unresolvable ref or a failed git call rather than reporting an empty gap
    • its output reaches where the team reads (a run summary, an artifact, a pinned document) and its count is a metric in the metrics registry
    • no tracker status or field records which environment a work item has reached
  8. Where the repository keeps a page listing its pipelines, that page is generated from the pipeline files or a check fails when a pipeline is missing from it or it names one that no longer exists; a hand-kept page with no check does not count.
    pipeline-index-derived-or-gatedWhat the audit looks for (2)
    • a generator writes the page from the pipeline files (header comments, names) with a drift gate in CI, or a CI check compares the page's entries with the pipeline files in both directions
    • expected-absent when no such page exists: the provider's list is the index
  9. External state delivery depends on is declared as intended state in a repository registry and checked read-only on a schedule under the real consuming identity; unreadable state, pending checkers and expired waivers fail rather than reporting green.
    external-preconditions-live-checkedWhat the audit looks for (6)
    • the registry names each precondition's kind, intended state, owner and recovery action, without dated verification snapshots
    • a scheduled runner checks live state using the consuming identity; secret checks exercise read access and identity checks exercise authentication and authorization
    • missing and denied are distinct diagnostics; unavailable or ambiguous reads fail closed
    • unimplemented checkers remain pending and non-green; deliberate exceptions name a reason, approver and an enforced expiry
    • a branch written directly by a bot cannot require pull requests without admitting that bot through every applicable blocker
    • the runner has paired self-tests with pass, denied, pending and expired-waiver cases, run in CI

M10 Strict — regulated / compliance posture

the verified-pointer watchdog and the promote-safety lint both run in CI with their self-tests; the watchdog decides by cause, heals only a dropped trigger and within a budget of attempts, bounds the runner queue and fails on divergence, and verification covers the whole unverified range; promotion to production is manual and gated by an environment protection rule so it cannot auto-fire (mechanical), runs from the trusted ref, one at a time without dropping a request; a deploy completes only on the live identity check; release state is kept off the source line; ephemeral preview environments plus a resettable, seeded, tenant-isolated test-data factory exist; and a check against a deliberately-behind environment confirms its currency first and drops the cell otherwise.

What the audit checks at Strict convention-only is enough must be mechanically enforced
  1. A scheduled check that runs against an environment that is deliberately behind first confirms the environment runs a version the check applies to: the floor is derived from history, the deployed version is read from the environment's pin, ancestry decides, and a non-current environment's cell is removed from the matrix rather than skipped (expected-absent where no scheduled check runs against an environment that is deliberately behind).
    environment-currency-checkedWhat the audit looks for (4)
    • a currency job derives the floor as the newest commit touching the check's dependency paths (git log -1 -- <paths>), never from a hand-kept minimum version
    • it reads the deployed version from the environment's pin (a manifests commit, an identity endpoint) and tests ancestry (git merge-base --is-ancestor <floor> <deployed>)
    • it emits the list of current environments, and the check's matrix is built from that output, so a stale environment has no cell; the cell is not merely skipped by a condition
    • an unreadable pin, a dependency path that no longer exists or a failed git lookup counts the environment as stale; the check's other cells still run when the currency job itself fails
  2. The watchdog decides why the `verified` pointer lags and acts by cause: it heals only a dropped trigger, by dispatching verification at the tip, and only up to a budget of dispatches at the same tip; it fails when the heals at a tip keep ending without a verdict, when verification succeeded but the pointer did not move, when the pointer diverged from the integration branch, and when a verification run has waited for a runner past a bound, which it cancels; and verification covers the whole range from the pointer to the tip, so a superseded or cancelled run is covered by its successor (expected-absent for a library-shaped repo with no verified pointer).
    watchdog-decides-by-causeWhat the audit looks for (8)
    • the watchdog's lag counts only changes to paths verification builds or tests; a documentation-only tip does not fail it
    • it reads the tip's verification runs and tells running (fine), failed (fine, no heal), succeeded with the pointer unmoved (fail, never re-run) and no conclusive run past a grace window (heal: a dispatch of verification at the tip) apart; a run that was cancelled or timed out counts as no verdict
    • it counts its own dispatches at the current tip that ended without a verdict and, past a budget, fails instead of dispatching again
    • it fails on a pointer that is not an ancestor of the integration branch, naming a back-merge as the recovery; nothing force-resets the pointer
    • it reads the verification runs' jobs and cancels, then fails on, a run whose job has waited for a runner past a bound; a job waiting for an environment approval does not count
    • every read fails closed: a failed or malformed listing is not read as no runs, and an ancestry check that errors is not read as not an ancestor
    • the watchdog runs on a runner pool other than the one verification runs on, or from outside the provider
    • the verification workflow's change detection diffs the whole verified..tip range, never the tip against its parent; its concurrency keeps one pending run per integration branch without cancelling a running one, gives a dispatch from another ref its own slot, and accepts a manual dispatch
  3. The verified-pointer freshness gate and the promote-safety lint both run in CI, each with a self-test, so a broken deploy gate fails loudly.
    verify-and-promote-gates-self-tested-in-ciWhat the audit looks for (2)
    • bun check-verified-fresh.ts and bun check-promote-safety.ts run in CI
    • each ships a paired self-test exercising a known pass and a known fail, run in CI
  4. Promotion to production is a manual action behind an environment protection rule and cannot auto-fire on push (expected-absent for a library-shaped repo with no production environment).
    production-promotion-manual-and-gatedWhat the audit looks for (2)
    • the production deploy uses a manual trigger and a protected environment (required reviewers / wait timer)
    • no workflow auto-deploys to production on push; the promote-safety lint over the deploy workflows is green
  5. Disposable preview environments are created and destroyed per PR, and a seeded, tenant-isolated, resettable test-data factory exists (expected-absent for a library-shaped repo with no runnable environment).
    ephemeral-envs-and-test-data-factoryWhat the audit looks for (2)
    • a workflow creates a preview environment on PR open and destroys it on close
    • a factory seeds a known dataset per isolated tenant and can reset to it in one command
  6. Promotions to one environment never drop a queued request, and each waits until no earlier promotion is active before its first change and checks again just before the migration; the promotion workflow and its gate code load from the trusted ref, the only ref the production environment admits (expected-absent for a library-shaped repo with no production environment).
    promotions-serialized-from-trusted-refWhat the audit looks for (3)
    • the promotion's serialization queues every request: no concurrency group that keeps only one pending run guards it alone (GitHub: a group keyed per run plus a lock job that waits for earlier active promotions; GitLab: a resource_group held across the whole mutating sequence, on the one job or trigger job with strategy: depend that runs it, not on each job separately)
    • the lock refuses a re-run of a promotion (GitHub: github.run_attempt above 1), which keeps its original run id, and is checked again just before the migration or other irreversible step
    • the gate job checks its code out from the verified pointer, and the production environment admits only that ref (GitHub: its deployment branches and tags rule lists only verified; GitLab: production credentials are released only to the verified ref, e.g. an ID token whose cloud trust policy admits only that ref, since protected variables reach every protected ref)
  7. A deploy is complete only when the live environment reports the exact artifact identity that was promoted, its rollouts are ready, and a readiness check that exercises the application's critical dependencies passes; anything downstream reads a manifest of what actually deployed (expected-absent for a library-shaped repo with no runnable environment).
    deploy-verifies-live-identityWhat the audit looks for (3)
    • a job after every deploy compares the live spec's image (or a build-info identity) with the promoted digest before waiting on rollout status
    • it waits for rollouts to be ready (e.g. kubectl rollout status, argocd app wait --health) and calls a readiness endpoint that exercises the application's critical dependencies (for an application with a database, one that queries it), each under a deadline
    • the deploy run publishes a manifest of the parts it deployed, and downstream workflows read it rather than the run's conclusion
  8. Release pointers only fast-forward to verified source, and rendered deployment state lives on its own ref, written only by a dedicated machine identity that the ref's protection admits (expected-absent for a repository with neither a release pointer nor rendered deployment state in git; a repository with only one of them is scored on that one).
    release-state-off-source-lineWhat the audit looks for (3)
    • the release pointer advances only by a fast-forward to the gated commit (git merge --ff-only, then a check that it equals the gated commit), only after the identity check passes, a gated commit older than the pointer is refused once the promotion holds the lock, before its first change, and no job commits generated files to it
    • rendered manifests are committed to a dedicated ref that a GitOps controller reads (Argo CD targetRevision, Flux GitRepository ref)
    • only one job holds the writer identity's credentials, and the ref's protection restricts pushes to that identity with no pull-request requirement (or an explicit bypass for it)

Deploy-shaped criteria are expected-absent for a library-shaped repo: a published package has no environments, no verified-to-production path, and no preview environments to spin up. Its path to its users is a release in versions, which M16 covers: a changelog per released artifact, the version chosen after the merge, a tag only on verified code. Such a repo can satisfy this module at Lite (document that it does not deploy) without the Standard/Strict deploy machinery counting against it; the audit calibrates by repo shape. A repository that both deploys and publishes follows both modules.

Adoption steps

  1. Copy templates/CI-ARCHITECTURE.md into your docs tree and adjust the tool names; use templates/pipeline.example.yaml as the spine when you split your CI into the four stages.
  2. Introduce the verified pointer: add a post-merge verification workflow that advances a verified branch/tag only on success, and point your deploy jobs at it instead of at a branch.
  3. Make verification diff the whole verified..tip range and accept a manual dispatch, then add the watchdog (reference/verified-pointer/) as a scheduled job on another runner pool: it dispatches verification on a dropped trigger within its heal budget, cancels a run stalled in the runner queue, and fails on the faults a person must repair (an exhausted heal budget, a pointer that did not move after a success, a stalled queue, divergence, an observation it cannot read); wire the failure to your pager.
  4. Gate production behind a manual trigger + environment protection rule, and add the reference/promote-safety/ lint over your deploy workflows so the gating can’t regress.
  5. Make the promotion execute what it gated (Promotion execution): output the gated commit from the first job and pass it on, promote artifacts by digest with settings supplied at deploy time, serialize promotions without dropping one, end every deploy with the identity check, and move rendered deployment state to its own ref (recipes in mappings.md).
  6. Stand up disposable preview environments per PR and a seeded, tenant-isolated, resettable test-data factory (platform options in mappings.md).
  7. Keep the kit clean (Environment hygiene): give every create step its owner-keyed, report-first reaper; run reference/promotion-gap/ on a schedule and on every pointer move, and register its count as a metric; and put a currency step in front of any check that runs against an environment that is deliberately behind.
3 · The mechanicsopen what you need
Core piecesOpen
  1. The four stages — delivery is PR gates → post-merge verification → deploy → promotion, each with one responsibility and a hard boundary to the next, however many jobs it runs. Stage 2 never trusts stage 1’s green, stage 3 only ships what stage 2 marked, stage 4 never fires itself. The copyable contract is templates/CI-ARCHITECTURE.md; the provider-neutral spine is templates/pipeline.example.yaml.
  2. The verified pointer — an explicit, inspectable marker (a branch or tag, e.g. refs/tags/verified) that names “the newest commit we actually trust.” Post-merge verification is the only thing that advances it, and deploys read it. It turns “is this good enough to ship?” from a vibe into a commit anyone can query.
  3. The watchdog — a scheduled check that asks why the pointer lags the default-branch tip and answers by cause: nothing to verify, verifying, blocked by failed gates, a dropped trigger it heals, heals that keep ending without a verdict, a pointer that did not move after a success, a diverged pointer, a run stalled waiting for a runner. If verification wedges, the pointer freezes silently; the watchdog makes that silence loud and heals the one cause a machine can. It is a freshness gate on a pointer rather than a file, the same move M2 makes for generated files, with the decision a pointer needs, and it ships as reference/verified-pointer/.
  4. Deploy verified artifacts only — deploy jobs are driven by the pointer moving and check out what it points at, never a raw branch or a moving tag. A deploy that reads main instead of verified bypasses the whole chain.
  5. Manual, gated promotion — production is reached by a deliberate human action on an already-verified, already-deployed build, behind an environment protection rule (required reviewers / wait timer). It must be impossible for a push to auto-promote. This is a HITL boundary shared with M7, enforced by configuration and by the reference/promote-safety/ lint, which fails a production deploy that auto-fires, ships a mutable ref, or looks its commit up again by name.
  6. Ephemeral preview environments — each PR (and each verification run) can spin up its own disposable copy of the app on its own URL, torn down when the PR closes. Cheap and throwaway by design: a broken one is deleted, not debugged. Reviewers click a link instead of imagining the behavior.
  7. A test-data factory — a programmatic way to seed a known, realistic dataset on demand, give every run (or preview environment) its own isolated tenant so runs can’t corrupt each other, and reset to the known state in one command. Seeded + tenant-isolated + resettable is the contract; without it, “realistic” tests are flaky and fixtures rot. Values a test builds in its own process are a different tool, M14’s typed test-data builders; M14 also says which test tiers run per change and which on a schedule.
  8. Promotion execution — the promotion itself ships what its gates approved, and proves it did: see Promotion execution.
  9. Environment hygiene — every resource the pipeline creates (a preview deployment, an ephemeral environment, a test tenant, a per-worktree data namespace) has an owner-keyed reaper that reads an expiry set at creation; the promotion gap between two environments is computed from git ancestry by reference/promotion-gap/; and a check against a deliberately-behind environment confirms its currency first: see Environment hygiene.
External preconditionsA green build cannot establish that a service identity can read its secrets, that a certificate still matches its pin, or that a bot can write a protected branch. Those are external…Open

A green build cannot establish that a service identity can read its secrets, that a certificate still matches its pin, or that a bot can write a protected branch. Those are external preconditions: facts the pipeline depends on but does not contain.

Declare what must be true, with an owner and a recovery action, in a repository registry. Never record a dated inventory of what was true. Check it on a schedule against the live system, read-only, under the identity the real consumer uses. An administrator’s successful read does not prove that a workflow’s identity has access. Check an identity end to end: a user that exists but cannot authenticate, or a secret that exists but cannot be read, does not satisfy the precondition.

A checker that cannot read the live state fails. Report absent separately from denied; where a provider hides existence from an unauthorized caller, report the uncertainty instead of claiming absence. A kind whose checker has not landed is pending, never green. A deliberate exception names its reason, approver and expiry; an expired waiver fails even if the underlying condition now holds, so the stale exception must leave the registry. A valid waiver remains visibly waived and cannot hide an unreadable or pending check.

The registry template and reference runner provide this contract. The first kind checks branch protection, including classic rules and rulesets together. Expected protection for a bot-written branch must permit the named bot to bypass a pull-request requirement; every applicable live rule must admit its write. A bypass in one ruleset cannot cancel a blocker in another. A bypass that also lets the bot force-push or delete a branch fails when the expected state forbids those operations for it.

The report maintains one current tracker issue for the registry through M11’s reconciliation rule. Live checks never repair host settings. A person reviews and applies the recovery action; the next observation proves whether it worked.

The watchdog decides by causeA pointer that lags is a symptom with several causes, and each wants a different response. A threshold on the lag ("more than 20 commits, or older than a day") can only page, and it…Open

A pointer that lags is a symptom with several causes, and each wants a different response. A threshold on the lag (“more than 20 commits, or older than a day”) can only page, and it pages for the wrong things: a tip that changes only documentation, a verification that correctly failed. People learn to ignore the page, and the one time it matters, nobody looks. So the watchdog decides by cause, under these rules.

  • Lag counts only code-bearing changes. The pointer lags when the range from it to the tip changes a path verification builds or tests. A tip that changes only documentation legitimately leaves the pointer behind: nothing about it needs verifying.
  • Decide by cause, and heal exactly one. For a tip with code ahead, the state of its verification decides. A run queued or in progress is latency: fine. A run that failed is the gates holding the pointer back: fine, and no heal, since running them again changes nothing until the tip changes. A run that succeeded while the pointer stayed is a skipped or broken advance step: it fails for a person to look at and is never re-run, because re-running reproduces the skip. No conclusive run past a grace window is a dropped trigger: the push never became a run, or the run ended without a verdict (cancelled, timed out, never started). The watchdog heals it by dispatching verification at the tip. That is the only cause it heals, and only within a budget of attempts: when the runs it dispatched at the same tip keep ending without a verdict, another dispatch would only repeat them on every scheduled observation, so past the budget it stops healing and fails for a person. Every other failure is a fact for a person.
  • A queue stall is a failure. A job’s timeout counts no time spent waiting for a runner, so a run no runner picks up holds its serialized slot indefinitely, and every newer run waits behind it while everything reads as latency. The watchdog bounds that wait, cancels the run that holds the slot and fails loudly: the cancel frees the slot, and the missing runner is a capacity fault only a person can repair. The cancel bypasses no gate, because the next run covers the whole range (below). This is M13’s bound applied to post-merge verification; M13’s queue-stall check measures the same wait over every workflow, and its supersede rule says when a cancelled run is covered.
  • Divergence is a failure. The pointer only ever fast-forwards, so a pointer that is not an ancestor of the integration branch can never advance again: something wrote a commit to it that the branch lacks. The watchdog fails and names the recovery: contain first (until shown otherwise, a divergence is a leaked writer credential or a broken workflow), then a back-merge, a commit on the integration branch with the branch’s own tree and the pointer’s tip as its second parent, which restores ancestry without merging the diverged content. Never force the pointer back: its protection exists to forbid that write, and a pointer that jumps backwards makes the deploy that follows it ship something older than what runs.
  • Verification covers the whole gap. Every verification run diffs the whole range from the pointer to the tip, never the tip against its parent. Only then is it safe for the verification queue to keep one pending run per branch and drop the runs it supersedes, for the watchdog to cancel a stalled run, and for a heal dispatched at the tip to cover a dropped push behind a documentation-only commit. A tip-only diff loses a superseded push’s changes without a trace: a push that renames a database column queues behind the run in progress, a typo fix lands on top of it and takes its place in the queue, and the surviving run, diffed against its parent, sees the typo and never the rename. A dispatch from another branch covers nothing of the integration branch’s queue, so it gets a slot of its own.

reference/verified-pointer/ makes the rules mechanical: it takes the observation (ancestry, code ahead, the tip’s verification state and age, the longest runner wait, the heals already dispatched at the tip) and gives two verdicts the workflow branches on, queue= and pointer=. The recipes that collect the observation per provider are in mappings.md. A watchdog scheduled onto the runner pool it watches stalls with it: give it another pool.

Promotion executionA gated, manual promotion can still ship the wrong thing. The gate checks one commit; a later job fetches the branch again and gets a newer one. Staging verified one build; production…Open

A gated, manual promotion can still ship the wrong thing. The gate checks one commit; a later job fetches the branch again and gets a newer one. Staging verified one build; production gets a rebuild with different bytes. The deploy command returns success; the cluster is still running the old version. Two promotions start a minute apart; one of them is silently dropped, or both migrate the same database at once. Each of these passes every check described so far. The invariants below close them.

The gated commit is the shipped commit

  • Pass the commit, never look it up again. The first job of a promotion resolves the verified pointer once and outputs the commit it checked. Every later job (migrate, deploy, verify) takes that commit from the upstream job’s output. A job that fetches a branch by name, the pointer included, gets whatever the name points at when that job starts, and the pointer may have moved while the gate ran or while the run waited its turn. The promote-safety lint’s rule (c) fails a production deploy job that selects its commit by name.
  • One promotion per environment at a time, and none dropped. Two promotions running together race each other’s deploy and, worse, each other’s database migration. Serialize them, but through a mechanism that queues every request: a mechanism that keeps only the newest pending run discards a request someone made on purpose, with different inputs, without telling anyone. Where the CI provider’s own serialization drops pending runs, key it so it never does and add an explicit lock step that waits for every earlier promotion to finish before the first change is made. The lock refuses a re-run, which keeps its original place in that order and would pass as earliest while a later promotion is changing production (start a new promotion instead), and is checked again just before the step that cannot be undone, the migration (mappings.md has the GitHub Actions form). GitLab’s resource group is held per job, so it serializes a promotion only when it is held across the whole mutating sequence: on the one job, or trigger job, that runs it. On GitHub Actions a lock held for the whole mutating section would not depend on that order (see Future).
  • Run the promotion from the trusted ref. A manually started workflow runs the copy of its own definition that lives on the branch the operator picks, so starting it from an old or unreviewed branch runs old or unreviewed gate code against production. Start promotions from the verified pointer, check the gate’s own code out from it, and have the production environment admit only that ref, so a run started from any other branch cannot deploy. Instructions and defaults alone do not stop an operator from picking another branch.

Build once

Build once: what reaches production is byte-identical to what verification approved: the same container image, the same bundle, addressed by its digest (a hash of the content, such as image@sha256:…), never by a tag that can be moved. Promotion copies or re-tags that artifact; it never rebuilds it. That only works when nothing environment-specific is compiled in, so per-environment settings (the API’s address, public keys, feature switches) are supplied at deploy time: a runtime configuration file served beside a web app’s bundle, environment variables or a configuration object for a container. The artifact’s own identity (the commit it was built from) is the one value that stays compiled in, because it describes the code, not the environment.

Post-deploy identity

  • A deploy is done when the environment says so (the post-deploy identity check). The deploy command returning, or a deployment tool reporting “synced”, says the request was accepted, not that the new version runs. A deploy is complete only when the live environment reports the exact artifact identity that was promoted (the digest it runs), its rollouts are ready (every running copy of the new version, a replica, is up, and none of the old serves traffic), and a readiness check that exercises the application’s critical dependencies passes (for an application with a database, one that queries it). Check the reported identity before waiting on rollout status: a wait started before the new version is applied reports the previous, already-finished rollout as success.
  • Read what actually deployed. A deploy run that changed only some of its parts (the backend but not the web app) writes a manifest of what it actually deployed this run: each part, whether it deployed, and its identity. Anything downstream, such as an end-to-end run against the new environment, reads that manifest instead of assuming everything changed or guessing from the run’s success.

Release state off the source line

  • Release pointers stay pure fast-forwards of verified source. A pointer that says “this is what production runs” (a main or release branch advanced only by promotion) only ever moves forward to a commit the verified pointer held, and only once the identity check has passed, so a failed render or rollout leaves it naming what production still runs. A promotion whose gated commit is older than the pointer is refused before it changes anything, checked against a freshly fetched pointer once the promotion holds the lock: a fast-forward-only merge of an older commit succeeds as a no-op, so check that the pointer is an ancestor of the gated commit, and that the pointer equals the gated commit after the merge. If the promotion also commits generated files to it, the pointer diverges from verified, and the next promotion cannot fast-forward.
  • Rendered deployment state lives on its own ref. When deployment is driven from git (GitOps: a controller makes the cluster match what a git ref holds), the rendered manifests for an environment (its rendered state) go to a dedicated ref holding nothing else. Only a dedicated machine identity, allowed to write that ref and nothing else, writes it. Its history is the record of what was deployed, and rolling back means returning it to an earlier commit.
  • Branch protection must let that identity through. A machine-written ref is advanced by a direct push, never by a pull request, so a rule that requires every change to arrive through a pull request blocks the writer, even when it requires zero approvals. Protect such a ref by restricting who may push to the one writer identity, and require no pull request on it; where a pull-request rule must stay, give the writer an explicit bypass. A release step that commits a new version to the integration branch uses the same exception, narrowed further; that branch is then not a release pointer, and M16 says how the two stay apart.
Environment hygieneThe environment kit creates things: a preview deployment per pull request, an ephemeral environment per verification run, a tenant per test run, a database namespace per worktree, a…Open

The environment kit creates things: a preview deployment per pull request, an ephemeral environment per verification run, a tenant per test run, a database namespace per worktree, a process a test started. Each is cheap to create and, left alone, stays forever. The failures are slow and then sudden: a host that stops publishing once a project holds too many stale deployments turns a missing reaper into a deploy outage; a shared database fills with the schemas of branches deleted months ago; a scheduled check pages every night about an environment that is behind on purpose. The rules below keep the kit honest.

Every created resource has a reaper

  • Teardown is symmetric with creation. Whatever creates a resource writes, at creation, who owns it and when it expires (a label on the namespace, a comment on the schema, a row in a registry), and a reaper keyed to that owner runs on a schedule and removes what has expired or lost its creator. The reaper is decided when the create step is written, not when the platform fills up. Preview deployments are kept by count per project (the newest N, the rest deleted oldest first); ephemeral environments by the expiry their spawner wrote; per-worktree namespaces by owner and expiry (M12’s reference decides which to drop); processes and scratch directories a test started by the test runner’s own scope, which removes them when the process ends.
  • Report first, act on opt-in, refuse production. A destructive reaper’s default is a report of what it would remove. It acts only when a repository variable or a dispatch input says so, never because it merged: a destructive scheduled job that goes live on merge removes something the day its first bug ships. It refuses the production environment or namespace outright, at every layer it has (the operator’s command, the rendered job, the target the job reads from its own environment), so no combination of inputs reaches production. A reaper that cannot read what it would reap (a failed listing, a denied credential) fails rather than reading the failure as nothing to do.
  • One owner’s reaper touches only that owner’s resources. Two owners’ reapers then never race, and a resource created without an owner or an expiry is reported as unlabelled, never reaped: the missing key is the finding.

The promotion gap comes from ancestry

Which changes have reached which environment is the range between the environments’ pointers: the commits in production..verified are what waits for the next promotion, and the work items they name in their subjects and trailers are the promotion gap. reference/promotion-gap/ reads it. It is never kept by hand in tracker fields (“deployed to staging”): a field holds only while every promotion remembers to move every item, and a pointer that moved by itself (a deploy, a back-merge) moves no field. The report runs on a schedule and on every push to a pointer branch, publishes where the team reads (the run’s summary, an artifact, a pinned document), and its count per environment pair is a metric in M11’s registry. When the later environment’s pointer (production) is not an ancestor of the earlier one’s (verified) the gap is not a range, and the report refuses to decide: the divergence rule applies.

A check confirms the environment’s currency first

An environment that is deliberately behind (a demo promoted by hand, a staging that waits for a window) runs an older version than the integration branch. A scheduled check that calls into it (a janitor, a smoke test, a contract test) depends on routes, schemas and behaviour that landed at particular commits; run against an older build it reports red for staleness that is no defect, and after enough red nobody reads it. So a currency step decides, once, before the check’s cells are built, whether the environment runs a version the check applies to:

  • The floor is derived, never declared. The oldest version the check applies to is the newest commit touching any path the check depends on, read from history. A minimum version kept by hand stops moving the day someone changes a dependency without updating it, and from then on it reports current for an environment that is not.
  • Ancestry decides. The deployed version is read from the environment’s own pin (the commit its manifest names, the identity its build reports), and the environment is current when the floor is an ancestor of it.
  • A non-current cell is removed, not skipped. The currency step emits the list of environments to check, and the matrix is built from it; a skipped cell still reports a status, and a status that is neither red nor green is read as green. No cell means no status, which is the honest answer.
  • It fails closed, without taking the rest down. An unreadable pin, a dependency path that no longer exists, a git lookup that fails: each counts the environment as stale and drops its cell. The check’s other cells still run when the currency step itself fails for reasons of its own (a checkout that timed out), so an infrastructure failure of one environment’s step does not silence another’s.

mappings.md wires each per provider: the reaper’s opt-in and its keep-newest sweep, the gap report’s triggers, and the currency step’s matrix.

In your toolsThe same rule, wired into a specific CI provider, hook manager or tracker. Shows only your stack.Open

The module invariant — four stages, an explicit verified pointer, a watchdog that decides why the pointer lags, verified-only deploys, a manual gated promotion that ships what it gated — is tool-independent. This file maps its mechanisms onto concrete CI providers, preview-environment platforms, promotion gates, and the promotion-execution tools (registries, GitOps controllers, rollout checks). Replace <placeholders> with your values. Install the pinned Bun runtime before the commands below; the module gates and tests require Bun.

The two gates, per rung

GateLocal (hook)CI (authority)
Promote-safety lintpre-commit over the deploy workflows (optional)blocking on any PR that touches the deploy workflows — the workflows are the thing checked
Verified-pointer watchdogn/a (needs live pointer, run and queue state)scheduled job on another runner pool; heals a dropped trigger within a budget of attempts and cancels a stalled run; fails on the faults a person must repair (ran but stale, a stalled queue, a diverged pointer, heals exhausted, an observation it cannot read); passes running verification, failed gates and a documentation-only gap

The watchdog is a scheduled job, not a per-PR gate — it watches a background process (verification keeping up), not a diff, exactly as M8’s parity report is scheduled rather than per-PR.

One thing the promote-safety example must get right and you must not drop:

  • Run the lint from the BASE, not the PR checkout. A merge-blocking lint that runs out of the PR’s own checkout is not a gate — the PR can edit the script (or the workflow) to report success. Check the PR’s tree out as data to be scanned, and run the gate script from a separately checked-out base tree the PR cannot alter (or a pinned reusable workflow). Set one M10 variable to wherever you vendored the module and build every path from it. This is the same base-not-head discipline as M7’s reviewer lint.

GitHub Actions

yaml
# .github/workflows/deploy-safety.yml — lints the deploy workflows on every PR
on:
  pull_request:
    paths: [".github/workflows/**"]
jobs:
  promote-safety:
    runs-on: ubuntu-latest
    env:
      M10: base/modules/M10-environments-deploy    # gate scripts, from the base tree
    steps:
      - uses: actions/checkout@<full-commit-sha>    # v4; PR tree — scanned as DATA
        with: { path: pr }
      - uses: actions/checkout@<full-commit-sha>    # v4; BASE tree — owns the gate
        with:
          ref: ${{ github.event.pull_request.base.sha }}
          path: base
      - name: Production deploys are gated + verified-only (blocking)
        run: WORKFLOWS_DIR=pr/.github/workflows bun "$M10"/reference/promote-safety/check-promote-safety.ts
      - name: Gate self-tests (blocking)
        run: |
          bun test "$M10"/reference/promote-safety/check-promote-safety.test.ts
          bun test "$M10"/reference/verified-pointer/check-verified-fresh.test.ts

GitLab CI

yaml
promote_safety:
  rules: [{ if: '$CI_PIPELINE_SOURCE == "merge_request_event"' }]
  variables:
    # Gate scripts MUST come from the BASE the MR targets, never the MR's own
    # tree — a fork MR can edit its own copy of the gate to report success.
    # Extract the base copy of the module and point M10 at THAT; the MR's
    # workflow files are scanned only as data.
    M10: base/modules/M10-environments-deploy
  before_script:
    - git fetch --depth=1 origin "$CI_MERGE_REQUEST_DIFF_BASE_SHA"
    - mkdir -p base && git archive "$CI_MERGE_REQUEST_DIFF_BASE_SHA"
        modules/M10-environments-deploy | tar -x -C base
  script:
    # scan the MR's own deploy workflows (data) with the trusted base-tree gate
    - WORKFLOWS_DIR=.gitlab/deploy bun "$M10"/reference/promote-safety/check-promote-safety.ts
    - bun test "$M10"/reference/promote-safety/check-promote-safety.test.ts
    - bun test "$M10"/reference/verified-pointer/check-verified-fresh.test.ts

The verified-pointer watchdog

The decision is provider-neutral and lives in reference/verified-pointer/; what differs per provider is the collector that observes the pointer, the tip’s verification runs and the runner queue, and the two actions, a dispatch and a cancel. Every read in the collector fails closed: an ancestry check or a diff that errors is not “no”, a run listing that fails or is cut short is not “no runs”, and a run status the collector does not know is an error, not “running”. The collector reads only the integration branch’s own verification runs, and observes again when the pointer moved while it read them, since a run that just advanced the pointer would otherwise read as “verified but not moved”.

Verification covers the whole gap

The watchdog’s heal and cancel are safe only when each verification run checks the whole verified..tip range.

ConcernGitHub ActionsGitLab CI
The range a run checksthe change-detection step diffs the pointer against the head (git diff --name-only refs/remotes/origin/verified HEAD, or the change-area resolver run against the pointer), never HEAD~1 HEADthe same diff in the verification job, with the pointer fetched first (git fetch origin verified)
One run at a time, superseded runs dropped`concurrency: { group: verify-${{ github.ref == ‘refs/heads/’ && ''
The heal can start iton: workflow_dispatch beside on: push; the jobs that package and advance run on either event, gated on the integration branch (github.ref == 'refs/heads/<branch>')a pipeline created through the API (POST /projects/:id/pipeline?ref=<branch>) runs the same jobs as a push

GitHub Actions

yaml
# .github/workflows/verified-watchdog.yml — why does the pointer lag?
on:
  schedule: [{ cron: "*/15 * * * *" }]
  workflow_dispatch:
concurrency:
  # Scheduled ticks cover one another; a manual run keeps a group of its own.
  group: verified-watchdog-${{ github.event_name == 'schedule' && 'schedule' || github.run_id }}
  cancel-in-progress: true
permissions:
  contents: read
  actions: write                              # dispatch verification, cancel a stalled run
jobs:
  watchdog:
    runs-on: <a pool other than the one verification runs on>
    timeout-minutes: 10
    env:
      M10: modules/M10-environments-deploy     # where you vendored the module
      VERIFY_WORKFLOW: verify.yml              # the post-merge verification workflow
      BRANCH: <integration branch>
      POINTER: refs/heads/verified             # or refs/tags/verified
      GH_TOKEN: ${{ github.token }}
    steps:
      - uses: actions/checkout@<full-commit-sha>  # v4
        with: { fetch-depth: 0 }
      - name: Observe the pointer, the tip and the queue
        id: observe
        run: |
          set -euo pipefail
          for ATTEMPT in 1 2 3; do
            git fetch --quiet origin "+$POINTER:refs/watchdog/verified" "+refs/heads/$BRANCH:refs/watchdog/tip"
            VERIFIED=$(git rev-parse refs/watchdog/verified); TIP=$(git rev-parse refs/watchdog/tip)
            # Only exit 1 means "not an ancestor" (or "differs" below); any other exit is the check failing.
            rc=0; git merge-base --is-ancestor "$VERIFIED" "$TIP" || rc=$?
            [ "$rc" -le 1 ] || { echo "::error::merge-base exited $rc"; exit 1; }
            ANCESTOR=$([ "$rc" -eq 0 ] && echo yes || echo no)
            echo "ANCESTOR $ANCESTOR" > observation.txt
            # The whole range, against the paths verification builds or tests.
            rc=0; git diff --quiet "$VERIFIED" "$TIP" -- . ':(exclude)docs/' ':(exclude)*.md' || rc=$?
            [ "$rc" -le 1 ] || { echo "::error::git diff exited $rc"; exit 1; }
            if [ "$ANCESTOR" = no ]; then
              :  # A diverged pointer is decided on ancestry and the queue alone: it has no age to read.
            elif [ "$rc" -eq 0 ]; then
              echo "CODE_AHEAD no" >> observation.txt
            else
              echo "CODE_AHEAD yes" >> observation.txt
              # Age from when the oldest code-bearing change the pointer lacks reached the
              # branch, as the forge recorded it: a commit's own timestamp says when it was
              # written, and a fast-forward lands an old commit at once. Arrivals are read
              # newest first back to one the pointer already holds; one whose commit is not
              # in the tip's history (deleted, force-pushed away) is skipped, and a listing
              # that ends before reaching the pointer fails, rather than ageing too young.
              # GitHub's activity log records every push and merge to the branch.
              gh api --paginate "repos/$GITHUB_REPOSITORY/activity?ref=refs/heads/$BRANCH&per_page=100" \
                --jq '.[] | "\(.after)\t\(.timestamp | sub("\\.[0-9]+"; "") | fromdateiso8601)"' > arrivals.tsv
              ARRIVED=; REACHED=no
              while IFS=$'\t' read -r AFTER AT; do
                git cat-file -e "$AFTER^{commit}" 2>/dev/null || continue
                rc=0; git merge-base --is-ancestor "$AFTER" "$VERIFIED" || rc=$?
                [ "$rc" -le 1 ] || { echo "::error::merge-base exited $rc"; exit 1; }
                [ "$rc" -eq 0 ] && { REACHED=yes; break; }
                rc=0; git merge-base --is-ancestor "$AFTER" "$TIP" || rc=$?
                [ "$rc" -le 1 ] || { echo "::error::merge-base exited $rc"; exit 1; }
                [ "$rc" -eq 0 ] || continue
                rc=0; git diff --quiet "$VERIFIED" "$AFTER" -- . ':(exclude)docs/' ':(exclude)*.md' || rc=$?
                [ "$rc" -le 1 ] || { echo "::error::git diff exited $rc"; exit 1; }
                [ "$rc" -eq 0 ] || ARRIVED=$AT
              done < arrivals.tsv
              [ "$REACHED" = yes ] && [ -n "$ARRIVED" ] || { echo "::error::no recorded arrival for the unverified change"; exit 1; }
              echo "UNVERIFIED_AGE_SECONDS $(( $(date -u +%s) - ARRIVED ))" >> observation.txt
              # The tip's verification runs on the integration branch, started by a
              # push or a dispatch: a run of another ref at the same commit has its
              # own concurrency group and skips the advance. Every page is read, and
              # a listing GitHub caps at 1,000 runs fails rather than leaving runs out.
              gh api --paginate "repos/$GITHUB_REPOSITORY/actions/workflows/$VERIFY_WORKFLOW/runs?head_sha=$TIP&branch=$BRANCH&per_page=100" \
                --jq 'if .total_count > 1000 then error("over 1000 runs at the tip") else .workflow_runs[] end' > runs.json
              # The listing shows each run's newest attempt only: read every earlier
              # attempt of a re-run run too, so a success a re-run followed is kept.
              jq -r 'select(.run_attempt > 1) | "\(.id)\t\(.run_attempt)"' runs.json > rerun.tsv
              while IFS=$'\t' read -r RUN N; do
                for ((A = 1; A < N; A++)); do gh api "repos/$GITHUB_REPOSITORY/actions/runs/$RUN/attempts/$A"; done
              done < rerun.tsv > attempts.json
              # Only the statuses and conclusions named here count; any other fails
              # the step. A success in any attempt is sticky; the newest attempt of
              # each run says whether it is still running, and the newest run tells
              # a failure from an aborted run. HEAL_ATTEMPTS counts each dispatched
              # run once, when its newest attempt ended without a verdict.
              jq -rs --arg branch "$BRANCH" '
                def state:
                  if .status == "completed" then
                    {success: "succeeded", failure: "failed", cancelled: "aborted", timed_out: "aborted",
                     skipped: "aborted", stale: "aborted", startup_failure: "aborted"}[.conclusion // ""]
                      // error("unknown conclusion: \(.conclusion)")
                  elif (.status | IN("requested", "queued", "pending", "waiting", "in_progress")) then "running"
                  else error("unknown status: \(.status)") end;
                [.[] | .state = state | select(.head_branch == $branch and (.event | IN("push", "workflow_dispatch")))] as $all
                | [$all | group_by(.id)[] | max_by(.run_attempt)] as $r
                | (if any($r[]; .state == "running") then "running"
                   elif any($all[]; .state == "succeeded") then "succeeded"
                   elif ($r | length) == 0 then "none"
                   else $r | sort_by(.updated_at) | last | .state end) as $v
                | "VERIFICATION \($v)",
                  "HEAL_ATTEMPTS \([$r[] | select(.event == "workflow_dispatch" and .state == "aborted")] | length)"
              ' runs.json attempts.json >> observation.txt
            fi
            # Verification can advance the pointer while its runs are read: observe again.
            git fetch --quiet origin "+$POINTER:refs/watchdog/verified"
            [ "$(git rev-parse refs/watchdog/verified)" = "$VERIFIED" ] && break
            [ "$ATTEMPT" -lt 3 ] || { echo "::error::the pointer moved during three observations"; exit 1; }
          done
          # The runs that can hold the slot: the branch's queued, in-progress and
          # waiting runs, each listing read in full. Only a job still `queued` waits
          # for a runner (a job waiting for an approval is `waiting`, not a stall);
          # a queued run with no jobs yet counts from its last update. A job status
          # outside the known ones fails the step rather than reading as no wait.
          for STATUS in queued in_progress waiting; do
            export STATUS
            gh api --paginate "repos/$GITHUB_REPOSITORY/actions/workflows/$VERIFY_WORKFLOW/runs?branch=$BRANCH&status=$STATUS&per_page=100" \
              --jq 'if .total_count > 1000 then error("over 1000 runs are \(env.STATUS)") else .workflow_runs[] | [.id, .status, .updated_at] | @tsv end'
          done > holders.tsv
          WAIT=0; HOLDER=""
          while IFS=$'\t' read -r RUN STATUS UPDATED; do
            gh api --paginate "repos/$GITHUB_REPOSITORY/actions/runs/$RUN/jobs?filter=latest&per_page=100" --jq '.jobs[]' > jobs.json
            W=$(jq -rs --argjson now "$(date -u +%s)" --arg status "$STATUS" --arg updated "$UPDATED" '
              if any(.[]; .status | IN("requested", "queued", "pending", "waiting", "in_progress", "completed") | not)
              then error("a job status outside the known ones: \([.[].status] | unique)")
              elif length == 0 and $status == "queued" then $now - ($updated | fromdateiso8601)
              else [.[] | select(.status == "queued") | $now - (.created_at | fromdateiso8601)] | max // 0 end' jobs.json)
            if [ "$W" -gt "$WAIT" ]; then WAIT=$W; HOLDER=$RUN; fi
          done < holders.tsv
          echo "QUEUE_WAIT_SECONDS $WAIT" >> observation.txt
          echo "holder=$HOLDER" >> "$GITHUB_OUTPUT"
      - name: Decide
        id: decide
        continue-on-error: true                 # the steps below act; the last one fails the job
        run: bun "$M10"/reference/verified-pointer/check-verified-fresh.ts --max-heal-attempts 3 --output "$GITHUB_OUTPUT" observation.txt
      - name: Cancel the run stalled in the runner queue
        if: steps.decide.outputs.queue == 'stalled'
        env:
          HOLDER: ${{ steps.observe.outputs.holder }}
        run: gh run cancel "${HOLDER:?no run holds the slot}"
      - name: Heal a dropped trigger
        id: heal
        if: steps.decide.outputs.pointer == 'dropped-trigger'
        run: gh workflow run "$VERIFY_WORKFLOW" --ref "$BRANCH"
      - name: Fail on everything a person must see
        # A heal that was dispatched, with a healthy queue, is the one failing verdict that stays green.
        if: steps.decide.outcome != 'success' && !(steps.heal.outcome == 'success' && steps.decide.outputs.queue == 'ok')
        run: exit 1

Each listing is read in full: --paginate follows every page, and a search GitHub caps at 1,000 runs fails the step instead of leaving runs out, as in M13’s queue watchdog. A failed cancel or dispatch fails its own step, and so the job; the job stays green only when the dispatch succeeded. A heal runs as a workflow_dispatch run on the integration branch, which is what HEAL_ATTEMPTS counts, each run once by its newest attempt; a success in an earlier attempt stays a success, so a cancelled re-run cannot turn it into a heal. Once --max-heal-attempts dispatched runs at the same tip have ended without a verdict, the check answers pointer=heal-exhausted and the job fails instead of dispatching again.

GitLab CI

yaml
verified_watchdog:
  rules: [{ if: '$CI_PIPELINE_SOURCE == "schedule"' }]
  tags: [<a runner other than the ones verification uses>]
  timeout: 10m
  variables:
    M10: modules/M10-environments-deploy
    BRANCH: <integration branch>
    POINTER: refs/heads/verified               # or refs/tags/verified
    VERIFY_JOB: <verification job>             # the job whose success lets the pointer advance
    GIT_DEPTH: 0                               # ancestry needs the whole history
  script:
    - |
      set -euo pipefail
      API="$CI_API_V4_URL/projects/$CI_PROJECT_ID"
      api() { curl -fsS --connect-timeout 10 --max-time 60 --header "PRIVATE-TOKEN: $WATCHDOG_TOKEN" "$@"; }
      # Every page of a listing, as one JSON array. A page without the
      # x-next-page header cannot say whether more follow, so it fails.
      list() {
        local page=1; : > pages.json
        while [ -n "$page" ]; do
          api -D headers.txt "$API/$1&per_page=100&page=$page" >> pages.json
          grep -qi '^x-next-page:' headers.txt || { echo "no x-next-page header: $1" >&2; exit 1; }
          page=$(awk -F': *' 'tolower($1) == "x-next-page" { sub(/\r$/, "", $2); print $2 }' headers.txt)
        done
        jq -s 'if all(.[]; type == "array") then add // [] else error("not a listing") end' pages.json
      }
      # A shallow clone hides ancestors, and is-ancestor would answer "no".
      [ "$(git rev-parse --is-shallow-repository)" = false ] || git fetch --quiet --unshallow origin
      for ATTEMPT in 1 2 3; do
        git fetch --quiet origin "+$POINTER:refs/watchdog/verified" "+refs/heads/$BRANCH:refs/watchdog/tip"
        VERIFIED=$(git rev-parse refs/watchdog/verified); TIP=$(git rev-parse refs/watchdog/tip)
        # Only exit 1 means "not an ancestor" (or "differs" below); any other exit is the check failing.
        rc=0; git merge-base --is-ancestor "$VERIFIED" "$TIP" || rc=$?
        [ "$rc" -le 1 ] || { echo "merge-base exited $rc" >&2; exit 1; }
        ANCESTOR=$([ "$rc" -eq 0 ] && echo yes || echo no)
        echo "ANCESTOR $ANCESTOR" > observation.txt
        rc=0; git diff --quiet "$VERIFIED" "$TIP" -- . ':(exclude)docs/' ':(exclude)*.md' || rc=$?
        [ "$rc" -le 1 ] || { echo "git diff exited $rc" >&2; exit 1; }
        if [ "$ANCESTOR" = no ]; then
          :  # A diverged pointer is decided on ancestry and the queue alone: it has no age to read.
        elif [ "$rc" -eq 0 ]; then
          echo "CODE_AHEAD no" >> observation.txt
        else
          echo "CODE_AHEAD yes" >> observation.txt
          # Age from when the oldest code-bearing change the pointer lacks reached the
          # branch, as the forge recorded it: a commit's own timestamp says when it was
          # written, and a fast-forward lands an old commit at once. Arrivals are read
          # newest first back to one the pointer already holds; one whose commit is not
          # in the tip's history (deleted, force-pushed away) is skipped, and a listing
          # that ends before reaching the pointer fails, rather than ageing too young.
          # GitLab records every push to the branch, a merge's included, as a push
          # event. Events start two days before the pointer's commit was written,
          # which no arrival after it can precede but by clock skew. A push of more
          # branches than the instance's push-event limit is one bulk event that
          # names none of them: one met before the pointer is reached may hide the
          # branch's arrival, so it fails rather than ageing too young.
          SINCE=$(jq -rn --argjson t "$(git log -1 --format=%ct "$VERIFIED")" '$t - 172800 | strftime("%Y-%m-%d")')
          list "events?action=pushed&after=$SINCE" | jq -r --arg branch "$BRANCH" '.[]
            | select(.push_data.ref_type == "branch" and (.push_data.ref == $branch or .push_data.ref == null))
            | "\(if .push_data.ref == null then "BULK" else .push_data.commit_to end)\t\(.created_at | sub("\\.[0-9]+"; "") | fromdateiso8601)"' > arrivals.tsv
          ARRIVED=; REACHED=no
          while IFS=$'\t' read -r AFTER AT; do
            [ "$AFTER" != BULK ] || { echo "a bulk push event may hide the branch's arrival" >&2; exit 1; }
            git cat-file -e "$AFTER^{commit}" 2>/dev/null || continue
            rc=0; git merge-base --is-ancestor "$AFTER" "$VERIFIED" || rc=$?
            [ "$rc" -le 1 ] || { echo "merge-base exited $rc" >&2; exit 1; }
            [ "$rc" -eq 0 ] && { REACHED=yes; break; }
            rc=0; git merge-base --is-ancestor "$AFTER" "$TIP" || rc=$?
            [ "$rc" -le 1 ] || { echo "merge-base exited $rc" >&2; exit 1; }
            [ "$rc" -eq 0 ] || continue
            rc=0; git diff --quiet "$VERIFIED" "$AFTER" -- . ':(exclude)docs/' ':(exclude)*.md' || rc=$?
            [ "$rc" -le 1 ] || { echo "git diff exited $rc" >&2; exit 1; }
            [ "$rc" -eq 0 ] || ARRIVED=$AT
          done < arrivals.tsv
          [ "$REACHED" = yes ] && [ -n "$ARRIVED" ] || { echo "no recorded arrival for the unverified change" >&2; exit 1; }
          echo "UNVERIFIED_AGE_SECONDS $(( $(date -u +%s) - ARRIVED ))" >> observation.txt
          # The verification job of each pipeline a push, a heal (api) or a person
          # (web) started at the tip on the branch, retried jobs included, so a
          # success a retry followed is kept. This watchdog's own pipeline and
          # other scheduled ones are not verification. A push or web pipeline
          # without the job does not count; a heal without it is a heal that ran
          # no verification, aborted once the pipeline is no longer active.
          list "pipelines?sha=$TIP&ref=$BRANCH" | jq -r --argjson self "$CI_PIPELINE_ID" \
            '.[] | select(.id != $self and (.source | IN("push", "api", "web"))) | [.id, .source, .status, .created_at] | @tsv' > candidates.tsv
          : > runs.json
          while IFS=$'\t' read -r P SOURCE STATUS CREATED; do
            list "pipelines/$P/jobs?include_retried=true" | jq --arg job "$VERIFY_JOB" --arg source "$SOURCE" \
              --argjson pipeline "$P" --arg status "$STATUS" --arg created "$CREATED" '
              [.[] | select(.name == $job) | {pipeline: $pipeline, created_at, status, source: $source}]
              | if length > 0 or $source != "api" then .
                elif $status | IN("created", "waiting_for_resource", "preparing", "pending", "running", "scheduled")
                then [{pipeline: $pipeline, created_at: $created, status: "created", source: $source}]
                else [{pipeline: $pipeline, created_at: $created, status: "skipped", source: $source}] end' >> runs.json
          done < candidates.tsv
          # Only the statuses named here count; any other fails the job. A success
          # in any job, retried or not, is sticky; the newest job of each pipeline
          # says whether it is still running, and the newest of those tells failed
          # from canceled or skipped (aborted). HEAL_ATTEMPTS counts each heal
          # pipeline once, when its newest job ended without a verdict.
          jq -rs '
            def state:
              if IN("created", "waiting_for_resource", "preparing", "pending", "running", "scheduled", "canceling") then "running"
              elif . == "success" then "succeeded" elif . == "failed" then "failed"
              elif IN("canceled", "skipped") then "aborted"
              else error("unknown job status: \(.)") end;
            [(add // [])[] | .state = (.status | state)] as $all
            | [$all | group_by(.pipeline)[] | max_by(.created_at)] as $r
            | (if any($r[]; .state == "running") then "running"
               elif any($all[]; .state == "succeeded") then "succeeded"
               elif ($r | length) == 0 then "none"
               else $r | max_by(.created_at) | .state end) as $v
            | "VERIFICATION \($v)",
              "HEAL_ATTEMPTS \([$r[] | select(.source == "api" and .state == "aborted")] | length)"
          ' runs.json >> observation.txt
        fi
        # Verification can advance the pointer while its runs are read: observe again.
        git fetch --quiet origin "+$POINTER:refs/watchdog/verified"
        [ "$(git rev-parse refs/watchdog/verified)" = "$VERIFIED" ] && break
        [ "$ATTEMPT" -lt 3 ] || { echo "the pointer moved during three observations" >&2; exit 1; }
      done
      # The longest a pending verification job on the branch has waited for a runner.
      list "jobs?scope=pending" | jq --arg job "$VERIFY_JOB" --arg ref "$BRANCH" \
        '[.[] | select(.name == $job and .ref == $ref) | {id, wait: (.queued_duration // error("no queued_duration on job \(.id)"))}]' > pending.json
      echo "QUEUE_WAIT_SECONDS $(jq -r 'map(.wait) | max // 0 | floor' pending.json)" >> observation.txt
      HOLDER=$(jq -r 'max_by(.wait) | .id // empty' pending.json)
      rc=0; bun "$M10"/reference/verified-pointer/check-verified-fresh.ts --max-heal-attempts 3 --output verdict.env observation.txt || rc=$?
      [ "$rc" -le 1 ] || exit "$rc"              # the check could not decide
      if grep -qx 'queue=stalled' verdict.env; then
        api -X POST "$API/jobs/${HOLDER:?no job holds the slot}/cancel" > /dev/null
      fi
      HEALED=no
      if grep -qx 'pointer=dropped-trigger' verdict.env; then
        api -X POST "$API/pipeline?ref=$BRANCH" > /dev/null
        HEALED=yes
      fi
      # A heal that was dispatched, with a healthy queue, is the one failing verdict that stays green.
      [ "$rc" -eq 0 ] || { [ "$HEALED" = yes ] && grep -qx 'queue=ok' verdict.env; } || exit 1
  artifacts:
    reports: { dotenv: verdict.env }

$WATCHDOG_TOKEN is a project access token with api scope, since the job token cannot cancel jobs or create pipelines. The script is one bash block under set -euo pipefail, so a failed read, cancel or dispatch ends the job red, and the job stays green only after a dispatch the API accepted. Every listing follows x-next-page to its last page, and every request carries a connect and a total timeout inside the job’s own timeout. A heal creates an api pipeline on the branch, which is what HEAL_ATTEMPTS counts, each pipeline once whatever its retries, and one that finished without the verification job counts as ended without a verdict: once --max-heal-attempts of them at the same tip have ended without a verdict, the check answers pointer=heal-exhausted and the job fails instead of dispatching again. The verdict file is a dotenv report so a later job can read queue and pointer.

Environment hygiene

The rules are provider-neutral; what differs is where a reaper’s opt-in lives, how the gap report is triggered, and how a currency step removes a cell from a matrix.

Reapers per created resource

ResourceExpiry and owner written at creationReaper
Preview deployment per pull request (Cloudflare Pages, Vercel, Netlify, Render)the pull request is the owner; the host lists deployments by agea weekly scheduled workflow with workflow_dispatch inputs keep (newest N per project) and dry_run; it pages through the host’s deployment list sorted by creation, deletes beyond keep oldest first, and fails on an API error rather than reading it as an empty list. Hosts cap deployments per project, and a project at the cap stops publishing
Ephemeral environment (a Kubernetes namespace per branch or run)an annotation on the namespace, <org>/expires-at: <ISO 8601, now plus the lease>, and an owner label, written by the spawnera CronJob or scheduled workflow that deletes namespaces whose annotation has passed, and refuses any namespace without the annotation
Test tenant or organization a scenario run createdthe run’s purpose and bot identity, recorded by the create calla scheduled janitor matrixed per environment and purpose, each cell authenticating as its own bot identity so it can only ever act on its own; --dry-run unless opted in
Per-worktree database namespacea schema comment or registry row with owner and expiry (M12’s reference)the same reference’s decision, run by each owner; the drop commands are in M12’s mappings
Scratch directories and processes a test startedthe test runner’s per-process scope (M14)the scope’s exit handler removes its subtree; a host sweep reaps by the scope’s prefix what a killed process left

The opt-in, per provider:

ConcernGitHub ActionsGitLab CI
Report by default, act on opt-in`env: APPLY: ${{ (github.event_name == ‘schedule’ && vars._AUTO_REAP == ‘true’)
Refuse productionthe reaper’s own command refuses the production target before anything is rendered, and the production environment’s protection admits no reaper workflowthe production environment: is protected, and the reaper job carries rules: - if: $CI_ENVIRONMENT_NAME == "production" with when: never
Review apps with a built-in reapernone built in: the scheduled sweep aboveenvironment: { on_stop: stop_review, auto_stop_in: 1 week } stops a review app when its lease passes; the stop job is the reaper

The promotion gap

ConcernGitHub ActionsGitLab CI
When it runson: schedule daily, on: push to every pointer branch (verified, the release branch, a manifests branch that pins a deploy), and workflow_dispatch with optional ref overrides; concurrency: { group: promotion-gap, cancel-in-progress: true } collapses rapid pushes, since a later run reads a superseta scheduled pipeline, with both rules on the report job: `rules: [{ if: ‘$CI_PIPELINE_SOURCE == “schedule”’ }, { if: ‘$CI_COMMIT_BRANCH =~ /^(verified
Reading the refsfetch-depth: 0, then git fetch origin <pointer>... for each pointer; a pointer that is a pin (a commit written into a manifest) is resolved from that commit firstthe same fetch in the job
Publishingthe report to $GITHUB_STEP_SUMMARY, the JSON as an artifact (actions/upload-artifact, retained a month), and the count to the metrics backend; a tracker document updated in place is optional and keyed by a fixed title so the update is idempotentthe report as a job artifact with expose_as, the count to the metrics backend

Environment currency

ConcernGitHub ActionsGitLab CI
The floora step runs git log -1 --format=%H -- <dependency paths> over the check’s dependency list and fails closed when a path no longer exists or the log is emptythe same step in a .pre stage job
The deployed versionread from the environment’s pin: the sha= token in the manifests branch’s head commit, or the identity endpoint the post-deploy identity check readsthe same
Removing the cellthe currency job outputs envs as a JSON list of the environments that are current, written with jq -c so it is always valid JSON; the check job uses strategy: { matrix: { env: ${{ fromJSON(needs.currency.outputs.envs) }} } }, so a stale environment has no cell at all (matrix is not available in a job-level if:, so the cell cannot be skipped there, and a skipped cell would read as green anyway). Actions rejects an empty matrix, so the check job’s own if:, which is evaluated before the matrix expands, also requires needs.currency.outputs.envs != '' and != '[]': with no current environment the check job is skipped and the currency job’s report says whythe check job’s parallel: matrix is generated by the currency job into a child pipeline (trigger: { include: { artifact: matrix.yml, job: currency } }), so a stale environment appears in no cell
Not taking the rest downthe check job runs with if: ${{ !cancelled() && needs.currency.outputs.envs != '' && needs.currency.outputs.envs != '[]' }}: a failure inside the currency job after it wrote envs (its own checkout, its own timeout) still lets the environments it emitted run, since a job’s outputs keep what its steps wrote before the failure; a currency job that failed before writing envs leaves it empty, so the check job is skipped and the failed currency job is the red signal; a cancelled workflow run stops itthe currency job is not allowed to fail, so its failure stays the pipeline’s red signal, and it has artifacts: { paths: [matrix.yml], when: always }. Its first step writes a matrix.yml holding one job that only reports “no environment confirmed current” (a child pipeline needs at least one job), and it rewrites the file after each environment it confirms, so a failure part-way leaves the environments already confirmed. GitLab uploads no artifacts from a job that times out, when: always included, so the confirmation runs under timeout a margin shorter than the job’s own (timeout 25m <confirm> in a job with timeout: 30m): a confirmation that runs long fails the script instead, and the upload still happens. The trigger job has needs: [currency] and when: always, so it runs on whichever file was uploaded even when the currency job failed; optional: true would only cover a currency job absent from the pipeline

CI providers — the four stages + the verified pointer

Any provider works; the four stages are just workflows keyed on different triggers, and the verified pointer is a plain git ref (a branch or tag) the verify stage advances and the deploy stage reads.

ProviderStage 1 (PR gates)Stage 2 (verify → advance pointer)Stages 3–4 (deploy / promote gate)
GitHub Actionson: pull_requeston: push to default branch; final step force-updates refs/tags/verifieddeploy job on verified update; environment: with required reviewers gates prod
GitLab CImerge-request pipelinedefault-branch pipeline; final job moves the verified refmanual (when: manual) job in a protected environment:
Jenkins / Buildkite / CircleCI / othersper-PR pipelinedefault-branch pipeline advancing a verified tagmanual approval step + protected deploy credentials for prod

The pointer is deliberately a git ref, not a database row: it is inspectable (git log verified), diffable, and survives a CI outage. Advance it with a force-update of a tag (git tag -f verified <sha> && git push --force origin verified) or a fast-forward of a verified branch.

Preview-environment platforms (options)

Disposable per-PR environments. Any of these is one option among several — pick by where your app already runs; none is required.

OptionFit
Vercel / Netlify / Cloudflare Pages preview deploysfrontend / static / edge apps — a preview URL per PR out of the box
Render / Railway / Heroku review appsfull-stack apps with a managed backend + database branch per PR
Fly.io / a Kubernetes namespace-per-PR / Argo CD ApplicationSetcontainer apps where you want the preview on the same platform as prod
A platform-as-a-service ephemeral environment (self-hosted spawner)when you already run the infra and want the preview identical to prod

Whatever the platform, keep the two properties: created on PR open and destroyed on PR close (cattle, not pets), and seeded by the test-data factory so the preview has realistic data.

Test-data factory (options)

The contract is seeded + tenant-isolated + resettable; the implementation is yours. Common building blocks:

ConcernOptions
Seeda seed script / factory library (per-language: factory-bot-style builders, fixtures loaders) invoked with a target tenant id
Tenant isolationa schema/namespace per run, a per-PR database branch, or a tenant/org column scoped per environment
Resettransaction rollback per test, a snapshot restore, or a factory reset --tenant <id> command that truncates + reseeds

Keep it a factory (programmatic, on-demand), not a checked-in dump: a static snapshot drifts and becomes another generated artifact to keep fresh.

Promotion gates (environment protection / manual approval)

Stage 4 must be a human action that cannot auto-fire. The gate is a platform setting, not a script — the promote-safety lint checks that the wiring (a manual trigger or an environment: reference) exists; the protection rule itself lives in provider config.

ProviderManual-gate mechanism
GitHuba deployment environment with required reviewers and/or a wait timer; workflow_dispatch for the trigger
GitLaba protected environment + a when: manual job; deploy freezes / approval rules
Others (Jenkins / Buildkite / Argo CD)a manual approval / block step, protected prod credentials, or a sync gate requiring sign-off

The human checkpoint (promote to production) is enforced by these settings plus the HITL boundary shared with M7 — a bot must not hold it.

Promotion execution

The promotion-execution invariants — the gated commit is the shipped commit, build once, post-deploy identity, release state off the source line — map onto these mechanisms.

Pass the gated commit from job to job

ProviderFirst job resolves and outputsLater jobs take it
GitHub Actionsoutputs: { sha: ${{ steps.pin.outputs.sha }} }, with echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" after checking out the pointerneeds: gate and ref: ${{ needs.gate.outputs.sha }} in actions/checkout; the same expression in every command that names the commit
GitLab CIwrite GATED_SHA=<sha> to a dotenv file (plain NAME=value lines GitLab turns into variables of later jobs) declared as artifacts: reports: dotenv:needs: [gate]; the variable $GATED_SHA is set in the later job
Othersa pipeline output or artifact holding the commitread it; never git fetch origin <branch> again
yaml
# GitHub Actions — the shape the promote-safety lint's rule (c) accepts
jobs:
  gate:
    runs-on: ubuntu-latest
    outputs:
      sha: ${{ steps.pin.outputs.sha }}
    steps:
      - uses: actions/checkout@<full-commit-sha>   # v4
        with: { ref: verified, persist-credentials: false }   # gate code from the trusted ref
      - id: pin
        run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
      - run: ./gates/check-promotion.sh            # runs the copy checked out above
  deploy-production:
    needs: gate
    environment: production
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@<full-commit-sha>   # v4
        with: { ref: "${{ needs.gate.outputs.sha }}" }
      - run: ./deploy --target production --commit "${{ needs.gate.outputs.sha }}"

Run from the trusted ref

The trusted ref is the verified pointer. A GitHub workflow_dispatch run executes the workflow file as it is on the ref chosen in “Use workflow from” (or gh workflow run <file> --ref <ref>); the default is the default branch. Dispatch promotions with --ref verified, and make that the default of any script or skill that starts one. Check the gate’s code out from verified explicitly (as above), never from github.ref. GitLab runs a manual job from the pipeline it belongs to, so start the promotion from a pipeline on the trusted ref.

A default is not enforcement: an operator can still pick another branch. Make the platform refuse it:

ProviderOnly the trusted ref reaches production
GitHub Actionsthe production environment’s deployment branches and tags rule set to selected refs, listing only verified (a tag rule when the pointer is a tag); a job naming the environment from any other ref fails before it runs
GitLab CIprotected variables alone do not restrict the ref: every pipeline on any protected ref (a protected main too) receives them. Make verified a protected tag or branch and release production’s credentials only to it, for example through an ID token (id_tokens:) whose cloud-side trust policy admits only the claims ref = verified, ref_protected = true and environment = production; a protected environment limits who may deploy

Serialize promotions without dropping one

ProviderBuilt-in serializationWhat it does to a waiting requestUse
GitHub Actionsconcurrency: { group: <key>, cancel-in-progress: false }at most one run and one pending run per group: a newer pending run cancels the older pending one, whatever its inputskey the group per run (group: promote-production-${{ github.run_id }}) so none is dropped, and serialize with a lock job before the first change: it lists the workflow’s active runs, one query per active status (queued, in_progress, waiting for an environment approval, requested, pending), each read in full (gh api --paginate "repos/<owner>/<repo>/actions/workflows/<file>/runs?status=<status>&per_page=100"; a single page holds only the newest 30), and proceeds once its own run id is the smallest; a failed query, or a list that does not contain its own run, fails the job rather than proceeding. It also fails a re-run (github.run_attempt above 1): a re-run keeps its original, lower run id, so it would count itself earliest while a later promotion is changing production; start a new promotion instead. Repeat the check (fail, don’t wait) just before the migration
GitLab CIresource_group: productionjobs in the group queue and run one at a time; the process mode oldest_first runs them in pipeline order (set through the Resource Groups API, PUT /projects/:id/resource_groups/:key with process_mode=oldest_first, not in .gitlab-ci.yml). The group is held per job: between two jobs of one promotion, a job of another promotion can take ithold the group across the whole mutating sequence, never on each job separately: put it on the one job that runs every step changing production (migration through the identity check), or on a trigger job (trigger: with strategy: depend) that runs those steps as a downstream pipeline, which keeps the group until that pipeline finishes; set the process mode to oldest_first
Argo CD / Fluxone controller reconciles one targetthe newest commit on the target ref winsserialize the writes to the release-state ref (above), not the sync

Build once, promote by digest

ConcernMechanism
Address by digesta container image reference <registry>/<name>@sha256:<64 hex>; deployment manifests carry the digest, never a tag
Resolve a digestcrane digest <ref>, skopeo inspect --format '{{.Digest}}' docker://<ref>, docker buildx imagetools inspect <ref>, gcloud artifacts docker images describe <ref> --format='value(image_summary.digest)', aws ecr describe-images --query 'imageDetails[0].imageDigest'
Promote without rebuildingre-tag or copy the verified digest: crane tag <ref>@<digest> production, crane copy, skopeo copy, gcloud artifacts docker tags add, aws ecr put-image with the existing manifest
Reject a tag where a digest belongsthe code that renders deployment manifests refuses an image reference without @sha256:; a check over rendered manifests does the same
Web-app bundlesupload the verified bundle’s bytes (a build artifact keyed by commit) to each environment’s static host; do not run the build again at promotion

Runtime configuration. A build tool that inlines environment values at compile time (Vite’s import.meta.env, webpack’s DefinePlugin, Next.js’s NEXT_PUBLIC_*) makes every environment’s bundle different. Move those values to deploy time:

ArtifactPer-environment settings supplied at deploy time
Single-page web appa small env.js per environment, loaded by <script src="/env.js"> before the bundle, setting window.__ENV__; served uncached (Cache-Control: no-store, and a matching edge-cache rule on a content delivery network) while the content-hashed bundle files stay long-cached; a separate script file keeps a content security policy free of unsafe-inline
Containerenvironment variables, a Kubernetes ConfigMap / Secret, or a mounted config file; the image stays the same
Serverless functionthe platform’s environment configuration per stage

Keep the build’s own identity (its commit) compiled in: it says which code is running, and error trackers group releases by it.

GitOps and the release-state ref

ToolReadsProduction gate
Argo CDan Application’s spec.source.repoURL + targetRevision (the release-state ref) + pathno syncPolicy.automated on production: an operator runs argocd app sync <app>; argocd app wait <app> --sync --health waits for it
Fluxa GitRepository (spec.ref.branch: the release-state ref) and a Kustomization or HelmRelease over itthe gated promotion is the only writer of the release-state ref, so publishing to it is the gate and the Kustomization may reconcile it automatically; or keep it spec.suspend: true and have the promotion run flux resume kustomization <name> (which applies and waits), then flux suspend kustomization <name> again. A flux reconcile alone is not a gate: an unsuspended Kustomization applies new revisions on its own, and a suspended one applies nothing until resumed

Rendered manifests on their own ref. CI renders the environment’s manifests (Helm, Kustomize, cdk8s or another generator, to plain YAML with image digests filled in) and commits them to a dedicated ref (for example a release-state branch with no shared history with the source) that the controller reads. The source line’s release pointer then only ever fast-forwards to the gated commit, once the identity check has passed. git merge --ff-only of an older commit succeeds as a no-op, so refuse a stale promotion before it changes anything with git merge-base --is-ancestor origin/<release-branch> "$GATED_SHA". Run it once the promotion holds the lock, just before its first change, against a freshly fetched pointer: an earlier promotion may have advanced the pointer while this one waited. Confirm the result when advancing: git merge --ff-only "$GATED_SHA" && test "$(git rev-parse HEAD)" = "$GATED_SHA" && git push origin HEAD:<release-branch>.

One writer, and protection that admits it.

ForgeWriter identityProtection on a machine-written ref
GitHuba GitHub App installed on the one repository, its token minted inside the writing job only (actions/create-github-app-token)classic protection: “Restrict who can push” listing that App, no “Require a pull request before merging” (with zero approvals it still blocks a direct push); rulesets: “Restrict updates” with the App on the bypass list, no pull-request rule; force pushes and deletion blocked
GitLaba project access token or bot userprotected branch: “Allowed to push and merge” = that identity, “Allowed to merge” = no one

A test over the workflow files can hold the identity’s scope: the writer’s credential names appear in the writing job and in no other job or workflow-level block.

Post-deploy identity

The conditions, in this order, each under a deadline:

StepKubernetesOther platforms
1. The live spec reports the promoted identitypoll kubectl get deploy/<name> -o jsonpath='{.spec.template.spec.containers[0].image}' until it equals <image>@sha256:<digest> and .status.observedGeneration ≥ .metadata.generation, failing once a deadline passes (for example 10 minutes); only then is step 2 about the new versionthe platform’s release or version endpoint reports the digest or commit (a static host’s build-info file, a serverless function’s version), polled under the same deadline
2. Rollouts are readykubectl rollout status deploy/<name> --timeout=10m, then every running pod’s .status.containerStatuses[*].imageID carries the digest; argocd app wait --health adds the controller’s viewthe platform’s deployment status reaches its final ready state
3. A readiness check of the critical dependencies passescurl -fsS --connect-timeout 5 --max-time 10 --retry 8 --retry-max-time 120 https://<host>/ready, where /ready exercises what the application cannot serve without: for an application with a database, a query against it (a liveness check that answers without it does not count). --retry alone bounds attempts, not time: a server that accepts the connection and stalls holds the promotion until --max-time ends the attemptthe same endpoint; a static site’s check fetches the deployed entry page and its runtime configuration file

A permissions error reading the live state is a failure of the check, not a reason to keep waiting: report it at once rather than letting it time out as “not synced yet”.

A manifest of what deployed. The deploy run uploads a small file (for GitHub, actions/upload-artifact of a deploy-manifest.json) listing each part it could deploy, whether it did this run, its identity and its rollout result. A downstream workflow (on: workflow_run) downloads it with actions/download-artifact with run-id: ${{ github.event.workflow_run.id }} and github-token (another run’s artifacts need a token, and the job needs permissions: actions: read), checks the triggering run’s branch and event, and acts only on the parts that deployed, validating any commit it reads before checking it out.

External preconditions

The registry contract separates an intended-state assertion from the provider-specific read. Only branch protection ships as a check kind; the other rows describe integration points for a repository’s operated checks, not implemented kinds.

StateProvider mappingWhat the consuming identity must establish
Branch protectionGitHub classic protection plus every applicable repository and organization ruleset, through the reference runnerRequired checks, pull-request and history controls hold together; the named writer can push through every blocker without bypassing required history protection
Identity-provider realmKeycloak OpenID Connect discovery and signing keysAuthenticate as the consuming service identity, verify the token signature against discovered keys, and assert the claims the consumer authorizes; merely finding a user is insufficient
Cloud secretsGoogle Cloud Secret Manager version accessRead a version under the consuming workload identity without printing its value; distinguish an authorized absence from denied or ambiguous access
Certificate pinsThe consumer’s configured trust bundle and its deployed peer’s certificateValidate the certificate chain and hostname, then compare the live certificate or key fingerprint to the intended pin; a stored fingerprint alone is no live observation
Storage lifecycleThe provider’s bucket lifecycle APICompare live lifecycle rules with declared retention intent under the consuming identity; never change rules in the checker

The GitHub reader needs Administration read to inspect classic branch protection. GitHub reveals ruleset bypass actors only to callers with write access to the ruleset; an App therefore needs Administration write to establish its bypass access. The checker still sends only read requests. A read-scoped token leaves withheld bypass lists unknown and non-green. The App installation must approve any added permission. Use a separate issue identity for M11 reconciliation, so the reader needs no issue-write permission and the checker performs no host writes. Jira, Linear and other trackers can implement the same port; only GitHub Issues ships here.

Source: modules/M10-environments-deploy/mappings.md

4 · Statuswhat is built, and what is left out on purpose

Runnable form

Jig’s plugin carries the github-actions skill, which reviews a change to a repository’s workflows against its documented CI architecture; CI-ARCHITECTURE.md is the shape it recognises when the repository names no document of its own (github_actions.conventions_doc).

What the module provides

PieceWhat it is
templates/CI-ARCHITECTURE.mdThe copyable four-stage contract (PR gates, post-merge verification, deploy, promotion), with the preview-environment and test-data-factory contracts, and the rule for a pipeline index: derived or gated, never hand-kept
templates/pipeline.example.yamlA provider-neutral spine of the four stages
reference/verified-pointer/The watchdog: decides why the verified pointer lags (nothing to verify, verifying, blocked, within grace, a dropped trigger to heal, heals exhausted, ran but stale, diverged) and whether a verification run is stalled waiting for a runner; or, from two numbers, whether the pointer lags at all
reference/promote-safety/The lint that fails a production deploy that can fire on its own, ships a mutable ref, or looks its commit up again by name
reference/promotion-gap/The promotion gap report: the work items the commits between two environment pointers name, from git ancestry, with a bound and a JSON form for the metric
mappings.mdCI providers, preview-environment platforms, promotion gates, the promotion-execution recipes (digest pinning, runtime configuration, GitOps tools, serialization, rollout and identity checks), and the environment-hygiene wiring (reapers per resource, the gap report’s triggers, the currency matrix)
maturity criteriaThe criteria the audit skill scores

Each reference gate is a Bun script with a self-test and fixtures; the watchdog and the promotion-gap report import the repository’s lib/ helpers, so each runs from a pinned Jig checkout or with lib/ vendored beside it.

Left out by design

  • A preview-environment spawner and a test-data factory. Both are product- and infrastructure-specific code (a particular host, database and tenant model), not a portable mechanism. The module gives their contracts (disposable environments; seeded, tenant-isolated, resettable data) and catalogues platform options in mappings.md; the implementation belongs to each repository’s stack.
  • Delivery telemetry. Gate-pass dashboards and deploy metrics belong with M11.
  • Where each suite runs, and what it costs. Per change, after merge, on a schedule or on demand is decided by M13 pipeline economy’s placement table, which this module’s verified pointer feeds: a suite runs after merge when the pointer waits for it.
  • A reaper per platform, and a currency script. A reaper’s drop is a call into one host’s or database’s API, and a currency step’s dependency paths are one check’s own, so the module states the rules, gives the decisions that are portable (which namespaces to drop, which items wait) and catalogues the per-platform forms in mappings.md.
  • A rollout-assertion script. The post-deploy identity check depends on the platform (a Kubernetes cluster, a serverless host, a static-file host), so the module states its conditions and their order, and mappings.md gives the commands per platform.

Future

  • A recovery script for a diverged pointer. The watchdog names the back-merge; a script that plans it (which commits diverged, whether any reached production), opens it as a pull request once the operator confirms containment, and merges it only as a merge commit pinned to that head, is validated in a working repository and not yet brought here.
  • A held promotion lock. The lock step described above waits until its run is the earliest active promotion, refuses re-runs and re-checks before the migration, so it depends on run ids rising with each new promotion. A lock held for the whole mutating section, or a durable queue, would not depend on that order, and is not yet proven in a working repository.
  • Verifying what runs at admission. Signing the promoted artifact and having the platform refuse anything unsigned (image signatures checked at admission, signed commits required on the rendered-state ref) would prove the digest that runs is the one verified. It is not yet validated in a working repository.