diff --git a/.baseline/product/deployment.md b/.baseline/product/deployment.md new file mode 100644 index 0000000..eec284b --- /dev/null +++ b/.baseline/product/deployment.md @@ -0,0 +1,7 @@ +# {{ .reponame }} — live deployment manifest + +> Not rendered yet. The bootstrap's `08-docs` phase probes every live URL and +> regenerates this file from what answered — the workspace, the URLs and their +> status, and the secrets inventory by name. Until then, nothing here claims +> the product is live. The operating contract is +> [operations.md](operations.md). diff --git a/.github/workflows/baseline.yml b/.github/workflows/baseline.yml index 0446365..0a3ce2d 100644 --- a/.github/workflows/baseline.yml +++ b/.github/workflows/baseline.yml @@ -51,11 +51,11 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - - name: Contract tests (manifest, phases, coverage, rebrand) + - name: Contract tests (manifest, phases, coverage, rebrand, retouch, bootstrap-defer, fleet-stubs, pen-reset) run: | set -euo pipefail python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml - for t in manifest phases coverage rebrand; do + for t in manifest phases coverage rebrand retouch bootstrap-defer fleet-stubs pen-reset; do echo "── $t" bash "testing/$t.test.sh" done @@ -81,15 +81,15 @@ jobs: - uses: actions/checkout@v6 - uses: sourceplane/orun-action@v1.2.0 with: - # The bootstrap floor (BOOTSTRAP.md), not the product lane pin: the - # blueprint's `orun.run/watch@v1` `sha:` exists from v2.58.5, and an - # older CLI refuses the whole document at parse; v2.58.6 is where a - # landing's check wait covers the whole PR run; v2.58.7 knows - # orun.doctor/check@v1's `githubOwner`; v2.58.8 reads - # orun.secrets/exists@v1's `environments`; v2.58.10 defers a probe - # about a project the bootstrap has not created yet; v2.58.11 fills - # an input declared `from: workspace`. - version: v2.58.11 + # The bootstrap floor (BOOTSTRAP.md), not the product lane pin. It + # used to be v2.58.11 — the first CLI that could read this document + # at all (`orun.run/watch@v1`'s `sha:`, a landing's whole-run check + # wait, `githubOwner`, `environments`, a deferred project probe, and + # `from: workspace`). It is v2.88.0 now, for three keys an older CLI + # refuses at parse: `hooks.preInstantiate[].background`, + # `orun.pr/land@v1`'s `checks: local`, and + # `orun.integrations/reconcile@v1`'s `secrets:` list (v2.87.0). + version: v2.88.0 - name: repo-blueprint.yaml, read by the pinned CLI run: | set -euo pipefail diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1850109..da2accc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,19 +19,39 @@ permissions: contents: read packages: write id-token: write + # A lane of several jobs posts one check run per job, named by the job's + # check title, so branch protection sees the same names as before lanes. + checks: write jobs: plan: runs-on: ubuntu-latest outputs: - job-matrix: ${{ steps.matrix.outputs.job-matrix }} + lane-matrix: ${{ steps.matrix.outputs.lane-matrix }} steps: - uses: actions/checkout@v6 with: fetch-depth: 0 + # A TREE THAT NAMES NO WORKSPACE PLANS NOTHING, AND SAYS SO HERE. + # `ws_SET_ME` is what 01-scaffold's `orun-workspace` hook writes when the + # build resolved no workspace: every remote op of a plan here would be + # refused, and the refusal arrives as a secret-resolution error in each + # lane, an hour of runner time later, naming nothing an owner can act on. + # So the one check that can be made from the tree is made first. + # + # There is no "never linked" placeholder branch here, as there is in the + # Cloudflare-only baselines: this repository names a real workspace and + # every product's bootstrap writes its own, so `ws_SET_ME` is the only + # unset state reachable, and it is an error rather than a skip. + - id: linked + run: | + if grep -Eq '^[[:space:]]*workspace:[[:space:]]*ws_SET_ME[[:space:]]*$' intent.yaml; then + echo "::error title=Orun workspace unset::intent.yaml names no Orun workspace (ws_SET_ME). The build that created this repository resolved none. Set execution.state.workspace to your workspace id (orun cloud link, or the console's Git Repos), and re-run." >&2 + exit 1 + fi - uses: sourceplane/orun-action@v1.2.0 with: - version: v2.56.2 + version: v2.78.4 - env: # Surface the best-effort catalog auto-sync (execution.state.autopushCatalog). # A successful push prints "✓ pushed catalog …"; ORUN_VERBOSE also makes @@ -49,9 +69,14 @@ jobs: ) orun plan "${plan_args[@]}" + # One matrix entry per LANE (execution.lanes in intent.yaml). A plan + # without lanes gets one per job, exactly the old matrix, and + # `orun run --lane ` on it is `--job `. - id: matrix run: | - echo "job-matrix=$(jq -c '[.jobs[] | {"job-id": .id, "job-name": .checkName}]' plan.json)" >> "$GITHUB_OUTPUT" + echo "lane-matrix=$(jq -c 'if ((.lanes // []) | length) > 0 + then [.lanes[] | {"lane": .id, "name": .name}] + else [.jobs[] | {"lane": .id, "name": .checkName}] end' plan.json)" >> "$GITHUB_OUTPUT" - uses: actions/upload-artifact@v7 with: name: orun-plan @@ -60,18 +85,57 @@ jobs: run: needs: plan runs-on: ubuntu-latest - if: ${{ needs.plan.outputs.job-matrix != '[]' && needs.plan.outputs.job-matrix != '' }} + # A BOOTSTRAP LANDING IS CHECKED BY `plan` ALONE. Every phase of the + # baseline bootstrap lands on a branch named for its task — the provenance + # pen's `orun/-`, and the bootstrap's tasks are all `BASE-n` — + # and is merged by `orun.pr/land@v1` as soon as this workflow is green. + # On those pull requests `plan` above is the check: the intent, every + # component and every composition resolve, the changed set is computed, + # and the plan is uploaded. The lanes are not run there, because the merge + # runs every one of them again on main moments later, for real, and the + # bootstrap watches that convergence to green before the next phase — the + # PR pass was the same work twice, and a third of a bootstrap's wall-clock. + # + # Measured on pullely/multi-tenant-saas, 2026-10-25: 04-workers' landing PR + # ran 46 jobs in 6m49s, every one of them again on the merge. Six landings + # pay it; the fleet's is the dearest, and it is where that build ran out of + # token before it ever reached the convergence. + # + # Every other pull request runs its lanes exactly as before. + if: >- + ${{ needs.plan.outputs.lane-matrix != '[]' && needs.plan.outputs.lane-matrix != '' + && !(github.event_name == 'pull_request' && startsWith(github.head_ref, 'orun/BASE-')) }} strategy: fail-fast: false # Stagger the fan-out: every lane hits the lease-bound resolve at job - # start, and an unbounded herd saturated it twice. The orun DAG already - # serializes dependents, so capped parallelism costs little wall-clock. - max-parallel: 8 + # start, and an unbounded herd saturated it twice. Nineteen is the free + # plan's twenty concurrent jobs less the `plan` job that is already + # done, and it is above execution.lanes.maxLanes (18), so a packed plan + # starts every lane at once; it only binds on a small plan that runs one + # lane per job. Inside a lane a job that waits on another lane holds no + # slot. + max-parallel: 19 matrix: - include: ${{ fromJson(needs.plan.outputs.job-matrix) }} - name: ${{ matrix.job-name }} + include: ${{ fromJson(needs.plan.outputs.lane-matrix) }} + name: ${{ matrix.name }} + env: + # One pnpm store for every lane, restored below. Each lane installs the + # whole workspace with --frozen-lockfile; without this every one of them + # downloaded all ~500 packages from the registry again. + npm_config_store_dir: /home/runner/.pnpm-store + PNPM_STORE_DIR: /home/runner/.pnpm-store steps: - uses: actions/checkout@v6 + # Keyed by the lockfile alone, so every lane of every run shares one + # entry until a dependency changes. The first lane to finish saves it; + # the rest find the key taken and skip the save. + - name: pnpm store cache + uses: actions/cache@v4 + with: + path: /home/runner/.pnpm-store + key: pnpm-store-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + pnpm-store-${{ runner.os }}- - uses: actions/download-artifact@v8 with: name: orun-plan @@ -83,14 +147,15 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - uses: sourceplane/orun-action@v1.2.0 with: - version: v2.56.2 + version: v2.78.4 # exec-id is the RUN id alone (no attempt suffix): a `gh run rerun # --failed` then RESUMES the same orun execution — jobs that succeeded in # a prior attempt stay completed, so re-run lanes' cross-job dependencies # are already satisfied instead of waiting forever on lanes that are not # re-running (the partial-rerun deadlock). --retry re-opens THIS lane's - # job when it terminally failed in a prior attempt (no-op on first - # attempts) — together they make `gh run rerun --failed` a true resume. + # failed jobs when they terminally failed in a prior attempt (no-op on + # first attempts); its completed jobs stay completed — together they make + # `gh run rerun --failed` a true resume. - run: | # --retry only on re-run attempts: on a fresh attempt a failed # upstream is a genuine failure and dependents must fail fast; on a @@ -126,7 +191,7 @@ jobs: --plan plan.json \ --runner github-actions \ $state_flag \ - --job "${{ matrix.job-id }}" \ + --lane "${{ matrix.lane }}" \ --exec-id "${{ github.run_id }}" \ $retry_flag env: diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md index d27b6f2..d83c8d1 100644 --- a/BOOTSTRAP.md +++ b/BOOTSTRAP.md @@ -13,18 +13,20 @@ now either a typed action inside the orun binary or a hook this repo still owns, which is why the version floor matters and why a phase can be run alone, months later, from a fresh container. -Budget: **84 minutes**, the sum of the phases' own `expectedMinutes` (the -shell layer this replaced measured ~73 for 01–06). The long poles are the -worker fleet (~31m across its two landings) and the console build (~16m); -Supabase project creation (5–7m per environment) is the longest wait nobody -can shorten. Where the numbers come from, and which are still estimates: +Budget: **53 minutes**, the sum of the phases' own `expectedMinutes`. The +long poles are the worker fleet (~14m, one landing and one deploy each) and +the console build (~13m); Supabase project creation (5–7m per environment) is +the longest wait nobody can shorten. The budget came down from 84 because a +bootstrap landing is no longer verified twice (its PR runs `plan` alone), the +fleet no longer deploys twice, and prod no longer waits out stage. Where the +numbers come from, and which are still estimates: [docs/phases/TIMINGS.md](docs/phases/TIMINGS.md). ## 0. What you need - **Tools.** `git`, `gh`, `node` (≥ 20), `pnpm`, `python3`, `curl`, and the - `orun` CLI **≥ v2.58.11**. That is the floor for RUNNING the bootstrap; the - product's own `ci.yml` lane pin is a separate, lower floor (v2.56.2). + `orun` CLI **≥ v2.88.0**. That is the floor for RUNNING the bootstrap; the + product's own `ci.yml` lane pin is a separate, lower floor (v2.78.4). v2.56.0 carried the phase overlay (before it there is no `--phase` and `hooks.{pre,post,await}` does not parse); v2.56.2 let a branded phase satisfy the next one's requirement; v2.58.4 resolves a milestone name and a @@ -42,8 +44,14 @@ can shorten. Where the numbers come from, and which are still estimates: preflight, without which every fresh build stops before its first phase; and v2.58.11 fills `orunWorkspace` from the workspace the build runs in (`from: workspace`), which is the only way a console build has of saying - it. `baseline.yml`'s `blueprint-parses` job pins the same version, so the - floor is tested rather than remembered. + it. v2.58.11 was the floor until this document used three keys an older + CLI refuses at parse: `hooks.preInstantiate[].background` and + `orun.pr/land@v1`'s `checks: local` (both v2.88.0), and + `orun.integrations/reconcile@v1`'s `secrets:` list (v2.87.0) — so the floor + is v2.88.0. The product's lane pin moved to v2.78.4 for `execution.lanes` + (v2.76.0), which is what makes CI run one job per lane instead of one per + orun job. `baseline.yml`'s `blueprint-parses` job pins the bootstrap floor, + so it is tested rather than remembered. - **GitHub.** Access to the org or user the product repo will live under (`githuborg`), and the Orun GitHub App installed there and connected to the workspace. `01-scaffold` waits for that connection to be to the account @@ -127,8 +135,10 @@ every phase after `01-scaffold` brands the tree — derives as `drifted`, and ## 1b. Or phase by phase — the same document, at your pace The phases are `01-scaffold`, `02-foundation`, `03-infrastructure`, -`03-infrastructure-database`, `04-workers`, `04-workers-restore`, `05-edge`, -`06-console`, `08-docs` — nine phases filed under seven milestones. The gap +`03-infrastructure-database`, `04-workers`, `05-edge`, `06-console`, +`08-docs` — eight phases filed under seven milestones. (`04-workers-restore` +is gone: the fleet deploys once, with its bindings — see +[docs/phases/04-workers.md](docs/phases/04-workers.md).) The gap at 07 is the optional `07-domain` phase, whose parked custom-domain component lands in `06-console` since baseline-v30 (the `domain` input that switched it on is gone). Each is idempotent, each follows one contract — @@ -151,7 +161,7 @@ orun new --blueprint repo-blueprint.yaml --out ~/sourceplane/acme --run-hooks \ orun new --blueprint repo-blueprint.yaml --out ~/sourceplane/acme --run-hooks \ --phase 02-foundation --values ~/sourceplane/acme/.rebrand/values.json # … 03-infrastructure, 03-infrastructure-database, 04-workers, -# 04-workers-restore, 05-edge, 06-console, 08-docs. +# 05-edge, 06-console, 08-docs. ``` The flags that shape a run: @@ -235,7 +245,7 @@ none of that happens. To see the *shape* without a real run, use `--status`. | requirement | detail | |---|---| -| image deps | `git`, `gh`, `node` (≥ 20), `pnpm`, `python3`, `curl`, `orun` ≥ v2.58.11 to run the bootstrap. The product's `ci.yml` lane pin (v2.56.2) is its own floor | +| image deps | `git`, `gh`, `node` (≥ 20), `pnpm`, `python3`, `curl`, `orun` ≥ v2.88.0 to run the bootstrap. The product's `ci.yml` lane pin (v2.78.4) is its own floor | | `ORUN_TOKEN` | orun access token; the typed actions authenticate with it (no login flow). A session token from `orun auth token` lives ~30m, shorter than a full run: use the workspace's admin-role API key, mint one per phase, or point `ORUN_TOKEN_FILE` at a file something keeps fresh (the CLI re-reads it on every call and prefers it) | | `GITHUB_TOKEN` | fine-grained PAT: **read** on `sourceplane/lumen` (the clone); on the PRODUCT repo: **contents write** (pushes), **pull-requests write** (landings), **actions read+write** (`orun.run/watch@v1` watches runs and re-runs failed lanes), **checks read**; **repo create** on the org if `01-scaffold` creates the repo (or pre-create it, empty — supported) | | pinning | the clone's `--branch ` pins EVERYTHING: the blueprint, its modules, and the hooks' scripts all come from that one commit. Use a tag for reproducible bootstraps; `main` for latest | @@ -328,7 +338,7 @@ the orun component lanes — and every product gets it. | job | what it proves | |---|---| | `baseline-contract` | bash + python3 + PyYAML only: `testing/manifest.test.sh` (card ↔ blueprint), `phases.test.sh` (the partition, the order, the narration, and `docs/phases/` — every phase has a page and every page a phase), `coverage.test.sh` (every component placed by exactly one phase; the ignore list honest), `rebrand.test.sh` | -| `blueprint-parses` | orun pinned at the bootstrap floor, v2.58.11: `orun new --status` reads the document the way a bootstrap will; then `testing/leak.test.sh` (what a product carries) and `testing/placement.test.sh` (the tree placed offline from `tests/fixtures/acme.json`, branded, and made to answer, phase by phase through a rebrand) | +| `blueprint-parses` | orun pinned at the bootstrap floor, v2.88.0: `orun new --status` reads the document the way a bootstrap will; then `testing/leak.test.sh` (what a product carries) and `testing/placement.test.sh` (the tree placed offline from `tests/fixtures/acme.json`, branded, and made to answer, phase by phase through a rebrand) | All of it runs locally with no credential and no network — `bash testing/.test.sh` from the repo root. Leak and placement need `orun` on @@ -371,13 +381,15 @@ purpose, written down so they read as instructions rather than breakage. | Terraform: resource already exists (10014 etc.) with empty platform state | `adopt.tf` imports at plan time — present in the kv, hyperdrive and supabase roots. Roots without adoption must be state-migrated or the resource deleted. | | `03-infrastructure-database` refuses: `SUPABASE_*` not published | `03-infrastructure`'s supabase apply did not publish on that environment. Read that lane, fix, re-run `03-infrastructure`. | | `04-workers` refuses: `WIRING_*` not published | Phase 03 did not finish — `WIRING_CLOUDFLARE_KV` is `03-infrastructure`'s, `WIRING_CLOUDFLARE_HYPERDRIVE` is `03-infrastructure-database`'s. | -| Cloudflare 10143 (service binding target not found) in `04-workers` | A feedback edge the strip does not cover. Run `node /tooling/bootstrap/cycle-break.mjs --check` from the product repo; add the edge to `FEEDBACK_EDGES` and to the acknowledged-cycles test together. | +| Cloudflare 10143 (service binding target not found) in `04-workers` | The worker does not wait on `policy-worker`, whose pre-deploy places every binding target (`tooling/deploy/fleet-stubs.mjs`): its `dependsOn: policy-worker` must carry `mode: enforced`. `testing/fleet-stubs.test.sh` checks every binding holder. List what would be placed with `node /tooling/deploy/fleet-stubs.mjs --root . --env stage --list`. | | api-edge deploy: `Service binding '_WORKER' … not found` | A fleet worker never deployed in phase 04. Resume that convergence, then re-run `05-edge`. | | Convergence run fails, lanes look transient | `orun.run/watch@v1` already resumes it up to 3× (`gh run rerun --failed` is a true resume: exec-id + `--retry`). | | Convergence still red after the resume budget | Re-running the phase lands nothing new, and CI plans `--changed`, so nothing redeploys what the failed run left undeployed. Resume the run itself — `gh run rerun --failed ` — then re-run the phase so its `await` hooks verify. | | `/health` probes fail against a green deploy | Check `subdomain` first: it must be the Cloudflare account's workers.dev subdomain, and the default is a placeholder. A console build reads it from the Cloudflare connection; a hand-run build passes it with `--set`. | | CLI login dies with 429 `rate_limited` | Fixed ≥ v2.48.1 (redeem honours Retry-After). Upgrade the CLI. | -| `unknown flag: --phase`, `cannot unmarshal !!map into []scaffold.Hook`, or an action `has no parameter "githubOwner"` / `"sha"` | The CLI is below the v2.58.11 floor. This blueprint is not readable by an older one. | +| `unknown flag: --phase`, `cannot unmarshal !!map into []scaffold.Hook`, or an action `has no parameter "githubOwner"` / `"sha"` / `"checks"` / `"secrets"` / `"background"` | The CLI is below the v2.88.0 floor. This blueprint is not readable by an older one. | +| `! [rejected] orun/BASE-n- (non-fast-forward)` on a retry | A build that stopped between the pen's push and the merge left that branch on the remote, and the retry commits a sibling of it. Each landing's `pen-reset` hook clears it (`tooling/bootstrap/pen-reset.mjs`); if you are on a baseline without that hook, delete the branch — `git push origin --delete orun/BASE-n-`, which also closes its pull request — and re-run the phase. Do NOT `git pull`: the branches have diverged, and merging the abandoned commit back in lands a doubled diff. | +| The build stops with nothing failed, no merge and no convergence | Its `ORUN_TOKEN` very likely expired: `orun auth token` mints a short-lived one (~30m) and a full bootstrap is longer. Use the workspace's admin-role API key, or point `ORUN_TOKEN_FILE` at a file something keeps fresh — the CLI re-reads it on every call. Seen on pullely/multi-tenant-saas (2026-10-25): 46/46 PR checks green at 30m46s, then no merge and no further platform event. | | A fresh build stops before 01-scaffold: `✕ phase "04-workers" precondition "wiring" is not met: … project "" not found` | The CLI is below v2.58.10, which asks the preflight about the product's project before phase 01 has created it and calls the answer a failure. Upgrade; the probe is then deferred to phase 04. | | The product's `intent.yaml` says `workspace: ws_SET_ME`, or its secret refs name the repository (`secret:///…`) | `orunWorkspace` was empty: set it, or run the build in the workspace (ORUN_WORKSPACE) with a CLI ≥ v2.58.11, which fills it from there. | | `✕ input "productname" is required` | Required inputs are validated before anything else, so this names the key nobody typed. All three — `reponame`, `productname`, `githuborg` — must be set on every invocation, including single-phase ones. `--values /.rebrand/values.json` carries them. The domain is not required (a baseline before v30 asked for `productdomain` too). | diff --git a/README.md b/README.md index 3110e21..de2dc1e 100644 --- a/README.md +++ b/README.md @@ -42,10 +42,10 @@ _Not yet recorded — run [`08-docs`](docs/phases/08-docs.md) after This baseline births new products from one artifact — `repo-blueprint.yaml`, run by `orun new` (**[BOOTSTRAP.md](BOOTSTRAP.md)** → -[docs/phases/](docs/phases/README.md)). It declares nine idempotent phases — -scaffold, foundation, infrastructure, database, workers, workers-restore, -edge, console (with the custom-domain component, parked), docs — each landing -a verified slice, each selectable with `--phase `. +[docs/phases/](docs/phases/README.md)). It declares eight idempotent phases — +scaffold, foundation, infrastructure, database, workers, edge, console (with +the custom-domain component, parked), docs — each landing a verified slice, +each selectable with `--phase `. Products receive **product-only content** (source, infra, CI, their own docs); none of this baseline's machinery ships, and a product's docs speak only about the product. This README does not ship either: a product gets its @@ -56,9 +56,10 @@ own `README.md` and an `AGENTS.md`, rendered from - Node.js >= 20 (CI and components run on Node 22) - pnpm >= 10 (`npm install -g pnpm`) -- (Optional, for local Orun validation) the `kiox` CLI on your `PATH`. `kiox` - pins the Orun provider declared in `kiox.yaml`; invoke Orun as - `kiox -- orun ...`. +- (Optional, for local Orun validation) the `orun` CLI on your `PATH`, at the + version `.github/workflows/ci.yml` pins. Orun is pinned where it runs — in + CI by `orun-action`'s `version:`, and for a bootstrap by the floor + BOOTSTRAP.md names — so there is no provider manifest to install. ## Getting Started @@ -123,16 +124,16 @@ released there, and adopted here by bumping the pinned tag. CI is powered by [Orun](https://github.com/sourceplane/orun) with the local Stack Tectonic composition stack. `.github/workflows/ci.yml` calls only `orun plan` and `orun run` — no direct `pnpm`, `turbo`, Wrangler, or Terraform commands run in -GitHub Actions. The Orun runtime is pinned in `kiox.yaml` (resolved digest in -`kiox.lock`); the workflow's `orun-action` `version:` matches that pin. +GitHub Actions. The Orun runtime is pinned where it runs: the workflow's +`orun-action` `version:`. ### Local Orun Verification ```bash -kiox -- orun compositions lock --intent intent.yaml -kiox -- orun validate --intent intent.yaml -kiox -- orun plan --changed --intent intent.yaml --output plan.json -kiox -- orun run --plan plan.json --dry-run --runner github-actions +orun compositions lock --intent intent.yaml +orun validate --intent intent.yaml +orun plan --changed --intent intent.yaml --output plan.json +orun run --plan plan.json --dry-run --runner github-actions ``` Use `--changed` for PR-scoped checks; use a full plan when validating @@ -157,7 +158,7 @@ manual prerequisites. typed `parameters` the composition schema requires. 3. Orun discovers it automatically on the next plan (`discovery.roots` covers `apps/`, `infra/`, `packages/`, `tests/`). Validate with - `kiox -- orun validate --intent intent.yaml`. + `orun validate --intent intent.yaml`. See `specs/core/orun-golden-path.md` for the intent/component/composition layer rules before changing CI, infra, or `intent.yaml`. diff --git a/agents/orchestrator.md b/agents/orchestrator.md index ac05798..38ee23b 100644 --- a/agents/orchestrator.md +++ b/agents/orchestrator.md @@ -400,11 +400,11 @@ Must: - run the required Orun verification for the changed components - create PR - write report -- run `kiox -- orun validate --intent intent.yaml` +- run `orun validate --intent intent.yaml` when `intent.yaml` exists -- run `kiox -- orun plan --changed --intent intent.yaml --output plan.json` +- run `orun plan --changed --intent intent.yaml --output plan.json` when Orun is scaffolded -- run `kiox -- orun run --plan plan.json --dry-run --runner github-actions` +- run `orun run --plan plan.json --dry-run --runner github-actions` when a plan is produced, recording no-op results when the plan has no jobs Report: @@ -435,7 +435,7 @@ Must: - validate milestone acceptance criteria - identify spec drift and ensure proposals exist for non-trivial spec changes - run quality gates -- run local kiox/orun validation when available +- run local orun validation when available - inspect GitHub Actions logs, not just status summaries - detect overreach / hidden coupling - confirm production-grade basics @@ -456,10 +456,10 @@ Recommended Next Move Verifier Merge Protocol: -- Prefer `kiox` when `kiox` is not on `PATH` -- Run `kiox -- orun validate --intent intent.yaml` when `intent.yaml` exists -- Run `kiox -- orun plan --changed --intent intent.yaml --output plan.json` when Orun is scaffolded -- Run `kiox -- orun run --plan plan.json --dry-run --runner github-actions` when a plan is produced; if no jobs are planned, record the no-op result +- Skip local validation when `orun` is not on `PATH` +- Run `orun validate --intent intent.yaml` when `intent.yaml` exists +- Run `orun plan --changed --intent intent.yaml --output plan.json` when Orun is scaffolded +- Run `orun run --plan plan.json --dry-run --runner github-actions` when a plan is produced; if no jobs are planned, record the no-op result - When a task creates or updates Cloudflare, Supabase, AWS IAM, S3, or Secrets Manager resources, verify the resulting resources directly with provider CLIs/APIs, Terraform state, or GitHub Actions logs and include non-secret observed resource state in the verifier report - Check PR CI logs with `gh`, including successful jobs, to confirm expected commands actually ran - Verify PR CI logs show `orun plan --changed --intent intent.yaml --output plan.json` and `orun run --plan plan.json --runner github-actions --remote-state` when applicable diff --git a/ai/context/open-risks.md b/ai/context/open-risks.md index 012e46f..916acf4 100644 --- a/ai/context/open-risks.md +++ b/ai/context/open-risks.md @@ -211,7 +211,7 @@ Last updated: 2026-05-26 ## Watch Items - Keep `.github/workflows/ci.yml` Orun-only. -- Verify that local `kiox -- orun ...` behavior and GitHub Actions behavior use +- Verify that local `orun ...` behavior and GitHub Actions behavior use the same rendered plan. - Keep reusable SaaS starter work separate from product-specific `specs-v2` work. diff --git a/apps/admin-worker/component.yaml b/apps/admin-worker/component.yaml index 603b898..093cf17 100644 --- a/apps/admin-worker/component.yaml +++ b/apps/admin-worker/component.yaml @@ -15,7 +15,19 @@ spec: domain: starter-runtime path: apps/admin-worker dependsOn: + # ENFORCED ON MAIN: the data plane before anything that reads its wiring, + # and policy-worker before anything that holds a service binding — its + # pre-deploy creates a placeholder for every binding target that does not + # exist yet (tooling/deploy/fleet-stubs.mjs), so each worker's first + # deploy can carry its full bindings. Peer edges stay advisory: they are + # runtime calls, not deploy order. A pull request deploys nothing, so + # nothing on one waits. - component: cloudflare-hyperdrive + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request # Shared workspace packages this component BUNDLES. Declared so a change # to one marks this component changed and redeploys it — without the # edge, `orun plan --changed` keys on `path:` alone and a worker can run diff --git a/apps/admin-worker/docs/runbook.md b/apps/admin-worker/docs/runbook.md index 128595e..70a7606 100644 --- a/apps/admin-worker/docs/runbook.md +++ b/apps/admin-worker/docs/runbook.md @@ -25,8 +25,11 @@ exercised through `api-edge` (this Worker has no public URL). infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/apps/api-edge/component.yaml b/apps/api-edge/component.yaml index b569b33..c1368e9 100644 --- a/apps/api-edge/component.yaml +++ b/apps/api-edge/component.yaml @@ -15,8 +15,31 @@ spec: domain: starter-runtime path: apps/api-edge dependsOn: + # ENFORCED ON MAIN: the data plane before anything that reads its wiring, + # and policy-worker before anything that holds a service binding — its + # pre-deploy creates a placeholder for every binding target that does not + # exist yet (tooling/deploy/fleet-stubs.mjs), so each worker's first + # deploy can carry its full bindings. Peer edges stay advisory: they are + # runtime calls, not deploy order. A pull request deploys nothing, so + # nothing on one waits. + - component: policy-worker + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request - component: cloudflare-hyperdrive + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request - component: cloudflare-kv + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request - component: projects-worker - component: events-worker - component: config-worker @@ -38,6 +61,12 @@ spec: - name: dev profile: verify - name: stage + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod @@ -52,6 +81,12 @@ spec: when: triggerRef: github-push-main - name: prod + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod diff --git a/apps/api-edge/docs/runbook.md b/apps/api-edge/docs/runbook.md index 7fc7484..8eb3338 100644 --- a/apps/api-edge/docs/runbook.md +++ b/apps/api-edge/docs/runbook.md @@ -34,8 +34,11 @@ a persistent failure is real. infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/apps/billing-worker/component.yaml b/apps/billing-worker/component.yaml index 34f4dc3..f8ce19d 100644 --- a/apps/billing-worker/component.yaml +++ b/apps/billing-worker/component.yaml @@ -15,7 +15,19 @@ spec: domain: starter-runtime path: apps/billing-worker dependsOn: + # ENFORCED ON MAIN: the data plane before anything that reads its wiring, + # and policy-worker before anything that holds a service binding — its + # pre-deploy creates a placeholder for every binding target that does not + # exist yet (tooling/deploy/fleet-stubs.mjs), so each worker's first + # deploy can carry its full bindings. Peer edges stay advisory: they are + # runtime calls, not deploy order. A pull request deploys nothing, so + # nothing on one waits. - component: policy-worker + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request # Shared workspace packages this component BUNDLES. Declared so a change # to one marks this component changed and redeploys it — without the # edge, `orun plan --changed` keys on `path:` alone and a worker can run @@ -34,6 +46,12 @@ spec: - name: dev profile: verify - name: stage + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod @@ -46,6 +64,12 @@ spec: when: triggerRef: github-push-main - name: prod + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod diff --git a/apps/billing-worker/docs/runbook.md b/apps/billing-worker/docs/runbook.md index 01bedde..ada86da 100644 --- a/apps/billing-worker/docs/runbook.md +++ b/apps/billing-worker/docs/runbook.md @@ -25,8 +25,11 @@ exercised through `api-edge` (this Worker has no public URL). infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/apps/config-worker/component.yaml b/apps/config-worker/component.yaml index 6b24724..e840838 100644 --- a/apps/config-worker/component.yaml +++ b/apps/config-worker/component.yaml @@ -15,8 +15,20 @@ spec: domain: starter-runtime path: apps/config-worker dependsOn: + # ENFORCED ON MAIN: the data plane before anything that reads its wiring, + # and policy-worker before anything that holds a service binding — its + # pre-deploy creates a placeholder for every binding target that does not + # exist yet (tooling/deploy/fleet-stubs.mjs), so each worker's first + # deploy can carry its full bindings. Peer edges stay advisory: they are + # runtime calls, not deploy order. A pull request deploys nothing, so + # nothing on one waits. - component: membership-worker - component: policy-worker + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request # Shared workspace packages this component BUNDLES. Declared so a change # to one marks this component changed and redeploys it — without the # edge, `orun plan --changed` keys on `path:` alone and a worker can run @@ -34,6 +46,12 @@ spec: - name: dev profile: verify - name: stage + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod @@ -46,6 +64,12 @@ spec: when: triggerRef: github-push-main - name: prod + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod diff --git a/apps/config-worker/docs/runbook.md b/apps/config-worker/docs/runbook.md index 97211e6..094a544 100644 --- a/apps/config-worker/docs/runbook.md +++ b/apps/config-worker/docs/runbook.md @@ -25,8 +25,11 @@ exercised through `api-edge` (this Worker has no public URL). infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/apps/events-worker/component.yaml b/apps/events-worker/component.yaml index ca545c1..cbd8451 100644 --- a/apps/events-worker/component.yaml +++ b/apps/events-worker/component.yaml @@ -15,8 +15,20 @@ spec: domain: starter-runtime path: apps/events-worker dependsOn: + # ENFORCED ON MAIN: the data plane before anything that reads its wiring, + # and policy-worker before anything that holds a service binding — its + # pre-deploy creates a placeholder for every binding target that does not + # exist yet (tooling/deploy/fleet-stubs.mjs), so each worker's first + # deploy can carry its full bindings. Peer edges stay advisory: they are + # runtime calls, not deploy order. A pull request deploys nothing, so + # nothing on one waits. - component: membership-worker - component: policy-worker + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request # Shared workspace packages this component BUNDLES. Declared so a change # to one marks this component changed and redeploys it — without the # edge, `orun plan --changed` keys on `path:` alone and a worker can run @@ -28,6 +40,12 @@ spec: - name: dev profile: verify - name: stage + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod @@ -40,6 +58,12 @@ spec: when: triggerRef: github-push-main - name: prod + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod @@ -82,4 +106,3 @@ spec: layer: runtime surface: events runtime: cloudflare -# ci: cycle-break pass 1 — deploy cluster with feedback edges stripped (20260622T135810Z) diff --git a/apps/events-worker/docs/runbook.md b/apps/events-worker/docs/runbook.md index 5a48167..cd91fa4 100644 --- a/apps/events-worker/docs/runbook.md +++ b/apps/events-worker/docs/runbook.md @@ -25,8 +25,11 @@ exercised through `api-edge` (this Worker has no public URL). infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/apps/identity-worker/component.yaml b/apps/identity-worker/component.yaml index 14006a1..bdebf85 100644 --- a/apps/identity-worker/component.yaml +++ b/apps/identity-worker/component.yaml @@ -15,8 +15,25 @@ spec: domain: starter-runtime path: apps/identity-worker dependsOn: + # ENFORCED ON MAIN: the data plane before anything that reads its wiring, + # and policy-worker before anything that holds a service binding — its + # pre-deploy creates a placeholder for every binding target that does not + # exist yet (tooling/deploy/fleet-stubs.mjs), so each worker's first + # deploy can carry its full bindings. Peer edges stay advisory: they are + # runtime calls, not deploy order. A pull request deploys nothing, so + # nothing on one waits. - component: cloudflare-hyperdrive + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request - component: policy-worker + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request - component: membership-worker - component: notifications-worker # Shared workspace packages this component BUNDLES. Declared so a change @@ -39,6 +56,12 @@ spec: - name: dev profile: verify - name: stage + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod @@ -51,6 +74,12 @@ spec: when: triggerRef: github-push-main - name: prod + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod diff --git a/apps/identity-worker/docs/runbook.md b/apps/identity-worker/docs/runbook.md index 2f4d1f6..95c6e5d 100644 --- a/apps/identity-worker/docs/runbook.md +++ b/apps/identity-worker/docs/runbook.md @@ -25,8 +25,11 @@ exercised through `api-edge` (this Worker has no public URL). infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/apps/integrations-worker/component.yaml b/apps/integrations-worker/component.yaml index 7d3e004..9ab515e 100644 --- a/apps/integrations-worker/component.yaml +++ b/apps/integrations-worker/component.yaml @@ -15,8 +15,20 @@ spec: domain: starter-runtime path: apps/integrations-worker dependsOn: + # ENFORCED ON MAIN: the data plane before anything that reads its wiring, + # and policy-worker before anything that holds a service binding — its + # pre-deploy creates a placeholder for every binding target that does not + # exist yet (tooling/deploy/fleet-stubs.mjs), so each worker's first + # deploy can carry its full bindings. Peer edges stay advisory: they are + # runtime calls, not deploy order. A pull request deploys nothing, so + # nothing on one waits. - component: membership-worker - component: policy-worker + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request - component: billing-worker - component: projects-worker # Shared workspace packages this component BUNDLES. Declared so a change @@ -40,6 +52,12 @@ spec: - name: dev profile: verify - name: stage + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod @@ -52,6 +70,12 @@ spec: when: triggerRef: github-push-main - name: prod + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod diff --git a/apps/integrations-worker/docs/runbook.md b/apps/integrations-worker/docs/runbook.md index 8119e42..de55722 100644 --- a/apps/integrations-worker/docs/runbook.md +++ b/apps/integrations-worker/docs/runbook.md @@ -25,8 +25,11 @@ exercised through `api-edge` (this Worker has no public URL). infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/apps/membership-worker/component.yaml b/apps/membership-worker/component.yaml index 4929920..d4a016b 100644 --- a/apps/membership-worker/component.yaml +++ b/apps/membership-worker/component.yaml @@ -15,7 +15,19 @@ spec: domain: starter-runtime path: apps/membership-worker dependsOn: + # ENFORCED ON MAIN: the data plane before anything that reads its wiring, + # and policy-worker before anything that holds a service binding — its + # pre-deploy creates a placeholder for every binding target that does not + # exist yet (tooling/deploy/fleet-stubs.mjs), so each worker's first + # deploy can carry its full bindings. Peer edges stay advisory: they are + # runtime calls, not deploy order. A pull request deploys nothing, so + # nothing on one waits. - component: policy-worker + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request - component: billing-worker # Shared workspace packages this component BUNDLES. Declared so a change # to one marks this component changed and redeploys it — without the @@ -29,6 +41,12 @@ spec: - name: dev profile: verify - name: stage + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod @@ -41,6 +59,12 @@ spec: when: triggerRef: github-push-main - name: prod + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod diff --git a/apps/membership-worker/docs/runbook.md b/apps/membership-worker/docs/runbook.md index 8fe426a..0f875c3 100644 --- a/apps/membership-worker/docs/runbook.md +++ b/apps/membership-worker/docs/runbook.md @@ -25,8 +25,11 @@ exercised through `api-edge` (this Worker has no public URL). infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/apps/metering-worker/component.yaml b/apps/metering-worker/component.yaml index 1f26560..3d1fa53 100644 --- a/apps/metering-worker/component.yaml +++ b/apps/metering-worker/component.yaml @@ -15,8 +15,20 @@ spec: domain: starter-runtime path: apps/metering-worker dependsOn: + # ENFORCED ON MAIN: the data plane before anything that reads its wiring, + # and policy-worker before anything that holds a service binding — its + # pre-deploy creates a placeholder for every binding target that does not + # exist yet (tooling/deploy/fleet-stubs.mjs), so each worker's first + # deploy can carry its full bindings. Peer edges stay advisory: they are + # runtime calls, not deploy order. A pull request deploys nothing, so + # nothing on one waits. - component: membership-worker - component: policy-worker + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request # Shared workspace packages this component BUNDLES. Declared so a change # to one marks this component changed and redeploys it — without the # edge, `orun plan --changed` keys on `path:` alone and a worker can run @@ -28,6 +40,12 @@ spec: - name: dev profile: verify - name: stage + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod @@ -40,6 +58,12 @@ spec: when: triggerRef: github-push-main - name: prod + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod diff --git a/apps/metering-worker/docs/runbook.md b/apps/metering-worker/docs/runbook.md index ec0a5c8..f1ea46b 100644 --- a/apps/metering-worker/docs/runbook.md +++ b/apps/metering-worker/docs/runbook.md @@ -25,8 +25,11 @@ exercised through `api-edge` (this Worker has no public URL). infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/apps/notifications-worker/component.yaml b/apps/notifications-worker/component.yaml index 8d20697..631419f 100644 --- a/apps/notifications-worker/component.yaml +++ b/apps/notifications-worker/component.yaml @@ -15,6 +15,19 @@ spec: domain: starter-runtime path: apps/notifications-worker dependsOn: + # ENFORCED ON MAIN: the data plane before anything that reads its wiring, + # and policy-worker before anything that holds a service binding — its + # pre-deploy creates a placeholder for every binding target that does not + # exist yet (tooling/deploy/fleet-stubs.mjs), so each worker's first + # deploy can carry its full bindings. Peer edges stay advisory: they are + # runtime calls, not deploy order. A pull request deploys nothing, so + # nothing on one waits. + - component: policy-worker + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request - component: events-worker - component: db-migrate # Shared workspace packages this component BUNDLES. Declared so a change @@ -82,6 +95,4 @@ spec: layer: runtime surface: notifications runtime: cloudflare -# ci: cycle-break pass 1 — deploy cluster with feedback edges stripped (20260622T135810Z) -# ci: cycle-break pass 1 — deploy cluster with feedback edges stripped (20260622T135810Z) # ci: re-trigger deploy (verify orun-secrets brokered CLOUDFLARE_API_TOKEN resolve in worker deploy lane, 20260727T153639Z) diff --git a/apps/notifications-worker/docs/runbook.md b/apps/notifications-worker/docs/runbook.md index 26782a2..629a6d6 100644 --- a/apps/notifications-worker/docs/runbook.md +++ b/apps/notifications-worker/docs/runbook.md @@ -25,8 +25,11 @@ exercised through `api-edge` (this Worker has no public URL). infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/apps/policy-worker/component.yaml b/apps/policy-worker/component.yaml index 14029d5..0ede276 100644 --- a/apps/policy-worker/component.yaml +++ b/apps/policy-worker/component.yaml @@ -55,7 +55,12 @@ spec: typecheckCommand: pnpm exec turbo run typecheck --filter=@saas/policy-worker dryRunCommand: pnpm exec wrangler deploy --dry-run --config wrangler.jsonc --env prod deployCommand: pnpm exec wrangler deploy --config wrangler.jsonc --env prod - preDeployCommand: "echo 'No pre-deploy step configured.'" + # The fleet's binding targets exist before any of it deploys: every worker + # that holds a service binding waits on this one (an enforced dependsOn on + # main), and this step uploads a placeholder for each target that does not + # exist yet, so their first deploys carry their full bindings + # (tooling/deploy/fleet-stubs.mjs). On a live product it uploads nothing. + preDeployCommand: "node ../../tooling/deploy/fleet-stubs.mjs --root ../.." migrationCommand: "echo 'No migrations configured.'" smokeCommand: "echo 'No smoke test configured.'" labels: diff --git a/apps/policy-worker/docs/runbook.md b/apps/policy-worker/docs/runbook.md index b95428b..cb2de94 100644 --- a/apps/policy-worker/docs/runbook.md +++ b/apps/policy-worker/docs/runbook.md @@ -25,8 +25,11 @@ exercised through `api-edge` (this Worker has no public URL). infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/apps/projects-worker/component.yaml b/apps/projects-worker/component.yaml index 448087b..84e6e84 100644 --- a/apps/projects-worker/component.yaml +++ b/apps/projects-worker/component.yaml @@ -15,8 +15,20 @@ spec: domain: starter-runtime path: apps/projects-worker dependsOn: + # ENFORCED ON MAIN: the data plane before anything that reads its wiring, + # and policy-worker before anything that holds a service binding — its + # pre-deploy creates a placeholder for every binding target that does not + # exist yet (tooling/deploy/fleet-stubs.mjs), so each worker's first + # deploy can carry its full bindings. Peer edges stay advisory: they are + # runtime calls, not deploy order. A pull request deploys nothing, so + # nothing on one waits. - component: membership-worker - component: policy-worker + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request - component: billing-worker # Shared workspace packages this component BUNDLES. Declared so a change # to one marks this component changed and redeploys it — without the @@ -29,6 +41,12 @@ spec: - name: dev profile: verify - name: stage + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod @@ -41,6 +59,12 @@ spec: when: triggerRef: github-push-main - name: prod + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod diff --git a/apps/projects-worker/docs/runbook.md b/apps/projects-worker/docs/runbook.md index eb07b32..f86168c 100644 --- a/apps/projects-worker/docs/runbook.md +++ b/apps/projects-worker/docs/runbook.md @@ -25,8 +25,11 @@ exercised through `api-edge` (this Worker has no public URL). infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/apps/webhooks-worker/component.yaml b/apps/webhooks-worker/component.yaml index a47dcd1..44cb258 100644 --- a/apps/webhooks-worker/component.yaml +++ b/apps/webhooks-worker/component.yaml @@ -15,8 +15,20 @@ spec: domain: starter-runtime path: apps/webhooks-worker dependsOn: + # ENFORCED ON MAIN: the data plane before anything that reads its wiring, + # and policy-worker before anything that holds a service binding — its + # pre-deploy creates a placeholder for every binding target that does not + # exist yet (tooling/deploy/fleet-stubs.mjs), so each worker's first + # deploy can carry its full bindings. Peer edges stay advisory: they are + # runtime calls, not deploy order. A pull request deploys nothing, so + # nothing on one waits. - component: membership-worker - component: policy-worker + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request # Shared workspace packages this component BUNDLES. Declared so a change # to one marks this component changed and redeploys it — without the # edge, `orun plan --changed` keys on `path:` alone and a worker can run @@ -34,6 +46,12 @@ spec: - name: dev profile: verify - name: stage + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod @@ -46,6 +64,12 @@ spec: when: triggerRef: github-push-main - name: prod + # Peer edges are runtime calls, not deploy order: every binding + # target exists before this deploys (policy-worker's pre-deploy + # places one, tooling/deploy/fleet-stubs.mjs), so nothing in this + # lane waits on a peer. The edges marked `mode: enforced` above + # still order. + dependencyMode: advisory profile: verify # wire-live (deploy profile) is the only reader, and dev never # deploys — scoping keeps dev jobs from requiring stage+prod diff --git a/apps/webhooks-worker/docs/runbook.md b/apps/webhooks-worker/docs/runbook.md index 02511fc..a3871a2 100644 --- a/apps/webhooks-worker/docs/runbook.md +++ b/apps/webhooks-worker/docs/runbook.md @@ -25,8 +25,11 @@ exercised through `api-edge` (this Worker has no public URL). infrastructure terraform upstream has not applied — check that lane first; within one convergence run the DAG guarantees order. - **Service-binding target missing (Cloudflare 10143)**: the target - Worker does not exist yet on this account — converge the fleet before - this lane (the bootstrap's two-pass landing handles first boot). + Worker does not exist yet on this account. Every binding holder waits on + `policy-worker`, whose pre-deploy uploads a placeholder for each missing + target (`tooling/deploy/fleet-stubs.mjs`), so this should not happen — if + it does, this component does not declare `dependsOn: policy-worker` with + `mode: enforced`. - **Smoke fails right after a first deploy**: a brand-new workers.dev route can 4xx for a few seconds; the lane already retries — persistent failure means a real regression. diff --git a/blueprint.yaml b/blueprint.yaml index d667a27..ad94d61 100644 --- a/blueprint.yaml +++ b/blueprint.yaml @@ -153,8 +153,8 @@ spec: # these. Idempotent by identity — epic by slug, milestone by name-within-epic # — so a re-run finds what it made before. The console renders the programme # so an operator can see the shape of the work before pressing Build. - # Nine phases, seven milestones: `03-infrastructure-database` and - # `04-workers-restore` are second landings of 03 and 04, and file under them. + # Eight phases, seven milestones: `03-infrastructure-database` is a second + # landing of 03 and files under it. programme: epicSlug: infra-baselining # = repo-blueprint.yaml's `epicSlug` default epicName: "Infra baselining — {productname}" @@ -179,11 +179,13 @@ spec: # the registry row names THIS file, the console card; it is not the build. blueprint: repo-blueprint.yaml # The sum of the phases' own `expectedMinutes` in repo-blueprint.yaml; - # `testing/manifest.test.sh` holds the two equal. It read 75 against a - # sum of 84, so the card and the phases disagreed. No build under - # the blueprint has been timed end to end yet (docs/phases/TIMINGS.md), - # so this is a budget, not a measurement. - expectedMinutes: 84 + # `testing/manifest.test.sh` holds the two equal. Re-budgeted from the + # measured runs once the duplicate PR verify pass was dropped, the fleet + # stopped deploying twice and prod stopped waiting out stage + # (docs/phases/TIMINGS.md has the arithmetic, phase by phase). No build + # has been timed end to end under these numbers yet, so this is a budget, + # not a measurement. + expectedMinutes: 53 tokenChannel: ORUN_TOKEN_FILE # how a runner hands over its refreshed token verify: urls: diff --git a/docs/phases/01-scaffold.md b/docs/phases/01-scaffold.md index 0507386..47d17af 100644 --- a/docs/phases/01-scaffold.md +++ b/docs/phases/01-scaffold.md @@ -24,7 +24,7 @@ The repo ROOT — no deployable components yet: ship by accident - `.rebrand/values.json` — the identity record every later phase reads - root files: `package.json`, `pnpm-workspace.yaml`, `pnpm-lock.yaml`, - `turbo.json`, `kiox` locks, `.gitignore` + `turbo.json`, `.gitignore` - `README.md` and `AGENTS.md` — the product's own, rendered from `.baseline/product/` with its name and repository: the front page, and the page an agent handed the product reads first (what it is, what to read @@ -115,6 +115,28 @@ block. This phase has no `await` hook: there is nothing to converge until a later phase lands a component. +## What it defers for the rest of the bootstrap + +Two rules in `intent.yaml` are right for a live product and wrong for a build +of one, so this phase turns both off and `08-docs`, the last landing, puts +them back byte-for-byte: + +- `prod.promotion.dependsOn: [stage]` makes every prod deploy wait out the + same component's stage deploy, doubling each convergence — twelve workers' + worth of it in `04-workers`. During a bootstrap both environments are empty + and every phase is watched to green, so the gate protects nothing yet + (`tooling/bootstrap/promotion.mjs --defer`). +- dev's `github-push-main` activation re-verifies every component on the dev + rung on every merge, which during a bootstrap proves nothing the pinned + baseline's own CI did not and takes runner slots from the deploys + (`tooling/bootstrap/dev-lanes.mjs --defer`). Pull requests keep their dev + lanes throughout. + +Both are deferred, never dropped: a bootstrap that stops before `08-docs` +leaves a marker comment in `intent.yaml`, and `--restore` (or a re-run of +`08-docs`) is the whole fix. `testing/bootstrap-defer.test.sh` holds the +round trip exact. + ## Verify / done means The repo is on GitHub, `main` carries the scaffold, `orun cloud check` diff --git a/docs/phases/04-workers.md b/docs/phases/04-workers.md index 97ccc1c..ea5278d 100644 --- a/docs/phases/04-workers.md +++ b/docs/phases/04-workers.md @@ -1,12 +1,15 @@ -# Phase 04 — workers (two landings) +# Phase 04 — the worker fleet -Lands the **12-worker fleet** in two landings: `04-workers` places the fleet -with two service-binding feedback edges stripped, so first-boot workers can -deploy in DAG order; `04-workers-restore` puts those two bindings back once -every worker they point at exists. Both file under the `04-workers` -milestone. +Lands the **12-worker fleet** in ONE landing, and one convergence deploys it +on stage and prod with every service binding in place. -This is the longest stretch of the bootstrap. +It used to be two landings: `04-workers` placed the fleet with two +service-binding feedback edges stripped out of its wrangler configs, and +`04-workers-restore` put them back once every target existed — two pull +requests, two convergences, the whole fleet deployed twice. That is gone; +see **Why one landing** below. + +This is still the longest stretch of the bootstrap. ## What it lands @@ -29,37 +32,34 @@ the only way in is a service binding from another worker. That is why this phase verifies by convergence rather than by probe; `05-edge` is where the fleet becomes observable from outside. -## Why two landings +## Why one landing The `{billing, membership, events, notifications}` cluster binds to itself — billing ↔ membership, and membership → notifications → events → membership — and a Cloudflare service binding cannot name a worker that does not exist -yet (error 10143). So a fresh fleet cannot deploy with its bindings intact: +yet (error 10143). So on a fresh account no order of first deploys works: something in the loop is always first. -`tooling/bootstrap/cycle-break.mjs` holds exactly two acknowledged feedback -edges, `billing-worker → membership-worker` and -`membership-worker → notifications-worker`: - -- `--strip` removes those bindings from the two workers' wrangler configs - (byte-preserving markers) before the first landing — the fleet then - deploys clean in DAG order; -- `--restore` puts them back byte-for-byte for the second landing, when - every target exists. - -Both are idempotent; `--check` reports the current state. - -These edges are not in the module DAG and there is no `cycleBreak:` for orun -to defer: the cycle lives in the wrangler config a deploy reads, not in the -placement order, so orun never sees it. That is why the script survives the -move to one blueprint — it is a deploy-time edit to a file, not an ordering -workaround the DAG could absorb. - -The restore is a phase of its own, rather than more hooks on the first, -because it can only run after `04-workers` has CONVERGED, and `post` hooks all -run before `await`: "strip, land, converge, restore, land, converge" cannot -be one phase's hook list. Two units of work that land separately, with two -PRs and two task contracts, are two phases here. +`tooling/deploy/fleet-stubs.mjs` is the answer. `policy-worker` binds to +nothing, and every worker that holds a binding declares +`dependsOn: policy-worker` with `mode: enforced` (advisory on a pull +request, which deploys nothing). Its pre-deploy step reads every +`apps/*/wrangler{.template,}.jsonc` for the environment's +`services[].service` names and uploads a placeholder Worker — a module that +answers 503 — for each one that does not exist yet. Every real deploy then +starts with all its targets present, carries its FULL bindings, and replaces +its own placeholder. + +It is race-free because nothing that holds a binding deploys while the +placeholders are being made: all of them wait on `policy-worker`. On a live +product every target exists and the tool uploads nothing. If the existence +check answers anything but 200 or 404 it refuses rather than guessing, so a +placeholder can never overwrite a real Worker. + +`testing/fleet-stubs.test.sh` drives the tool against a fake Cloudflare API +— a fresh account, a half-built one, a live one, and an erroring one — and +checks that every binding holder in `apps/` waits on the worker whose +pre-deploy runs it. ## Inputs @@ -69,67 +69,70 @@ runs, so pass them on every invocation; the product's own `.rebrand/values.json` is a complete values file. See [the phases README](README.md#inputs). -## `04-workers` - -1. **requires** — `03-infrastructure-database` placed, and a - `requires.probe`: `orun.secrets/exists@v1` asserts both - `WIRING_CLOUDFLARE_HYPERDRIVE` and `WIRING_CLOUDFLARE_KV` on stage and - prod before a single file is placed. Missing keys mean phase 03 did not - finish, and the phase says which. -2. **pre** — the phase's task. -3. **place** → **brand** → **lockfile**, then a `post` hook runs - `cycle-break.mjs --strip`. -4. **land** — PR `phase(04-workers): worker fleet (feedback edges - stripped)`. The PR's lanes build, test and plan the fleet on two - environments — nothing deploys from a PR — and the landing waits up to an - hour for them. -5. **converge** — the merge deploys the fleet. Budget an hour - (`waitSeconds: 3600`), resumed up to three times. Lanes resolve their - `WIRING_*` secrets at claim time. - -## The second landing: `04-workers-restore` - -1. **requires** — `04-workers` placed. It places no files, so it derives as - `unknown`; that is also why `05-edge` requires `04-workers` rather than - this phase. -2. **pre** — the task, filed under the `04-workers` milestone. -3. **restore** — `cycle-break.mjs --restore`. -4. **land** — PR `phase(04-workers): restore service-binding feedback - edges`. -5. **converge** — billing and membership redeploy with their bindings in - place (resumed up to twice). +## What the phase does + +1. **requires** — `03-infrastructure-database` placed. There is no wiring + probe: `WIRING_CLOUDFLARE_KV` is what `03-infrastructure`'s own `verify` + hook waited for and `WIRING_CLOUDFLARE_HYPERDRIVE` what + `03-infrastructure-database`'s did, both immediately before this phase, + and every worker resolves them from its `component.yaml` secret refs — so + a missing document fails that worker's lane rather than passing silently. +2. **pre** — the phase's task. The run-level `hooks.preInstantiate` list + opened it in the background before 01-scaffold placed a file; this finds + it and yields its key. +3. **retouch** → **place** → **brand** → **lockfile**. `retouch` rewrites one + trailing marker line in each component the task contract names, so a + RE-RUN after a convergence that failed post-merge still has a diff to land + (`tooling/bootstrap/retouch.mjs`). +4. **pen-reset** — clears this landing's own `orun/-04-workers` branch + if a stopped build left one behind, which would otherwise make every + retry's push fail non-fast-forward (`tooling/bootstrap/pen-reset.mjs`). +5. **land** — PR `phase(04-workers): the worker fleet`, checked LOCALLY + (`checks: local`): `orun validate` and both plans run on the commit before + it is pushed, so a tree that fails is never pushed. The PR's CI runs + `plan` alone on a bootstrap branch and nothing waits for it — the merge + runs every lane on main a minute later, for real. +6. **converge** — the merge deploys the fleet, each worker with its full + bindings. Budget an hour (`waitSeconds: 3600`), polled every 5 seconds, + resumed up to three times. Lanes resolve their `WIRING_*` secrets at claim + time. During a bootstrap stage and prod deploy side by side: 01-scaffold + deferred prod's promotion gate and 08-docs puts it back. ## Verify / done means -Both convergence runs green: every worker deployed with the two feedback -bindings stripped, then billing and membership redeployed with them, and -each deploy lane's smoke passed (the smoke retries over first-deploy -workers.dev route propagation — stack-tectonic ≥ 0.18.2, which the product's +One convergence run green: every worker deployed on stage and prod with its +full service bindings, and each deploy lane's smoke passed (the smoke retries +over first-deploy workers.dev route propagation, and a first deploy retries +Cloudflare's 10007 race — stack-tectonic ≥ 0.20.0, which the product's `intent.yaml` pins). ## Troubleshooting -- **The phase refuses: `WIRING_*` missing** — phase 03 is incomplete; its - two `verify` hooks assert the same keys. Re-run the phase 03 landing that - owns the missing key (`WIRING_CLOUDFLARE_KV` → `03-infrastructure`, +- **A worker's lane fails resolving `WIRING_*`** — phase 03 is incomplete; + its two `verify` hooks assert the same keys. Re-run the phase 03 landing + that owns the missing key (`WIRING_CLOUDFLARE_KV` → `03-infrastructure`, `WIRING_CLOUDFLARE_HYPERDRIVE` → `03-infrastructure-database`). -- **Cloudflare 10143 (service binding target not found)** during the FIRST - landing — the strip did not cover an edge. From the product repo, run - `node /tooling/bootstrap/cycle-break.mjs --check` (it reads - `apps/*/wrangler.template.jsonc` relative to the working directory); if a - new feedback edge was introduced, add it to `FEEDBACK_EDGES`, kept in sync - with `ACKNOWLEDGED_BINDING_CYCLES` in - `tests/config-worker/src/deployment-config.test.ts`. -- **10143 during the restore** — a target worker never deployed in the first - convergence. Resume that run before retrying the restore. -- **Convergence trips on runner starvation or resolve throttling** — that - is what the auto-resume is for, and `max-parallel: 8` in `ci.yml` is - deliberate. A genuinely red lane stays red across resumes: read its log. -- **Red after the resume budget** — re-running the phase lands nothing new, - and CI plans `--changed`, so no push will redeploy what the failed run left - undeployed. `gh run rerun --failed ` resumes the run itself; then - re-run the phase so its `await` hook verifies. See - [the phases README](README.md#pacing-idempotence-resume). +- **Cloudflare 10143 (service binding target not found)** — the worker does + not wait on `policy-worker`, whose pre-deploy places every target. Check + that its `dependsOn: policy-worker` carries `mode: enforced`; + `testing/fleet-stubs.test.sh` asserts this for every binding holder. To see + what would be placed: `node /tooling/deploy/fleet-stubs.mjs + --root . --env stage --list`. +- **Cloudflare 10007 (`This Worker does not exist on your account`)** — a + first-deploy race. stack-tectonic ≥ 0.19.0 retries it; the watch hook's + resume covers the rest. +- **The retry's push is rejected non-fast-forward** — a stopped build left + the pen branch on the remote. The `pen-reset` hook clears it; if you are on + an older baseline, `git push origin --delete orun/BASE-n-04-workers` and + re-run the phase. Never `git pull` it: the branches have diverged. +- **Convergence trips on runner starvation or resolve throttling** — that is + what the auto-resume is for, and `max-parallel: 19` in `ci.yml` is sized to + the free plan's twenty concurrent jobs. A genuinely red lane stays red + across resumes: read its log. +- **Red after the resume budget** — `gh run rerun --failed ` resumes + the run itself; then re-run the phase so its `await` hook verifies. The + `retouch` hook means the re-landing has a diff even when the merge already + happened. See [the phases README](README.md#pacing-idempotence-resume). ## Example commands @@ -139,10 +142,6 @@ From the baseline checkout: orun new --blueprint repo-blueprint.yaml --out $HOME/sourceplane/acme \ --run-hooks --phase 04-workers \ --values $HOME/sourceplane/acme/.rebrand/values.json - -orun new --blueprint repo-blueprint.yaml --out $HOME/sourceplane/acme \ - --run-hooks --phase 04-workers-restore \ - --values $HOME/sourceplane/acme/.rebrand/values.json ``` Headless (fresh container / no checkout — see BOOTSTRAP.md §2): clone the @@ -155,14 +154,12 @@ git clone --depth 1 --branch https://github.com/sourceplane/lumen cd lumen orun new --blueprint repo-blueprint.yaml --out /work/acme \ --run-hooks --phase 04-workers --values /work/acme.values.yaml -orun new --blueprint repo-blueprint.yaml --out /work/acme \ - --run-hooks --phase 04-workers-restore --values /work/acme.values.yaml ``` Preview with zero side effects: drop `--run-hooks` — the phase places files and stops, with no landing, no convergence watch and no probe. `--status` derives every phase's state and writes nothing at all. Re-running a -completed phase is safe: the placement is a no-op, strip and restore are +completed phase is safe: the placement is a no-op, the retouch marker is idempotent, the landing finds nothing new, and the `await` hooks re-assert. The pair measured ~31m end to end on the heaviest recorded run and ~21m on diff --git a/docs/phases/05-edge.md b/docs/phases/05-edge.md index c602cd5..082759a 100644 --- a/docs/phases/05-edge.md +++ b/docs/phases/05-edge.md @@ -35,9 +35,12 @@ runs, so pass them on every invocation; the product's own ## Steps -1. **requires** — `04-workers` placed. Not `04-workers-restore`: that phase - places no files, derives as `unknown`, and a requirement on it could never - be satisfied. Run the restore first anyway — `--resume` does. +1. **requires** — `04-workers` placed. That phase both places files and is + this one's predecessor, so the gate answers from the tree. It used to + require `04-workers-restore`, which placed none and therefore derived as + `unknown` — a requirement that could never be satisfied, and this phase + refused for the whole of a real bootstrap. That phase is gone: the fleet + deploys once, with its bindings. 2. **pre** — the phase's task. 3. **place** → **brand** → **lockfile** → **land** — the standard contract (PR `phase(05-edge): api-edge`). diff --git a/docs/phases/08-docs.md b/docs/phases/08-docs.md index 44a49e2..1160a09 100644 --- a/docs/phases/08-docs.md +++ b/docs/phases/08-docs.md @@ -23,6 +23,20 @@ No secret VALUE is ever read or written — inventories are names and statuses. A credential that cannot list a rung yields "listing unavailable to this credential" rather than a failed render. +## What it puts back + +Before it writes anything, this landing restores the two rules `01-scaffold` +deferred for the build: `prod.promotion.dependsOn: [stage]` +(`tooling/bootstrap/promotion.mjs --restore`) and dev's `github-push-main` +activation (`tooling/bootstrap/dev-lanes.mjs --restore`). Both reproduce +`intent.yaml` byte-for-byte. Restoring touches only the `environments` +section, which `orun plan --changed` maps to no component, so this landing +redeploys nothing. + +From here on a change reaches prod only after stage, and every merge to main +re-verifies the dev rung. A bootstrap that stopped before this phase leaves +a marker comment in `intent.yaml`; re-running `08-docs` is the whole fix. + ## Steps 1. **requires** — `06-console` placed. diff --git a/docs/phases/README.md b/docs/phases/README.md index b484320..9977212 100644 --- a/docs/phases/README.md +++ b/docs/phases/README.md @@ -1,6 +1,6 @@ # The phases — one blueprint, nine selections -`repo-blueprint.yaml` declares nine phases that take a product from +`repo-blueprint.yaml` declares eight phases that take a product from **nothing** to a **live, documented baseline** on Cloudflare and Supabase. Run them one at a time at your own pace with `--phase `, or run the whole sequence unattended with `--resume`. There is no wrapper that runs @@ -39,13 +39,12 @@ deploying is what a merge does and a PR cannot. | [`03-infrastructure`](03-infrastructure.md) | 03-infrastructure | `supabase`, `cloudflare-kv` | `WIRING_CLOUDFLARE_KV` + `SUPABASE_PROJECT_REF` / `SUPABASE_DB_PASSWORD` / `SUPABASE_DB_URL` published on stage and prod | | [`03-infrastructure-database`](03-infrastructure.md#the-second-landing-03-infrastructure-database) | 03-infrastructure | `cloudflare-hyperdrive`, `db-migrate` | `WIRING_CLOUDFLARE_HYPERDRIVE` published on stage and prod | | [`04-workers`](04-workers.md) | 04-workers | the 12-worker fleet, two feedback bindings stripped | convergence green | -| [`04-workers-restore`](04-workers.md#the-second-landing-04-workers-restore) | 04-workers | the two bindings put back (places no files) | convergence green | | [`05-edge`](05-edge.md) | 05-edge | `api-edge` (+ its tests, + `platform-limits-tests`) | `/health` answers on stage and prod | | [`06-console`](06-console.md) | 06-console | web console, and the custom-domain component (parked until a zone is wired) | console + edge live on stage and prod | | [`08-docs`](08-docs.md) | 08-docs | live-deployment docs (places no files; a hook renders them) | the URLs the manifest claims, re-probed | -Nine phases, seven milestones. `03-infrastructure-database` and -`04-workers-restore` are second landings of the unit before them: each has +Eight phases, seven milestones. `03-infrastructure-database` is a second +landing of the unit before it: it has its own PR and its own task, and each files under its predecessor's milestone. They are documented on their predecessor's page for the same reason. The numbering keeps its gap at 07: the custom-domain component that @@ -55,7 +54,7 @@ owner wires it later in an ordinary PR (see One requirement looks odd and is deliberate: -- **`05-edge` requires `04-workers`, not `04-workers-restore`.** A phase +- **A gate may only name a phase that places files.** A phase that places no files derives as `unknown` — the product repo cannot be asked whether a landing happened — and `requires.phases` fails closed on `unknown`. A requirement on a hook-only phase could never be satisfied. @@ -138,7 +137,7 @@ modes are the same files. ## Unattended: `--resume` `--resume` places every phase not already derived as done, in dependency -order, honouring each barrier. Budget **84 minutes** — the sum of the +order, honouring each barrier. Budget **53 minutes** — the sum of the phases' `expectedMinutes`, which the card carries — against the ~73 minutes measured for phases 01–06 under the shell layer this replaced. The worker fleet (~31m) and the console build (~16m) dominate; Supabase project creation @@ -175,7 +174,7 @@ Why it can run unattended: there), and `--resume` leaves a drifted phase placed rather than reverting your product's identity to `lumen`. Re-place one deliberately with `--phase `. -- `04-workers-restore` and `08-docs` place no files, so they derive as +- `08-docs` places no files, so it derives as `unknown`. `--status` prints all of this without writing anything. - **Git-level idempotence is not deploy-level idempotence.** The product's CI plans `--changed`: a component deploys only when its files changed in @@ -249,7 +248,7 @@ verb any bootstrap needs, and each resolves the baseline checkout as its `link` step (`orun cloud link`, then `orun cloud check` as the gate); - `pnpm install --lockfile-only` — the lanes install with `--frozen-lockfile`, and the lockfile grows with every phase; -- `tooling/bootstrap/cycle-break.mjs --strip` / `--restore` across the two +- `tooling/deploy/fleet-stubs.mjs`, the pre-deploy that makes one fleet worker landings; - `hooks/render-deployment-docs.sh`, `08-docs`'s renderer. diff --git a/docs/phases/TIMINGS.md b/docs/phases/TIMINGS.md index 4adb489..e827ea9 100644 --- a/docs/phases/TIMINGS.md +++ b/docs/phases/TIMINGS.md @@ -1,70 +1,78 @@ # Bootstrap timings — what to budget, and where the numbers come from -**Provenance matters here.** Every measured number on this page comes from -one of two real Lumen bootstraps, and both ran under the shell layer -("the flows") that `repo-blueprint.yaml` replaced. **No bootstrap has been -measured end to end under the blueprint yet.** - -- **vela** (2026-07-30) — fully headless phased bootstrap into the `seafern` - workspace with only `ORUN_TOKEN` + `GITHUB_TOKEN`. Landings waited for PR - checks, and PR lanes then deployed. Times are the clean path, with every - fix the run produced already landed. -- **ambient** (2026-08-02) — fully headless again, with a workspace-scoped - `sk_` API token instead of a user session (baseline-v8, orun v2.52.4). - Landings merged without waiting on PR checks (one deploy per landing), - which had shipped between the two runs. - -What moved into orun's typed actions is the mechanism, not the work: for -most phases the numbers carry over. Two changes do move the clock, and the -table labels every row that is an estimate because of them: - -1. **Phase 03 is two landings.** The flows landed supabase, kv, hyperdrive - and db-migrate in one PR without waiting on it. The blueprint lands - supabase and kv, waits for the apply, then lands hyperdrive and - db-migrate (see [03-infrastructure.md](03-infrastructure.md)). Neither - half has been timed. -2. **Every landing waits for its PR's CI again** — orun ≥ v2.58.6 waits for - the whole PR run and merges only on green. Unlike vela's, today's PR - lanes do not deploy (`ci.yml` gates deploy and apply profiles on a push to - `main`), so the wait costs build, test and plan time rather than a second - deploy. That should land between vela and ambient; it is not measured. +**Provenance matters here.** No bootstrap has been measured end to end under +the current numbers. The budgets below are arithmetic on measured runs — the +runs themselves are described under the table — and the second item that used +to head this page, *"every landing waits for its PR's CI again"*, is no longer +true: a bootstrap landing's pull request runs `plan` alone +(`.github/workflows/ci.yml`) and the landing is checked locally before it is +pushed (`checks: local`), so nothing waits for a runner to re-do work the +merge is about to do for real. + +What remains true from that header: **phase 03 is two landings** — the flows +landed supabase, kv, hyperdrive and db-migrate in one PR without waiting on +it, while the blueprint lands supabase and kv, waits for the apply, then +lands hyperdrive and db-migrate (see +[03-infrastructure.md](03-infrastructure.md)). ## Per-phase budget `expectedMinutes` is what the blueprint declares for each phase, and the card's `bootstrap.expectedMinutes` is their sum (`testing/manifest.test.sh` -holds the two equal). The phases' lines no longer quote it: a build page -shows one short line per step, and the budget is the engine's fact +holds them equal). The phases' lines no longer quote it: a build page shows +one short line per step, and the budget is the engine's fact (`.meta.expectedMinutes`), not prose. -| phase | `expectedMinutes` | provenance | what was measured | dominated by | -|---|---|---|---|---| -| `01-scaffold` | 2 | measured | ~2m (vela) | render + rebrand ~1m · repo create + push ~30s · link ~10s | -| `02-foundation` | 9 | measured | ~9m vela (PR verify lanes 3m29s · convergence 3m56s); 5m08s ambient | verify lanes, twice | -| `03-infrastructure` | 9 | **estimate** | the old one-landing phase 03: ~10m vela (convergence 6m47s), ~15m ambient (convergence ~11m) | Supabase project creation, 5–7m | -| `03-infrastructure-database` | 6 | **estimate** | — (its work was inside the old phase 03's numbers) | PR plan lanes · Hyperdrive create · migrations | -| `04-workers` | 31 | measured — **for both landings** | ~31m vela (PR lanes ~7m · strip convergence 13m18s · restore convergence 10m54s); 20m49s ambient | the fleet deploy | -| `04-workers-restore` | 5 | **estimate** | — as its own phase; its convergence was the 10m54s inside vela's 31m | billing + membership redeploy | -| `05-edge` | 5 | measured | 5m22s vela; 5m03s ambient | land → converge → `/health` probes | -| `06-console` | 16 | measured | 15m37s vela (all 3 resumes, self-healed); 14m01s ambient (0 resumes) | console builds are heavy | -| `08-docs` | 1 | **estimate** | — (neither run's table records it) | probe + render + land | -| tracking (BT) | seconds per landing | **estimate** | — | one task lookup and at most two creates per landing, plus the epic once | - -**Totals.** Measured: ~73m for 01–06 on vela, ~60m for 02–06 on ambient. The -per-phase numbers above sum to 84, and the card (`blueprint.yaml`) budgets -exactly that: it said 75 while the phases said 84, and -`testing/manifest.test.sh` now holds the two equal. The sum likely -overstates, because `04-workers`' 31 is vela's figure for the old phase 04, -which already contained the restore landing that `04-workers-restore` -budgets again — treat the 04 pair as ~20–31 between them, and expect a clean -run under 84. Correct the phases and the card together from the first -measured run (below). - -**Replace the estimates with measurements.** After the first full bootstrap -under the blueprint, take each phase's elapsed time from its `done` event -(`--progress json`) and edit this table and the blueprint's -`expectedMinutes` together. An estimate that survives its first real run -unchanged is a document nobody checked. +**These are re-budgeted, not re-measured.** The 84 they replace was the sum +under the old shape; three changes took time out of every phase, and the +column on the right is the arithmetic, from the measured runs below and from +`pullely/multi-tenant-saas` (2026-10-25, baseline before these changes). + +| phase | was | now | why | +|---|---|---|---| +| `01-scaffold` | 2 | **2** | unchanged. Measured ~2m (vela), 1m35s (multi-tenant-saas) | +| `02-foundation` | 9 | **5** | vela's 9m was PR verify lanes 3m29s + convergence 3m56s. The PR pass is gone (`plan` only on a bootstrap branch) | +| `03-infrastructure` | 9 | **8** | Supabase project creation, 5–7m, is the floor and nobody can shorten it. The PR pass (1m28s on multi-tenant-saas) is gone | +| `03-infrastructure-database` | 6 | **5** | measured 7m20s on multi-tenant-saas, of which its PR pass was 1m25s | +| `04-workers` | 31 | **14** | vela's 31m was PR lanes ~7m + strip convergence 13m18s + restore convergence 10m54s. One fleet deploy and no PR pass leaves the 13m18s | +| `04-workers-restore` | 5 | **gone** | the fleet deploys once, with its bindings (`tooling/deploy/fleet-stubs.mjs`) | +| `05-edge` | 5 | **4** | measured 5m22s (vela) / 5m03s (ambient) including its PR pass | +| `06-console` | 16 | **13** | measured 15m37s / 14m01s. The console build is still cold — the prebuilt artifact is NOT in this baseline | +| `08-docs` | 1 | **2** | it also restores the promotion gate and dev's lanes now | +| **total** | **84** | **53** | | + +Not counted, because they are seconds rather than minutes, and real: +the task plane opened in the background (~23s per build), each landing +checked locally instead of by a runner (~24s per landing, eight of them), +and the convergence watch reading every 5s instead of 40 (~20s per landing). + +**What the earlier measurements were.** Two real Lumen bootstraps, both under +the shell layer that `repo-blueprint.yaml` replaced, and both before any of +the changes above: + +- **vela** (2026-07-30) — fully headless phased bootstrap into the `seafern` + workspace with only `ORUN_TOKEN` + `GITHUB_TOKEN`. Landings waited for PR + checks, and PR lanes then deployed. ~73m for 01–06. +- **ambient** (2026-08-02) — fully headless again, with a workspace-scoped + `sk_` API token (baseline-v8, orun v2.52.4). Landings merged without + waiting on PR checks. ~60m for 02–06. + +And one under the blueprint, which did not finish: + +- **pullely/multi-tenant-saas** (2026-10-25) — reached the end of + `03-infrastructure-database` in 21m35s and `04-workers`' PR check in + 30m46s, then stopped: 46/46 PR jobs green, no merge, no convergence, no + further platform event. Nothing failed. Its `ORUN_TOKEN` is the likeliest + cause (`orun auth token` mints ~30m); every retry afterwards died on the + pen branch that build left behind, which is what + `tooling/bootstrap/pen-reset.mjs` now clears. Its 04-workers PR ran 46 jobs + in 6m49s — the duplicated pass that item 1 of this re-budget removes. + +**Replace these with measurements.** After the first full bootstrap under +these numbers, take each phase's elapsed time from its `done` event +(`--progress json`) and edit this table and the blueprint's `expectedMinutes` +together. An estimate that survives its first real run unchanged is a +document nobody checked. ## Things that shape the total diff --git a/infra/terraform/cloudflare-hyperdrive/README.md b/infra/terraform/cloudflare-hyperdrive/README.md index 13ee410..e62301d 100644 --- a/infra/terraform/cloudflare-hyperdrive/README.md +++ b/infra/terraform/cloudflare-hyperdrive/README.md @@ -153,7 +153,7 @@ See **Task 0010** for full Worker binding setup and runtime integration. ```bash # Ensure Orun CLI is installed -which orun # or: ~/.local/bin/kiox -- orun +which orun # Ensure AWS credentials are configured aws sts get-caller-identity diff --git a/infra/terraform/cloudflare-kv/README.md b/infra/terraform/cloudflare-kv/README.md index 6f460f9..44b54c7 100644 --- a/infra/terraform/cloudflare-kv/README.md +++ b/infra/terraform/cloudflare-kv/README.md @@ -134,19 +134,19 @@ land; the cutover is purely additive. ```bash # Validate intent -kiox exec -- orun validate +orun validate # Discover component -kiox exec -- orun component | grep cloudflare-kv +orun component | grep cloudflare-kv # Plan (dry) -kiox exec -- orun plan --intent intent.yaml --output plan.json +orun plan --intent intent.yaml --output plan.json # Inspect plan cat plan.json | jq '.jobs[] | select(.component == "cloudflare-kv") | {id, profile}' # Dry run -kiox exec -- orun run --plan plan.json --dry-run --runner github-actions +orun run --plan plan.json --dry-run --runner github-actions # Terraform fmt check terraform -chdir=infra/terraform/cloudflare-kv/terraform fmt -check @@ -171,7 +171,7 @@ terraform -chdir=infra/terraform/cloudflare-kv/terraform fmt -check | `Error: required field is not set` on `account_id` | `CLOUDFLARE_ACCOUNT_ID` not in env | Export `CLOUDFLARE_ACCOUNT_ID` (Orun CI does this automatically) | | `Error: 10000: Authentication error` | Token lacks Workers KV scope | Issue a new API token with `Workers KV Storage: Edit` | | Plan shows `0 components × N envs → 0 jobs` | Component not subscribed to PR-active env | Verify `subscribe.environments` matches `intent.yaml#environments.*.activation` | -| Wrangler `kv namespace list` doesn't show the namespace | apply didn't run, or wrong CF account | Run `kiox exec -- orun plan --intent intent.yaml` and confirm an apply job exists for the env | +| Wrangler `kv namespace list` doesn't show the namespace | apply didn't run, or wrong CF account | Run `orun plan --intent intent.yaml` and confirm an apply job exists for the env | ## Security diff --git a/intent.yaml b/intent.yaml index 4f3a5a7..2908bbe 100644 --- a/intent.yaml +++ b/intent.yaml @@ -21,6 +21,25 @@ execution: # default branch, keeping the org-global catalog head fresh without an # explicit `--push-catalog`. autopushCatalog: true + # Lanes (orun >= v2.76.0): CI runs one GitHub job per LANE, not per orun job. + # Auto mode leaves a small plan as one lane per job and packs a bigger one, + # keeping each environment on its own runners and every dependency chain + # (supabase -> hyperdrive -> db-migrate -> the workers that read their + # wiring) inside one lane. web-console-next is isolated (component.yaml): + # its build is the longest and must not hold up a lane. Every job still + # gets its own check run, named as before, so branch protection is + # unaffected. + lanes: + mode: auto + # The budget is the runner pool: a free GitHub plan starts 20 jobs at + # once, and `plan` is done before the lanes start, so 18 lanes fit in one + # wave. Auto mode shares them between environments by job count, so the + # fleet landing (twelve workers on stage and prod, plus dev's verify + # jobs) gives stage and prod several lanes each instead of one. + maxLanes: 18 + # Jobs in flight inside a lane = the runner's cores (4 on ubuntu-latest): + # above that each job only slows the others down. + concurrency: auto compositions: sources: @@ -31,7 +50,7 @@ compositions: # a commit here. Bumping the tag is the deliberate upgrade step. - name: stack-tectonic kind: oci - ref: oci://ghcr.io/sourceplane/stack-tectonic:0.18.2 + ref: oci://ghcr.io/sourceplane/stack-tectonic:0.20.0 resolution: precedence: - stack-tectonic @@ -81,6 +100,10 @@ automation: environments: dev: + description: Verify-only. Pull requests plan and verify here; nothing is deployed, so there is no door. + # dev only ever verifies (no component deploys to it), so nothing in it + # has to wait for anything: every dev job starts the moment a runner does. + dependencyMode: advisory activation: triggerRefs: - github-pull-request @@ -100,6 +123,11 @@ environments: BASE_DOMAIN: lumen.app stage: + description: The fleet, the API edge and the console, deployed on every merge to main before prod. + url: https://lumen-web-console-next-stage.rahulvarghesepullely.workers.dev + links: + - { title: API, url: https://lumen-api-edge-stage.rahulvarghesepullely.workers.dev } + - { title: Health, url: https://lumen-api-edge-stage.rahulvarghesepullely.workers.dev/health } activation: triggerRefs: - github-pull-request @@ -118,6 +146,11 @@ environments: BASE_DOMAIN: lumen.app prod: + description: Where customers are. Deploys after stage converges on the same commit. + url: https://lumen-web-console-next-prod.rahulvarghesepullely.workers.dev + links: + - { title: API, url: https://lumen-api-edge-prod.rahulvarghesepullely.workers.dev } + - { title: Health, url: https://lumen-api-edge-prod.rahulvarghesepullely.workers.dev/health } activation: triggerRefs: - github-pull-request diff --git a/kiox.lock b/kiox.lock deleted file mode 100644 index 6e14690..0000000 --- a/kiox.lock +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: kiox.io/v1 -kind: WorkspaceLock -metadata: - name: example-platform -providers: - - alias: orun - provider: sourceplane/orun - source: ghcr.io/sourceplane/orun:v2.15.0 - version: v2.15.0 - resolved: ghcr.io/sourceplane/orun@sha256:1d28be8612dc8d8083b508f97cd71a24c090f6472c43c71f68455e3709a6a3c1 - store: e02472f57f2eb5fb5168b7d270ea547e5bffbf83824c4286abd7ba20f87cb9d1 diff --git a/kiox.yaml b/kiox.yaml deleted file mode 100644 index d654da0..0000000 --- a/kiox.yaml +++ /dev/null @@ -1,6 +0,0 @@ -apiVersion: kiox.io/v1 -kind: Workspace -metadata: - name: example-platform -providers: - orun: ghcr.io/sourceplane/orun:v2.15.0 diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml index 232557f..a7684c2 100644 --- a/repo-blueprint.yaml +++ b/repo-blueprint.yaml @@ -532,6 +532,16 @@ modules: # engine, the phase splitter, the cycle breaker, the migration tools. A # product is a product, not a copy of the factory; the hooks below run the # baseline's own copies from `{{ .baseline.dir }}`. + # RUNS IN THE PRODUCT, not from the baseline: policy-worker's + # `preDeployCommand` invokes `../../tooling/deploy/fleet-stubs.mjs` on every + # deploy of every environment, for ever — so unlike tooling/bootstrap/, which + # the phases run from `{{ .baseline.dir }}` and no product carries, this one + # has to be placed. + - name: tooling-deploy + mode: copy + source: baseline + from: tooling/deploy + to: tooling/deploy - name: tooling-eslint mode: copy source: baseline @@ -613,16 +623,6 @@ modules: source: baseline from: turbo.json to: turbo.json - - name: root-kiox - mode: copy - source: baseline - from: kiox.yaml - to: kiox.yaml - - name: root-kiox-lock - mode: copy - source: baseline - from: kiox.lock - to: kiox.lock - name: root-gitignore mode: copy source: baseline @@ -699,6 +699,207 @@ modules: "epicSlug": "{{ .epicSlug }}" } +# ── THE TASK PLANE, OPENED BEFORE THE FIRST PHASE ───────────────────────── +# The epic, every milestone and every task, created once at the start of a run +# instead of one at a time as each phase reaches its own `task` hook. +# +# `background: true` (orun >= v2.88.0) lets the run get on with placing and +# branding the tree while these are being opened; the first hook that needs a +# task key is the one that waits for the list. Each phase keeps its own `task` +# hook — the same find-or-create by title within the epic — so it FINDS what +# this opened and yields its key, which is why every `name:` below must render +# to exactly the string its phase's hook asks for. testing/manifest.test.sh +# holds the two sets equal. +# +# Under an orun older than v2.88.0 the `background` key is ignored and the +# list is opened in order, which is where this work happened anyway. +hooks: + preInstantiate: + # THE EPIC IS THE BOOTSTRAP'S OWN CONTAINER, so the bootstrap makes it. + # Every task clubs under `epicSlug`, and until this existed nothing created + # it — a fresh workspace answered the first phase with `epic: no epic with + # that ref, key or slug` and the run ended there. Found-or-created by slug, + # so a re-run and a resume land in the same epic rather than minting a + # second one; that is why the slug is an input and not a generated id. + - id: epic + uses: orun.task/ensure@v1 + background: true + with: + kind: epic + slug: "{{ .inputs.epicSlug }}" + name: "Infra baselining — {{ .inputs.productname }}" + description: >- + Everything the lumen baseline builds for {{ .inputs.productname }} in + {{ .inputs.githuborg }}/{{ .inputs.reponame }}: the repository, its + shared packages, the Supabase and Cloudflare data plane, the + twelve-worker fleet, the API edge and the console, live on stage and + prod — then the record of what went live. One milestone per unit of + the product, in the order they land; one task per landing, each bound + to the pull request that lands it. + owner: me + - id: m01 + uses: orun.task/ensure@v1 + background: true + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 01-scaffold + exitCriteria: + - the repository created under the GitHub owner and linked to the workspace + - root manifests, tooling and CI on main, branded as the product + - id: m02 + uses: orun.task/ensure@v1 + background: true + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 02-foundation + exitCriteria: + - the shared packages on main, their verify lanes green + - id: m03 + uses: orun.task/ensure@v1 + background: true + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 03-infrastructure + exitCriteria: + - a Supabase Postgres project and a KV namespace applied on stage and prod + - Hyperdrive pooling the database, the schema migrated, the wiring published on both + - id: m04 + uses: orun.task/ensure@v1 + background: true + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 04-workers + exitCriteria: + - twelve workers deployed on stage and prod, each carrying its full service bindings + - id: m05 + uses: orun.task/ensure@v1 + background: true + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 05-edge + exitCriteria: + - api-edge deployed on stage and prod, answering /health + - id: m06 + uses: orun.task/ensure@v1 + background: true + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 06-console + exitCriteria: + - the web console deployed on stage and prod, answering as the product's console + - id: m07 + uses: orun.task/ensure@v1 + background: true + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 08-docs + exitCriteria: + - ai/context/deployment.md on main matches the probed live URLs + - prod waits on stage again, and dev verifies every merge again + - id: t01 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 01-scaffold + name: "phase(01-scaffold): repo born" + brief: >- + Create the repository, place the root manifests, tooling and CI, brand them, and land them as the first pull request. + prefix: BASE + contract: tasks/01-scaffold.TaskContract.yaml + - id: t02 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 02-foundation + name: "phase(02-foundation): shared packages" + brief: >- + Land the shared packages every worker bundles — contracts, db, sdk, cli, policy-engine, the test harness — and see their verify lanes green. + prefix: BASE + contract: tasks/02-foundation.TaskContract.yaml + - id: t03 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 03-infrastructure + name: "phase(03-infrastructure): supabase, kv" + brief: >- + Create a Supabase Postgres project and an idempotency KV namespace per environment, and publish their outputs for the pieces that read them. + prefix: BASE + contract: tasks/03-infrastructure.TaskContract.yaml + - id: t04 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 03-infrastructure + name: "phase(03-infrastructure): hyperdrive, db-migrate" + brief: >- + Pool the Supabase database through Cloudflare Hyperdrive and apply the schema to it, so the workers have a reachable database and its wiring. + prefix: BASE + contract: tasks/03-infrastructure-database.TaskContract.yaml + - id: t05 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 04-workers + name: "phase(04-workers): the worker fleet" + brief: >- + Land the twelve bounded-context workers and see one convergence deploy them on stage and prod, each with its full service bindings. + prefix: BASE + contract: tasks/04-workers.TaskContract.yaml + - id: t06 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 05-edge + name: "phase(05-edge): api-edge" + brief: >- + Land the public API edge in front of the fleet and see it answer /health on stage and prod. + prefix: BASE + contract: tasks/05-edge.TaskContract.yaml + - id: t07 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 06-console + name: "phase(06-console): web console" + brief: >- + Land the Next.js console on Workers and see it answer on stage and prod. + prefix: BASE + contract: tasks/06-console.TaskContract.yaml + - id: t08 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 08-docs + name: "docs(deployment): record live deployment state" + brief: >- + Probe every live URL one last time and write the deployment record from what actually answered, not from what the blueprint intended. + prefix: BASE + contract: tasks/08-docs.TaskContract.yaml + # ── PHASES ──────────────────────────────────────────────────────────────── # A phase is orun's own barrier over the module DAG — and, since BE1, the # whole of what a phase DOES. Each one declares what it is for a person @@ -726,11 +927,15 @@ modules: # `03-infrastructure-database` is the same kind of split for a different # reason: its PR lanes read what 03's apply publishes (see there). # -# Two phases place NO modules. `04-workers-restore` and `08-docs` are hooks -# and nothing else: the first re-adds the service bindings `04-workers` had to -# strip, the second records the live deployment. They are phases because they -# are separately landable units of the bootstrap with their own task and their -# own PR — which is what a phase is here — not because they write files. +# One phase places NO modules. `08-docs` is hooks and nothing else: it records +# the live deployment. It is a phase because it is a separately landable unit +# of the bootstrap with its own task and its own PR — which is what a phase is +# here — not because it writes files. +# +# There used to be a second such phase, `04-workers-restore`, which put back +# the service bindings `04-workers` had to strip. The fleet now deploys once +# with its bindings intact (tooling/deploy/fleet-stubs.mjs), so that phase, +# its landing and its convergence are gone. phases: - name: 01-scaffold title: The repo is born @@ -755,7 +960,7 @@ phases: start: 'Creating the repository and its foundations.' done: '{{ .inputs.githuborg }}/{{ .inputs.reponame }} has its foundations on main, branded as {{ .inputs.productname }}, in {{ .meta.elapsed }}.' failed: 'The repository did not get off the ground; the failing step says why.' - modules: [ai-deployment, ai-operations, discovery-roots, github-workflows, rebrand-values, root-agents, root-gitignore, root-intent, root-kiox, root-kiox-lock, root-package-json, root-pnpm-lock, root-pnpm-workspace, root-readme, root-turbo, tooling-eslint, tooling-tsconfig, tooling-wire] + modules: [ai-deployment, ai-operations, discovery-roots, github-workflows, rebrand-values, root-agents, root-gitignore, root-intent, root-package-json, root-pnpm-lock, root-pnpm-workspace, root-readme, root-turbo, tooling-deploy, tooling-eslint, tooling-tsconfig, tooling-wire] # THE PLATFORM MUST BE ABLE TO SEE THE REPOSITORY BEFORE IT EXISTS. Every # phase lands a pull request that files under its task, and the platform # learns of a PR only through the GitHub App installation on the account @@ -851,6 +1056,27 @@ phases: : "orun-workspace: intent.yaml workspace -> " + ws, ); # Re-stage so `git ls-files` and `rebrand --verify` see the rewritten tree. + # STAGE AND PROD DEPLOY SIDE BY SIDE UNTIL THE BOOTSTRAP IS DONE. + # intent.yaml gates prod behind stage (`promotion.dependsOn`), which + # makes every prod deploy wait out the same component's stage deploy + # and doubles each convergence — twelve workers' worth of it in + # 04-workers. During a bootstrap both environments are empty and every + # phase is watched to green before the next, so the gate protects + # nothing yet: it is deferred here and restored by 08-docs, the last + # landing. tooling/bootstrap/promotion.mjs. + - id: promotion + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/promotion.mjs", "--defer"] + # DEV'S VERIFY LANES STAY OFF MAIN UNTIL THE BOOTSTRAP IS DONE, for the + # same reason and by the same mechanism. Every merge to main re-verifies + # every component on the dev rung; during a bootstrap that proves + # nothing the pinned baseline's own CI did not, and it takes runner + # slots from the deploys (measured on the Cloudflare-only baseline: + # eight of eighteen lanes, leaving stage and prod five each). Deferred + # here, restored by 08-docs; pull requests keep their dev lanes + # throughout. tooling/bootstrap/dev-lanes.mjs. + - id: dev-lanes + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/dev-lanes.mjs", "--defer"] + # Re-stage so `git ls-files` and `rebrand --verify` see the rewritten tree. - id: git-restage run: ["git", "add", "-A"] - id: rebrand-verify @@ -901,6 +1127,17 @@ phases: - link - "{{ .inputs.orunWorkspace }}" - "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" + # CLEAR THIS LANDING'S OWN PEN BRANCH FIRST. A build that stopped + # between the pen's push and the merge leaves `orun/-` on + # the remote; the retry commits a SIBLING of that commit, so the push + # is rejected non-fast-forward — identically, on every retry, for + # ever. Observed on pullely/multi-tenant-saas (2026-10-25): the build + # stopped after 04-workers' PR went green, and every retry after it + # died on this push without reaching one step of the phase's work. + # A branch already merged is left alone; only a diverged one is + # deleted, and only under `orun/`. tooling/bootstrap/pen-reset.mjs. + - id: pen-reset + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/pen-reset.mjs", "--branch", "orun/{{ .phase.hooks.task.outputs.key }}-{{ .phase.name }}"] # EVERY PHASE IS A PULL REQUEST THAT IS VERIFIED, THEN MERGED. No # landing below says `wait: false`: each waits for its PR's own CI — # the workflow run to its last lane, not just the checks registered so @@ -922,10 +1159,21 @@ phases: epic: "{{ .inputs.epicSlug }}" branchSlug: "{{ .phase.name }}" title: "phase({{ .phase.name }}): repo born" + # CHECKED HERE, NOT BY A RUNNER (`checks: local`, orun >= v2.88.0): + # `orun validate`, then `orun plan` as the pull request and as the + # merge to main plan it, on the commit, before it is pushed. That + # is exactly what the PR's `plan` job checks — the intent, every + # component and every composition resolve — plus the merge's own + # plan, in under a second instead of a runner's ~25s, and a tree + # that fails is never pushed. The PR's CI still runs (`plan` + # alone on a bootstrap branch, .github/workflows/ci.yml); nothing + # waits for it. The merge runs every lane on main a minute later, + # for real, and that convergence is what `await` watches. + checks: local - name: 02-foundation title: The shared packages - expectedMinutes: 9 + expectedMinutes: 5 narrate: start: 'Placing the shared packages every worker builds on.' # After the convergence is green: built, not "building". @@ -946,6 +1194,17 @@ phases: prefix: BASE contract: tasks/02-foundation.TaskContract.yaml post: + # A RE-RUN MUST HAVE SOMETHING TO LAND. A convergence can fail AFTER + # its pull request merged, and the merge has already put every file + # this phase places on main; orun derives phase state from the tree, + # so a forced re-run lands an EMPTY diff while the product's CI plans + # `--changed`. Nothing redeploys, and the build reads green. So the + # phase rewrites ONE trailing marker line in each component.yaml its + # contract names — `# orun: redeploy ` — and the + # landing has a diff that re-plans exactly those components. The + # marker is a deploy trigger, not state: nothing reads it back. + - id: retouch + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/retouch.mjs", "--phase", "{{ .phase.name }}", "--affects", "{{ .baseline.dir }}/tasks/02-foundation.TaskContract.yaml"] # EVERY PHASE BRANDS WHAT IT PLACED, before it lands. # # orun writes a phase's files between its pre and post hooks (v2.58.5; @@ -971,6 +1230,17 @@ phases: # packages/contracts/package.json`. The landing stages it. - id: pnpm-lockfile run: ["pnpm", "install", "--lockfile-only"] + # CLEAR THIS LANDING'S OWN PEN BRANCH FIRST. A build that stopped + # between the pen's push and the merge leaves `orun/-` on + # the remote; the retry commits a SIBLING of that commit, so the push + # is rejected non-fast-forward — identically, on every retry, for + # ever. Observed on pullely/multi-tenant-saas (2026-10-25): the build + # stopped after 04-workers' PR went green, and every retry after it + # died on this push without reaching one step of the phase's work. + # A branch already merged is left alone; only a diverged one is + # deleted, and only under `orun/`. tooling/bootstrap/pen-reset.mjs. + - id: pen-reset + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/pen-reset.mjs", "--branch", "orun/{{ .phase.hooks.task.outputs.key }}-{{ .phase.name }}"] - id: land uses: orun.pr/land@v1 label: Packages @@ -980,6 +1250,17 @@ phases: epic: "{{ .inputs.epicSlug }}" branchSlug: "{{ .phase.name }}" title: "phase({{ .phase.name }}): shared packages" + # CHECKED HERE, NOT BY A RUNNER (`checks: local`, orun >= v2.88.0): + # `orun validate`, then `orun plan` as the pull request and as the + # merge to main plan it, on the commit, before it is pushed. That + # is exactly what the PR's `plan` job checks — the intent, every + # component and every composition resolve — plus the merge's own + # plan, in under a second instead of a runner's ~25s, and a tree + # that fails is never pushed. The PR's CI still runs (`plan` + # alone on a bootstrap branch, .github/workflows/ci.yml); nothing + # waits for it. The merge runs every lane on main a minute later, + # for real, and that convergence is what `await` watches. + checks: local await: - id: converge uses: orun.run/watch@v1 @@ -997,11 +1278,14 @@ phases: repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 waitSeconds: 1800 + # Read every 5s, not the action's 40: the build moves on the moment + # the run is green instead of up to 40s after it. + pollSeconds: 5 - name: 03-infrastructure title: The data infrastructure - expectedMinutes: 9 + expectedMinutes: 8 narrate: start: 'Creating a Supabase Postgres project and a KV namespace per environment.' done: 'Supabase and KV are up on stage and prod, their outputs published, in {{ .meta.elapsed }}.' @@ -1060,42 +1344,48 @@ phases: name: "phase({{ .phase.name }}): supabase, kv" prefix: BASE contract: tasks/03-infrastructure.TaskContract.yaml - - id: secret-workers-deploy - uses: orun.integrations/reconcile@v1 - narrate: 'CLOUDFLARE_API_TOKEN is in place, brokered from the Cloudflare connection.' - with: - provider: cloudflare - keys: [CLOUDFLARE_API_TOKEN] - template: workers-deploy - - id: secret-hyperdrive-edit - uses: orun.integrations/reconcile@v1 - narrate: 'CLOUDFLARE_HYPERDRIVE_TOKEN is in place, brokered from the Cloudflare connection.' - with: - provider: cloudflare - keys: [CLOUDFLARE_HYPERDRIVE_TOKEN] - template: hyperdrive-edit - - id: secret-account-id + # ONE HOOK PER CONNECTION (orun >= v2.87.0). `secrets:` mints each key + # under its OWN scope template from the one connection the build is + # bound to, reading the connections and the existing secrets once and + # creating the missing keys side by side. This used to be one hook per + # key, five of them, because `template:` was a property of the hook — + # and the scopes are five different scopes on purpose: the deploy + # token deliberately cannot touch Hyperdrive. The list keeps every one + # of those scopes and makes it one round trip per provider. + # + # CLOUDFLARE_HYPERDRIVE_TOKEN is not read until the next phase; it is + # minted here with its siblings because this is the phase that asks + # for the connections, and a key minted with its siblings is one the + # card lists in one place. Keys that already exist are kept. + - id: secrets-cloudflare uses: orun.integrations/reconcile@v1 - narrate: 'CLOUDFLARE_ACCOUNT_ID is in place, read from the Cloudflare connection.' + narrate: 'The Cloudflare deploy, Hyperdrive and account keys are in place, brokered from your Cloudflare connection.' with: provider: cloudflare - keys: [CLOUDFLARE_ACCOUNT_ID] - template: account-id - - id: secret-supabase-access + secrets: + - { key: CLOUDFLARE_API_TOKEN, template: workers-deploy } + - { key: CLOUDFLARE_HYPERDRIVE_TOKEN, template: hyperdrive-edit } + - { key: CLOUDFLARE_ACCOUNT_ID, template: account-id } + - id: secrets-supabase uses: orun.integrations/reconcile@v1 - narrate: 'SUPABASE_ACCESS_TOKEN is in place, brokered from the Supabase connection.' + narrate: 'The Supabase management token and org id are in place, read from your Supabase connection.' with: provider: supabase - keys: [SUPABASE_ACCESS_TOKEN] - template: management-access - - id: secret-supabase-org - uses: orun.integrations/reconcile@v1 - narrate: 'SUPABASE_ORG_ID is in place, read from the Supabase connection.' - with: - provider: supabase - keys: [SUPABASE_ORG_ID] - template: org-id + secrets: + - { key: SUPABASE_ACCESS_TOKEN, template: management-access } + - { key: SUPABASE_ORG_ID, template: org-id } post: + # A RE-RUN MUST HAVE SOMETHING TO LAND. A convergence can fail AFTER + # its pull request merged, and the merge has already put every file + # this phase places on main; orun derives phase state from the tree, + # so a forced re-run lands an EMPTY diff while the product's CI plans + # `--changed`. Nothing redeploys, and the build reads green. So the + # phase rewrites ONE trailing marker line in each component.yaml its + # contract names — `# orun: redeploy ` — and the + # landing has a diff that re-plans exactly those components. The + # marker is a deploy trigger, not state: nothing reads it back. + - id: retouch + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/retouch.mjs", "--phase", "{{ .phase.name }}", "--affects", "{{ .baseline.dir }}/tasks/03-infrastructure.TaskContract.yaml"] # Brand what this phase placed before it lands (see 02-foundation). - id: stage run: ["git", "add", "-A"] @@ -1107,6 +1397,17 @@ phases: run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] - id: pnpm-lockfile run: ["pnpm", "install", "--lockfile-only"] + # CLEAR THIS LANDING'S OWN PEN BRANCH FIRST. A build that stopped + # between the pen's push and the merge leaves `orun/-` on + # the remote; the retry commits a SIBLING of that commit, so the push + # is rejected non-fast-forward — identically, on every retry, for + # ever. Observed on pullely/multi-tenant-saas (2026-10-25): the build + # stopped after 04-workers' PR went green, and every retry after it + # died on this push without reaching one step of the phase's work. + # A branch already merged is left alone; only a diverged one is + # deleted, and only under `orun/`. tooling/bootstrap/pen-reset.mjs. + - id: pen-reset + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/pen-reset.mjs", "--branch", "orun/{{ .phase.hooks.task.outputs.key }}-{{ .phase.name }}"] - id: land uses: orun.pr/land@v1 label: Data plane @@ -1116,6 +1417,17 @@ phases: epic: "{{ .inputs.epicSlug }}" branchSlug: "{{ .phase.name }}" title: "phase({{ .phase.name }}): supabase, kv" + # CHECKED HERE, NOT BY A RUNNER (`checks: local`, orun >= v2.88.0): + # `orun validate`, then `orun plan` as the pull request and as the + # merge to main plan it, on the commit, before it is pushed. That + # is exactly what the PR's `plan` job checks — the intent, every + # component and every composition resolve — plus the merge's own + # plan, in under a second instead of a runner's ~25s, and a tree + # that fails is never pushed. The PR's CI still runs (`plan` + # alone on a bootstrap branch, .github/workflows/ci.yml); nothing + # waits for it. The merge runs every lane on main a minute later, + # for real, and that convergence is what `await` watches. + checks: local await: - id: converge uses: orun.run/watch@v1 @@ -1125,6 +1437,9 @@ phases: repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 waitSeconds: 1800 + # Read every 5s, not the action's 40: the build moves on the moment + # the run is green instead of up to 40s after it. + pollSeconds: 5 # WHERE THE OUTPUTS ARE PUBLISHED: each apply lease-publishes its # outputs to the project's ENVIRONMENT rungs (stage and prod), not to # the workspace. The flows read `--env stage` only; a prod apply that @@ -1142,13 +1457,13 @@ phases: # schema to it; both plan against supabase's published outputs on their PR, # which is why they could not land in the phase that creates them. # - # A phase of its own rather than more hooks on 03, for the reason - # 04-workers-restore is: `post` hooks all run before `await`, so "land 03, - # converge, THEN land these" cannot be one phase's hook list. It files under - # 03's milestone — it is the same unit of the product, landed in two PRs. + # A phase of its own rather than more hooks on 03: `post` hooks all run + # before `await`, so "land 03, converge, THEN land these" cannot be one + # phase's hook list. It files under 03's milestone — it is the same unit of + # the product, landed in two PRs. - name: 03-infrastructure-database title: The database is migrated and reachable - expectedMinutes: 6 + expectedMinutes: 5 narrate: start: 'Adding the schema migrations and a Hyperdrive pool per environment.' done: 'The schema is applied and Hyperdrive''s ids are published for the workers, in {{ .meta.elapsed }}.' @@ -1175,6 +1490,17 @@ phases: prefix: BASE contract: tasks/03-infrastructure-database.TaskContract.yaml post: + # A RE-RUN MUST HAVE SOMETHING TO LAND. A convergence can fail AFTER + # its pull request merged, and the merge has already put every file + # this phase places on main; orun derives phase state from the tree, + # so a forced re-run lands an EMPTY diff while the product's CI plans + # `--changed`. Nothing redeploys, and the build reads green. So the + # phase rewrites ONE trailing marker line in each component.yaml its + # contract names — `# orun: redeploy ` — and the + # landing has a diff that re-plans exactly those components. The + # marker is a deploy trigger, not state: nothing reads it back. + - id: retouch + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/retouch.mjs", "--phase", "{{ .phase.name }}", "--affects", "{{ .baseline.dir }}/tasks/03-infrastructure-database.TaskContract.yaml"] # Brand what this phase placed before it lands (see 02-foundation). - id: stage run: ["git", "add", "-A"] @@ -1186,6 +1512,17 @@ phases: run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] - id: pnpm-lockfile run: ["pnpm", "install", "--lockfile-only"] + # CLEAR THIS LANDING'S OWN PEN BRANCH FIRST. A build that stopped + # between the pen's push and the merge leaves `orun/-` on + # the remote; the retry commits a SIBLING of that commit, so the push + # is rejected non-fast-forward — identically, on every retry, for + # ever. Observed on pullely/multi-tenant-saas (2026-10-25): the build + # stopped after 04-workers' PR went green, and every retry after it + # died on this push without reaching one step of the phase's work. + # A branch already merged is left alone; only a diverged one is + # deleted, and only under `orun/`. tooling/bootstrap/pen-reset.mjs. + - id: pen-reset + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/pen-reset.mjs", "--branch", "orun/{{ .phase.hooks.task.outputs.key }}-{{ .phase.name }}"] - id: land uses: orun.pr/land@v1 label: Database @@ -1195,6 +1532,17 @@ phases: epic: "{{ .inputs.epicSlug }}" branchSlug: "{{ .phase.name }}" title: "phase(03-infrastructure): hyperdrive, db-migrate" + # CHECKED HERE, NOT BY A RUNNER (`checks: local`, orun >= v2.88.0): + # `orun validate`, then `orun plan` as the pull request and as the + # merge to main plan it, on the commit, before it is pushed. That + # is exactly what the PR's `plan` job checks — the intent, every + # component and every composition resolve — plus the merge's own + # plan, in under a second instead of a runner's ~25s, and a tree + # that fails is never pushed. The PR's CI still runs (`plan` + # alone on a bootstrap branch, .github/workflows/ci.yml); nothing + # waits for it. The merge runs every lane on main a minute later, + # for real, and that convergence is what `await` watches. + checks: local await: - id: converge uses: orun.run/watch@v1 @@ -1204,6 +1552,9 @@ phases: repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 waitSeconds: 1800 + # Read every 5s, not the action's 40: the build moves on the moment + # the run is green instead of up to 40s after it. + pollSeconds: 5 - id: verify uses: orun.secrets/exists@v1 narrate: "The Hyperdrive wiring the workers read is published on stage and prod." @@ -1214,21 +1565,23 @@ phases: - name: 04-workers title: The worker fleet - expectedMinutes: 31 + expectedMinutes: 14 narrate: start: 'Deploying the twelve-worker fleet, the longest stretch of the build.' done: 'Twelve workers are live on stage and prod, minus two bindings the next phase restores, in {{ .meta.elapsed }}.' failed: 'The fleet did not deploy; the failing step says why.' modules: [admin-worker, admin-worker-tests, billing-worker, billing-worker-tests, config-worker, config-worker-tests, events-worker, events-worker-tests, identity-worker, identity-worker-tests, integrations-worker, integrations-worker-tests, membership-worker, membership-worker-tests, metering-worker, metering-worker-tests, notifications-worker, notifications-worker-tests, policy-worker, policy-worker-tests, projects-worker, projects-worker-tests, webhooks-worker, webhooks-worker-tests] requires: + # NO WIRING PROBE. `WIRING_CLOUDFLARE_KV` is what 03-infrastructure's own + # `verify` hook waited for and `WIRING_CLOUDFLARE_HYPERDRIVE` what + # 03-infrastructure-database's did, both in this run and both immediately + # before this phase — and every worker below resolves them from the place + # every later run looks (their component.yaml secret refs), so a missing + # document fails that worker's lane rather than passing silently. The + # probe only re-asked, and a preflight that asks about the product's + # project before 01-scaffold has created it is how a fresh build used to + # stop before it started (BOOTSTRAP.md). phases: [03-infrastructure-database] - probe: - - id: wiring - uses: orun.secrets/exists@v1 - with: - keys: [WIRING_CLOUDFLARE_HYPERDRIVE, WIRING_CLOUDFLARE_KV] - project: "{{ .inputs.reponame }}" - environments: [stage, prod] hooks: pre: - id: task @@ -1237,10 +1590,21 @@ phases: kind: task epic: "{{ .inputs.epicSlug }}" milestone: "{{ .phase.name }}" - name: "phase({{ .phase.name }}): worker fleet (feedback edges stripped)" + name: "phase({{ .phase.name }}): the worker fleet" prefix: BASE contract: tasks/04-workers.TaskContract.yaml post: + # A RE-RUN MUST HAVE SOMETHING TO LAND. A convergence can fail AFTER + # its pull request merged, and the merge has already put every file + # this phase places on main; orun derives phase state from the tree, + # so a forced re-run lands an EMPTY diff while the product's CI plans + # `--changed`. Nothing redeploys, and the build reads green. So the + # phase rewrites ONE trailing marker line in each component.yaml its + # contract names — `# orun: redeploy ` — and the + # landing has a diff that re-plans exactly those components. The + # marker is a deploy trigger, not state: nothing reads it back. + - id: retouch + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/retouch.mjs", "--phase", "{{ .phase.name }}", "--affects", "{{ .baseline.dir }}/tasks/04-workers.TaskContract.yaml"] # Brand what this phase placed before it lands (see 02-foundation). - id: stage run: ["git", "add", "-A"] @@ -1252,20 +1616,32 @@ phases: run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] - id: pnpm-lockfile run: ["pnpm", "install", "--lockfile-only"] - # The Cloudflare service-binding two-pass. The + # CLEAR THIS LANDING'S OWN PEN BRANCH FIRST. A build that stopped + # between the pen's push and the merge leaves `orun/-` on + # the remote; the retry commits a SIBLING of that commit, so the push + # is rejected non-fast-forward — identically, on every retry, for + # ever. Observed on pullely/multi-tenant-saas (2026-10-25): the build + # stopped after 04-workers' PR went green, and every retry after it + # died on this push without reaching one step of the phase's work. + # A branch already merged is left alone; only a diverged one is + # deleted, and only under `orun/`. tooling/bootstrap/pen-reset.mjs. + - id: pen-reset + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/pen-reset.mjs", "--branch", "orun/{{ .phase.hooks.task.outputs.key }}-{{ .phase.name }}"] + # THE FLEET DEPLOYS ONCE, WITH ITS BINDINGS. The # {billing,membership,events,notifications} cluster binds to itself # (billing <-> membership; membership -> notifications -> events -> # membership), and a binding cannot name a worker that does not exist - # yet (Cloudflare error 10143), so the first pass deploys without the - # two feedback edges. + # yet (Cloudflare error 10143), so on a fresh account no order of + # first deploys works. This phase used to strip the two feedback + # edges from the wrangler config and land a second time to put them + # back — two landings, two convergences, the fleet deployed twice. # - # These edges are NOT in the module DAG and there is no `cycleBreak:` - # here to defer — the cycle lives in the wrangler config a deploy - # reads, not in the placement order, so orun never sees it. That is - # why cycle-break.mjs survives BE1: it is not an ordering workaround - # orun's DAG could absorb, it is a deploy-time edit to a file. - - id: strip - run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/cycle-break.mjs", "--strip"] + # Now policy-worker binds to nothing, every binding holder waits on it + # (`mode: enforced` on main), and its pre-deploy uploads a placeholder + # for every binding target that does not exist yet + # (tooling/deploy/fleet-stubs.mjs). Each worker's first deploy carries + # its full bindings and replaces its own placeholder. Nothing is + # edited here, and 04-workers-restore is gone. - id: land uses: orun.pr/land@v1 label: Fleet @@ -1274,9 +1650,18 @@ phases: task: "{{ .phase.hooks.task.outputs.key }}" epic: "{{ .inputs.epicSlug }}" branchSlug: "{{ .phase.name }}" - title: "phase({{ .phase.name }}): worker fleet (feedback edges stripped)" - # Twelve workers' verify lanes, on two environments. - checkTimeoutSeconds: 3600 + title: "phase({{ .phase.name }}): the worker fleet" + # CHECKED HERE, NOT BY A RUNNER (`checks: local`, orun >= v2.88.0): + # `orun validate`, then `orun plan` as the pull request and as the + # merge to main plan it, on the commit, before it is pushed. That + # is exactly what the PR's `plan` job checks — the intent, every + # component and every composition resolve — plus the merge's own + # plan, in under a second instead of a runner's ~25s, and a tree + # that fails is never pushed. The PR's CI still runs (`plan` + # alone on a bootstrap branch, .github/workflows/ci.yml); nothing + # waits for it. The merge runs every lane on main a minute later, + # for real, and that convergence is what `await` watches. + checks: local await: - id: converge uses: orun.run/watch@v1 @@ -1286,79 +1671,33 @@ phases: repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 waitSeconds: 3600 - - # The second pass, and a phase of its own rather than more hooks on the - # first. The restore can only run AFTER 04-workers has converged — a service - # binding may not name a worker that is not deployed — and `post` hooks all - # run before `await`, so "strip, land, converge, restore, land, converge" - # cannot be one phase's hook list. It is also, already, two landings with two - # PRs and two task contracts. Two units of work that land separately are two - # phases; that is the whole of what a phase is here. - - name: 04-workers-restore - title: The service bindings come back - expectedMinutes: 5 - narrate: - start: 'Restoring the two service bindings the fleet deployed without.' - done: 'Billing and membership are redeployed with their bindings; the fleet is fully wired.' - failed: 'The bindings did not go back; the workers are up, but billing and membership cannot call across the loop.' - modules: [] - requires: - phases: [04-workers] - hooks: - pre: - - id: task - uses: orun.task/ensure@v1 - with: - kind: task - epic: "{{ .inputs.epicSlug }}" - milestone: 04-workers - name: "phase(04-workers): restore service-binding feedback edges" - prefix: BASE - contract: tasks/04-workers-restore.TaskContract.yaml - post: - - id: restore - run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/cycle-break.mjs", "--restore"] - - id: land - uses: orun.pr/land@v1 - label: Bindings - narrate: '{{ if eq .hooks.land.outputs.landed "true" }}PR #{{ .hooks.land.outputs.number }} is merged into main.{{ else }}Nothing new to land; main already has it.{{ end }}' - with: - task: "{{ .phase.hooks.task.outputs.key }}" - epic: "{{ .inputs.epicSlug }}" - branchSlug: "{{ .phase.name }}" - title: "phase(04-workers): restore service-binding feedback edges" - await: - - id: converge - uses: orun.run/watch@v1 - narrate: 'Billing and membership redeployed with their bindings.' - with: - sha: "{{ .phase.hooks.land.outputs.mergeSha }}" - repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" - resumeBudget: 2 - waitSeconds: 1800 + # Read every 5s, not the action's 40: the build moves on the moment + # the run is green instead of up to 40s after it. + pollSeconds: 5 - name: 05-edge title: The API edge - expectedMinutes: 5 + expectedMinutes: 4 narrate: start: 'Deploying the API edge in front of the twelve services.' done: 'The edge is live on stage and prod, answering /health, in {{ .meta.elapsed }}.' failed: 'The edge did not come up; the failing step says why.' modules: [api-edge, api-edge-tests, platform-limits-tests] requires: - # 04-WORKERS, NOT 04-WORKERS-RESTORE, and the reason is what a gate can - # know. The restore places no files, so orun derives it as `unknown` — - # deliberately, because its work is a landing in the task plane and a - # deployment, neither of which the product repo can be asked about. A - # requirement on it could therefore NEVER be satisfied, and this phase - # refused for the whole of a real bootstrap: + # A GATE MAY ONLY NAME A PHASE THAT PLACES FILES. This used to require + # `04-workers-restore`, which placed none, so orun derived it as + # `unknown` — deliberately, its work being a landing and a deployment, + # neither of which the product repo can be asked about — and the + # requirement could therefore NEVER be satisfied. This phase refused for + # the whole of a real bootstrap: # # ✕ phase "05-edge" requires 04-workers-restore (unknown) # - # The ordering is not lost by naming its predecessor instead. Phase order - # in this document is what sequences a run; `requires` is the gate that - # catches somebody running 05 against a tree where 04 never happened, - # and `04-workers` answers exactly that, from the files on disk. + # That phase is gone (the fleet deploys once, with its bindings), and + # `04-workers` is both its predecessor and a phase that places files, so + # the gate answers from the files on disk. Phase order in this document + # is what sequences a run; `requires` only catches somebody running 05 + # against a tree where 04 never happened. phases: [04-workers] hooks: pre: @@ -1372,6 +1711,17 @@ phases: prefix: BASE contract: tasks/05-edge.TaskContract.yaml post: + # A RE-RUN MUST HAVE SOMETHING TO LAND. A convergence can fail AFTER + # its pull request merged, and the merge has already put every file + # this phase places on main; orun derives phase state from the tree, + # so a forced re-run lands an EMPTY diff while the product's CI plans + # `--changed`. Nothing redeploys, and the build reads green. So the + # phase rewrites ONE trailing marker line in each component.yaml its + # contract names — `# orun: redeploy ` — and the + # landing has a diff that re-plans exactly those components. The + # marker is a deploy trigger, not state: nothing reads it back. + - id: retouch + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/retouch.mjs", "--phase", "{{ .phase.name }}", "--affects", "{{ .baseline.dir }}/tasks/05-edge.TaskContract.yaml"] # Brand what this phase placed before it lands (see 02-foundation). - id: stage run: ["git", "add", "-A"] @@ -1383,6 +1733,17 @@ phases: run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] - id: pnpm-lockfile run: ["pnpm", "install", "--lockfile-only"] + # CLEAR THIS LANDING'S OWN PEN BRANCH FIRST. A build that stopped + # between the pen's push and the merge leaves `orun/-` on + # the remote; the retry commits a SIBLING of that commit, so the push + # is rejected non-fast-forward — identically, on every retry, for + # ever. Observed on pullely/multi-tenant-saas (2026-10-25): the build + # stopped after 04-workers' PR went green, and every retry after it + # died on this push without reaching one step of the phase's work. + # A branch already merged is left alone; only a diverged one is + # deleted, and only under `orun/`. tooling/bootstrap/pen-reset.mjs. + - id: pen-reset + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/pen-reset.mjs", "--branch", "orun/{{ .phase.hooks.task.outputs.key }}-{{ .phase.name }}"] - id: land uses: orun.pr/land@v1 label: API edge @@ -1392,6 +1753,17 @@ phases: epic: "{{ .inputs.epicSlug }}" branchSlug: "{{ .phase.name }}" title: "phase({{ .phase.name }}): api-edge" + # CHECKED HERE, NOT BY A RUNNER (`checks: local`, orun >= v2.88.0): + # `orun validate`, then `orun plan` as the pull request and as the + # merge to main plan it, on the commit, before it is pushed. That + # is exactly what the PR's `plan` job checks — the intent, every + # component and every composition resolve — plus the merge's own + # plan, in under a second instead of a runner's ~25s, and a tree + # that fails is never pushed. The PR's CI still runs (`plan` + # alone on a bootstrap branch, .github/workflows/ci.yml); nothing + # waits for it. The merge runs every lane on main a minute later, + # for real, and that convergence is what `await` watches. + checks: local await: - id: converge uses: orun.run/watch@v1 @@ -1401,6 +1773,9 @@ phases: repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 waitSeconds: 1800 + # Read every 5s, not the action's 40: the build moves on the moment + # the run is green instead of up to 40s after it. + pollSeconds: 5 - id: verify uses: orun.http/probe@v1 narrate: 'Both /health endpoints answered.' @@ -1419,7 +1794,7 @@ phases: # gap so 08-docs keeps its name. - name: 06-console title: The web console - expectedMinutes: 16 + expectedMinutes: 13 narrate: start: 'Building and deploying the web console.' done: 'The console is live on stage and prod, in {{ .meta.elapsed }}.' @@ -1439,6 +1814,17 @@ phases: prefix: BASE contract: tasks/06-console.TaskContract.yaml post: + # A RE-RUN MUST HAVE SOMETHING TO LAND. A convergence can fail AFTER + # its pull request merged, and the merge has already put every file + # this phase places on main; orun derives phase state from the tree, + # so a forced re-run lands an EMPTY diff while the product's CI plans + # `--changed`. Nothing redeploys, and the build reads green. So the + # phase rewrites ONE trailing marker line in each component.yaml its + # contract names — `# orun: redeploy ` — and the + # landing has a diff that re-plans exactly those components. The + # marker is a deploy trigger, not state: nothing reads it back. + - id: retouch + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/retouch.mjs", "--phase", "{{ .phase.name }}", "--affects", "{{ .baseline.dir }}/tasks/06-console.TaskContract.yaml"] # Brand what this phase placed before it lands (see 02-foundation). - id: stage run: ["git", "add", "-A"] @@ -1450,6 +1836,17 @@ phases: run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] - id: pnpm-lockfile run: ["pnpm", "install", "--lockfile-only"] + # CLEAR THIS LANDING'S OWN PEN BRANCH FIRST. A build that stopped + # between the pen's push and the merge leaves `orun/-` on + # the remote; the retry commits a SIBLING of that commit, so the push + # is rejected non-fast-forward — identically, on every retry, for + # ever. Observed on pullely/multi-tenant-saas (2026-10-25): the build + # stopped after 04-workers' PR went green, and every retry after it + # died on this push without reaching one step of the phase's work. + # A branch already merged is left alone; only a diverged one is + # deleted, and only under `orun/`. tooling/bootstrap/pen-reset.mjs. + - id: pen-reset + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/pen-reset.mjs", "--branch", "orun/{{ .phase.hooks.task.outputs.key }}-{{ .phase.name }}"] - id: land uses: orun.pr/land@v1 label: Console @@ -1459,8 +1856,18 @@ phases: epic: "{{ .inputs.epicSlug }}" branchSlug: "{{ .phase.name }}" title: "phase({{ .phase.name }}): web console" + # CHECKED HERE, NOT BY A RUNNER (`checks: local`, orun >= v2.88.0): + # `orun validate`, then `orun plan` as the pull request and as the + # merge to main plan it, on the commit, before it is pushed. That + # is exactly what the PR's `plan` job checks — the intent, every + # component and every composition resolve — plus the merge's own + # plan, in under a second instead of a runner's ~25s, and a tree + # that fails is never pushed. The PR's CI still runs (`plan` + # alone on a bootstrap branch, .github/workflows/ci.yml); nothing + # waits for it. The merge runs every lane on main a minute later, + # for real, and that convergence is what `await` watches. + checks: local # Console builds are the heaviest lane in the product. - checkTimeoutSeconds: 2700 await: - id: converge uses: orun.run/watch@v1 @@ -1470,6 +1877,9 @@ phases: repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 waitSeconds: 2700 + # Read every 5s, not the action's 40: the build moves on the moment + # the run is green instead of up to 40s after it. + pollSeconds: 5 - id: verify uses: orun.http/probe@v1 narrate: 'Every console and edge URL answered.' @@ -1485,7 +1895,7 @@ phases: # and why its verify is the same probe 06-console ends on. - name: 08-docs title: The deployment, recorded - expectedMinutes: 1 + expectedMinutes: 2 narrate: start: 'Recording the live deployment in the repository.' done: 'ai/context/deployment.md records the live deployment, from probed facts.' @@ -1505,9 +1915,31 @@ phases: prefix: BASE contract: tasks/08-docs.TaskContract.yaml post: + # THE PRODUCT GOES LIVE WITH ITS PROMOTION GATE. 01-scaffold deferred + # `prod.promotion.dependsOn: [stage]`; this, the last landing, puts it + # back, and from here on a change reaches prod only after stage. + # Restoring touches only intent.yaml's `environments` section, which + # `orun plan --changed` maps to no component, so this landing + # redeploys nothing. + - id: promotion + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/promotion.mjs", "--restore"] + # And dev verifies every merge to main again (01-scaffold deferred it). + - id: dev-lanes + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/dev-lanes.mjs", "--restore"] - id: render narrate: 'ai/context/deployment.md is written from the live probes.' run: ["bash", "{{ .baseline.dir }}/hooks/render-deployment-docs.sh", ".", "{{ .inputs.orunWorkspace }}", "{{ .baseline.dir }}"] + # CLEAR THIS LANDING'S OWN PEN BRANCH FIRST. A build that stopped + # between the pen's push and the merge leaves `orun/-` on + # the remote; the retry commits a SIBLING of that commit, so the push + # is rejected non-fast-forward — identically, on every retry, for + # ever. Observed on pullely/multi-tenant-saas (2026-10-25): the build + # stopped after 04-workers' PR went green, and every retry after it + # died on this push without reaching one step of the phase's work. + # A branch already merged is left alone; only a diverged one is + # deleted, and only under `orun/`. tooling/bootstrap/pen-reset.mjs. + - id: pen-reset + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/pen-reset.mjs", "--branch", "orun/{{ .phase.hooks.task.outputs.key }}-{{ .phase.name }}"] - id: land uses: orun.pr/land@v1 label: Docs @@ -1517,6 +1949,17 @@ phases: epic: "{{ .inputs.epicSlug }}" branchSlug: "{{ .phase.name }}" title: "docs(deployment): record live deployment state" + # CHECKED HERE, NOT BY A RUNNER (`checks: local`, orun >= v2.88.0): + # `orun validate`, then `orun plan` as the pull request and as the + # merge to main plan it, on the commit, before it is pushed. That + # is exactly what the PR's `plan` job checks — the intent, every + # component and every composition resolve — plus the merge's own + # plan, in under a second instead of a runner's ~25s, and a tree + # that fails is never pushed. The PR's CI still runs (`plan` + # alone on a bootstrap branch, .github/workflows/ci.yml); nothing + # waits for it. The merge runs every lane on main a minute later, + # for real, and that convergence is what `await` watches. + checks: local await: # QUIET: the same four URLs 06-console just probed. Their addresses # are already on the build page; a second set of the same facts is diff --git a/tasks/04-workers-restore.TaskContract.yaml b/tasks/04-workers-restore.TaskContract.yaml deleted file mode 100644 index 7a923e5..0000000 --- a/tasks/04-workers-restore.TaskContract.yaml +++ /dev/null @@ -1,26 +0,0 @@ -# Task contract template for the 04-workers landing (saas-baseline-tracking BT1). -# Unbound to a key on purpose: `orun task create --contract` seals and -# attaches it to the key the allocator issues. gates: [] is a DECLARATION — -# merge alone finishes this task; the main convergence is the gate the flow -# watches, not one the plane observes as a PR check. -apiVersion: orun.io/v1 -kind: TaskContract -spec: - goal: The fleet's service-binding feedback edges are restored and the fleet converges again - affects: - - admin-worker - - billing-worker - - config-worker - - events-worker - - identity-worker - - integrations-worker - - membership-worker - - metering-worker - - notifications-worker - - policy-worker - - projects-worker - - webhooks-worker - doneWhen: - - feedback edges restored and convergence green - - worker bindings verified - gates: [] diff --git a/tasks/04-workers.TaskContract.yaml b/tasks/04-workers.TaskContract.yaml index d53c8a9..76c707d 100644 --- a/tasks/04-workers.TaskContract.yaml +++ b/tasks/04-workers.TaskContract.yaml @@ -6,7 +6,7 @@ apiVersion: orun.io/v1 kind: TaskContract spec: - goal: The 12-worker fleet lands with service-binding feedback edges stripped so first-boot workers deploy in DAG order + goal: The 12-worker fleet lands and deploys once, each worker carrying its full service bindings affects: - admin-worker - billing-worker @@ -21,5 +21,5 @@ spec: - projects-worker - webhooks-worker doneWhen: - - convergence green with feedback edges stripped + - convergence green with every service binding in place gates: [] diff --git a/testing/bootstrap-defer.test.sh b/testing/bootstrap-defer.test.sh new file mode 100755 index 0000000..7b723d6 --- /dev/null +++ b/testing/bootstrap-defer.test.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# The two things a bootstrap turns off in intent.yaml and puts back — +# `prod.promotion` (tooling/bootstrap/promotion.mjs) and dev's push-to-main +# activation (tooling/bootstrap/dev-lanes.mjs) — must each defer, be +# idempotent both ways, leave a parseable intent while deferred, and restore +# the file BYTE-FOR-BYTE: a restore that reproduced the block by hand would +# be a second place the intent is authored. +set -euo pipefail +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +root="$(cd "$here/.." && pwd)" +fail=0 +ok() { echo " ok $1"; } +bad() { echo " ✕ $1" >&2; fail=1; } + +tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT +cp "$root/intent.yaml" "$tmp/intent.yaml" + +for tool in promotion dev-lanes; do + f="$tmp/intent.yaml"; cp "$root/intent.yaml" "$f" + echo "── $tool.mjs" + node "$root/tooling/bootstrap/$tool.mjs" --check --file "$f" | grep -q -E 'enforced|active' && ok "starts enforced/active" || bad "starts enforced/active" + node "$root/tooling/bootstrap/$tool.mjs" --defer --file "$f" >/dev/null + node "$root/tooling/bootstrap/$tool.mjs" --check --file "$f" | grep -q deferred && ok "--defer defers" || bad "--defer defers" + python3 -c "import yaml,sys; yaml.safe_load(open(sys.argv[1]))" "$f" && ok "deferred intent still parses" || bad "deferred intent still parses" + cp "$f" "$tmp/once.yaml"; node "$root/tooling/bootstrap/$tool.mjs" --defer --file "$f" >/dev/null + cmp -s "$f" "$tmp/once.yaml" && ok "a second --defer changes nothing" || bad "a second --defer changes nothing" + node "$root/tooling/bootstrap/$tool.mjs" --restore --file "$f" >/dev/null + cmp -s "$f" "$root/intent.yaml" && ok "--restore is byte-exact" || bad "--restore is byte-exact" + node "$root/tooling/bootstrap/$tool.mjs" --restore --file "$f" >/dev/null + cmp -s "$f" "$root/intent.yaml" && ok "a second --restore changes nothing" || bad "a second --restore changes nothing" +done + +echo "── what each deferral means to a push-to-main plan" +f="$tmp/intent.yaml"; cp "$root/intent.yaml" "$f" +node "$root/tooling/bootstrap/dev-lanes.mjs" --defer --file "$f" >/dev/null +python3 - "$f" <<'PY' && ok "dev is no longer activated by github-push-main while deferred" || bad "dev is no longer activated by github-push-main while deferred" +import sys, yaml +d = yaml.safe_load(open(sys.argv[1])) +refs = d["environments"]["dev"]["activation"]["triggerRefs"] +assert "github-push-main" not in refs and "github-pull-request" in refs, refs +PY +f="$tmp/intent.yaml"; cp "$root/intent.yaml" "$f" +node "$root/tooling/bootstrap/promotion.mjs" --defer --file "$f" >/dev/null +python3 - "$f" <<'PY' && ok "prod has no promotion gate while deferred" || bad "prod has no promotion gate while deferred" +import sys, yaml +d = yaml.safe_load(open(sys.argv[1])) +assert "promotion" not in d["environments"]["prod"], d["environments"]["prod"].keys() +PY + +if [ "$fail" -ne 0 ]; then echo "bootstrap-defer.test.sh: failure(s)" >&2; exit 1; fi +echo "bootstrap-defer.test.sh: ok" diff --git a/testing/fleet-stubs.test.sh b/testing/fleet-stubs.test.sh new file mode 100755 index 0000000..1ad22a8 --- /dev/null +++ b/testing/fleet-stubs.test.sh @@ -0,0 +1,100 @@ +#!/usr/bin/env bash +# tooling/deploy/fleet-stubs.mjs, against a fake Cloudflare API: it names +# every binding target of the environment, uploads a placeholder for exactly +# the missing ones (never for one that exists), does nothing on a live +# product, refuses to guess when the existence check errors, and the fleet's +# binding holders all wait on the worker whose pre-deploy runs it. +set -euo pipefail +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +root="$(cd "$here/.." && pwd)" +tool="$root/tooling/deploy/fleet-stubs.mjs" +fail=0 +ok() { echo " ok $1"; } +bad() { echo " ✕ $1" >&2; fail=1; } + +tmp="$(mktemp -d)" +cleanup() { [ -n "${srv:-}" ] && kill "$srv" 2>/dev/null; rm -rf "$tmp"; } +trap cleanup EXIT + +echo "── targets" +node "$tool" --root "$root" --env stage --list > "$tmp/stage" +node "$tool" --root "$root" --env prod --list > "$tmp/prod" +[ "$(wc -l < "$tmp/stage")" -ge 10 ] && ok "stage names the fleet's binding targets ($(wc -l < "$tmp/stage"))" || bad "stage names the fleet's binding targets" +grep -q -- '-membership-worker-stage$' "$tmp/stage" && ok "a stage target carries the -stage suffix" || bad "a stage target carries the -stage suffix" +! grep -q -- '-stage$' "$tmp/prod" && ok "prod names no stage Worker" || bad "prod names no stage Worker" +[ -z "$(node "$tool" --root "$root" --env dev --list)" ] && ok "dev binds nothing, so it stubs nothing" || bad "dev binds nothing, so it stubs nothing" + +# A fake API: GET .../scripts//settings answers 200 for names in +# $tmp/exists, 404 otherwise (500 for a name containing "boom"); PUT +# .../scripts/ records the name and its upload in $tmp/puts. +cat > "$tmp/api.mjs" <<'JS' +import http from "node:http"; +import fs from "node:fs"; +const dir = process.argv[2]; +const server = http.createServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + if (req.headers.authorization !== "Bearer t0k") { res.writeHead(403); return res.end("auth"); } + const m = req.url.match(/^\/client\/v4\/accounts\/acct\/workers\/scripts\/([^/]+)(\/settings)?$/); + if (!m) { res.writeHead(400); return res.end("url"); } + const name = decodeURIComponent(m[1]); + const exists = fs.readFileSync(`${dir}/exists`, "utf8").split("\n").includes(name); + if (req.method === "GET" && m[2]) { + if (name.includes("boom")) { res.writeHead(500); return res.end("upstream"); } + res.writeHead(exists ? 200 : 404); return res.end("{}"); + } + if (req.method === "PUT" && !m[2]) { + fs.appendFileSync(`${dir}/puts`, `${name}\n`); + fs.writeFileSync(`${dir}/upload-${name}`, body); + res.writeHead(200); return res.end("{}"); + } + res.writeHead(405); res.end(); + }); +}); +server.listen(0, "127.0.0.1", () => fs.writeFileSync(`${dir}/port`, String(server.address().port))); +JS +: > "$tmp/exists"; : > "$tmp/puts" +node "$tmp/api.mjs" "$tmp" & srv=$! +for _ in $(seq 1 50); do [ -s "$tmp/port" ] && break; sleep 0.1; done +export CLOUDFLARE_API_BASE_URL="http://127.0.0.1:$(cat "$tmp/port")/client/v4" +export CLOUDFLARE_ACCOUNT_ID=acct CLOUDFLARE_API_TOKEN=t0k + +echo "── a fresh account: every target is created" +ORUN_ENVIRONMENT=stage node "$tool" --root "$root" > "$tmp/out" +cmp -s <(sort "$tmp/puts") "$tmp/stage" && ok "one placeholder per missing target, no others" || bad "one placeholder per missing target, no others" +f="$tmp/upload-$(head -1 "$tmp/stage")" +grep -q '"main_module":"stub.mjs"' "$f" && grep -q 'export default' "$f" && ok "the upload is a module Worker with metadata" || bad "the upload is a module Worker with metadata" + +echo "── a half-built account: only the missing ones" +head -4 "$tmp/stage" > "$tmp/exists"; : > "$tmp/puts" +ORUN_ENVIRONMENT=stage node "$tool" --root "$root" >/dev/null +cmp -s <(sort "$tmp/puts") <(tail -n +5 "$tmp/stage") && ok "an existing Worker is never replaced" || bad "an existing Worker is never replaced" + +echo "── a live product: nothing" +cp "$tmp/stage" "$tmp/exists"; : > "$tmp/puts" +ORUN_ENVIRONMENT=stage node "$tool" --root "$root" > "$tmp/out" +[ ! -s "$tmp/puts" ] && grep -q "nothing to do" "$tmp/out" && ok "uploads nothing when every target exists" || bad "uploads nothing when every target exists" + +echo "── refusals" +CLOUDFLARE_API_TOKEN=wrong ORUN_ENVIRONMENT=stage node "$tool" --root "$root" >/dev/null 2>&1 && bad "an unexpected check answer (403) fails" || ok "an unexpected check answer (403) fails" +env -u ORUN_ENVIRONMENT node "$tool" --root "$root" >/dev/null 2>&1 && bad "no environment fails" || ok "no environment fails" + +echo "── the plan's side: every binding holder waits on policy-worker on main" +holders=0; missing="" +for t in "$root"/apps/*/wrangler.template.jsonc "$root"/apps/*/wrangler.jsonc; do + [ -f "$t" ] || continue + grep -q '"services"' "$t" || continue + app="$(basename "$(dirname "$t")")"; holders=$((holders + 1)) + python3 - "$root/apps/$app/component.yaml" <<'PY' || missing="$missing $app" +import sys, yaml +spec = yaml.safe_load(open(sys.argv[1]))["spec"] +deps = {d["component"]: d for d in spec.get("dependsOn", [])} +assert deps.get("policy-worker", {}).get("mode") == "enforced", deps.keys() +PY +done +[ -z "$missing" ] && ok "all $holders binding holders depend on policy-worker, enforced" || bad "not enforced on policy-worker:$missing" +grep -q 'fleet-stubs.mjs' "$root/apps/policy-worker/component.yaml" && ok "policy-worker's pre-deploy runs the tool" || bad "policy-worker's pre-deploy runs the tool" +! grep -q '"services"' "$root/apps/policy-worker/wrangler.jsonc" 2>/dev/null && ok "policy-worker itself binds nothing" || bad "policy-worker itself binds nothing" + +exit "$fail" diff --git a/testing/manifest.test.sh b/testing/manifest.test.sh index 737578b..3c51064 100755 --- a/testing/manifest.test.sh +++ b/testing/manifest.test.sh @@ -86,13 +86,21 @@ def uses(phase, action): # THE SECRETS THE BOOTSTRAP MINTS. `orun.integrations/reconcile@v1` is what # `create-secrets.sh` was written out longhand as: one connection, one scope # template, the keys it ensures. Read per key so a hook minting two keys under -# one template is three facts rather than one. +# one template is two facts rather than one. +# +# TWO SHAPES, because orun v2.87.0 added the second. The old one is a hook per +# template (`keys:` + `template:`); the new one is a hook per CONNECTION whose +# `secrets:` list carries a template per key — same scopes, one round trip. +# Both are read here so this check cannot go blind on either. blueprint_secrets = {} for phase in bp_phases: for hook in uses(phase, "orun.integrations/reconcile@v1"): w = hook.get("with") or {} for key in (w.get("keys") or []): blueprint_secrets[key] = (w.get("provider"), w.get("template")) + for entry in (w.get("secrets") or []): + if entry.get("key"): + blueprint_secrets[entry["key"]] = (w.get("provider"), entry.get("template")) if bp is not None and not bp_phases: bad("repo-blueprint.yaml declares no phases — this check has gone blind") diff --git a/testing/pen-reset.test.sh b/testing/pen-reset.test.sh new file mode 100755 index 0000000..bf8e812 --- /dev/null +++ b/testing/pen-reset.test.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +# A STOPPED BUILD MUST NOT POISON EVERY RETRY. +# +# `orun.pr/land@v1` pushes a phase to the provenance pen's branch, +# `orun/-`, with a plain `git push -u`. A build that stops +# between that push and the merge leaves the branch and its pull request on the +# remote. The retry re-places the phase and commits a SIBLING of that commit, +# so the push is rejected non-fast-forward — identically, on every retry, for +# ever. Seen on pullely/multi-tenant-saas (2026-10-25): the build stopped after +# 04-workers' PR went green, and every retry after it died on this push without +# reaching one step of the phase's work. +# +# Each landing's `pen-reset` hook (tooling/bootstrap/pen-reset.mjs) clears its +# own branch first. This test asserts the whole chain against a real remote: +# the rejection happens, the tool spots it, the delete unblocks the push, a +# merged branch is left alone, and nothing outside `orun/` can ever be touched. +set -uo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +tool="$root/tooling/bootstrap/pen-reset.mjs" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +failures=0 +fail() { echo " ✕ $*" >&2; failures=$((failures + 1)); } +ok() { echo " ✓ $*"; } + +export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null +git init -q --bare "$tmp/remote" +git init -q "$tmp/work" && cd "$tmp/work" +git config user.email t@example.invalid && git config user.name "pen test" +echo base > f && git add -A && git commit -qm base && git branch -M main +git remote add origin "$tmp/remote" && git push -q -u origin main 2>/dev/null + +BR=orun/BASE-5-04-workers + +echo "── the guard: only the pen's own namespace" +for bad in main refs/heads/main "orun/../../main" "orun/*" ""; do + if node "$tool" --branch "$bad" >/dev/null 2>&1; then + fail "accepted branch '$bad' — the guard must refuse anything but orun/-" + fi +done +ok "main, a path escape, a wildcard and an empty name are all refused" + +echo "── nothing to clear" +out="$(node "$tool" --branch "$BR" 2>&1)" +[ $? -eq 0 ] && [[ "$out" == *"nothing to clear"* ]] \ + || fail "a branch that is not on the remote should be a quiet no-op, got: $out" +ok "a branch the remote does not have is a no-op" + +echo "── a stopped build leaves a branch, and the retry's push is rejected" +git checkout -q -b "$BR" && echo run1 > g && git add -A && git commit -qm "run 1" +git push -q origin "$BR" 2>/dev/null +git checkout -q main +git checkout -q -b retry && echo run2 > g && git add -A && git commit -qm "run 2" +if git push -q origin "retry:$BR" 2>"$tmp/push.err"; then + fail "the push succeeded — this test no longer reproduces the failure it guards" +else + grep -q "non-fast-forward" "$tmp/push.err" \ + && ok "the push is rejected non-fast-forward, as it was on the real build" \ + || fail "rejected for another reason: $(head -1 "$tmp/push.err")" +fi + +echo "── --check reports it without changing anything" +node "$tool" --branch "$BR" --check >/dev/null 2>&1 +[ $? -eq 1 ] || fail "--check should exit non-zero on a diverged branch" +[ "$(git ls-remote --heads origin "$BR" | wc -l)" -eq 1 ] \ + || fail "--check deleted the branch; it must only report" +ok "--check reports the divergence and leaves the branch alone" + +echo "── the reset clears it and the same push then succeeds" +node "$tool" --branch "$BR" >/dev/null 2>&1 || fail "the reset failed" +[ "$(git ls-remote --heads origin "$BR" | wc -l)" -eq 0 ] || fail "the branch is still on the remote" +git push -q origin "retry:$BR" 2>/dev/null \ + && ok "the landing's push goes through" \ + || fail "the push still fails after the reset" + +echo "── a branch already merged is left alone" +git checkout -q main && git merge -q --no-ff -m merge retry && git push -q origin main 2>/dev/null +out="$(node "$tool" --branch "$BR" 2>&1)" +[[ "$out" == *"already in this history"* ]] || fail "a merged branch should be left alone, got: $out" +[ "$(git ls-remote --heads origin "$BR" | wc -l)" -eq 1 ] \ + || fail "a merged branch was deleted; the push would have fast-forwarded" +ok "a merged branch is kept — its push would fast-forward" + +echo "── an unreachable remote is reported, not fatal" +git remote set-url origin "$tmp/does-not-exist" +out="$(node "$tool" --branch "$BR" 2>&1)" +[ $? -eq 0 ] && [[ "$out" == *"could not reach"* ]] \ + || fail "an unreachable remote must be best-effort, got: $out" +ok "a remote it cannot reach is reported and the landing still runs" + +echo +if [ "$failures" -ne 0 ]; then echo "pen-reset.test.sh: $failures failure(s)" >&2; exit 1; fi +echo "pen-reset.test.sh: ok" diff --git a/testing/phases.test.sh b/testing/phases.test.sh index 1884bc2..9bc9b26 100755 --- a/testing/phases.test.sh +++ b/testing/phases.test.sh @@ -54,9 +54,9 @@ WAS = { # against `agents/` and `ai/state.json` — files no product receives # (orun-cloud saas-build-panel BV4; the leak gate refuses it now). "01-scaffold": ["ai-deployment", "ai-operations", "github-workflows", "rebrand-values", "root-gitignore", - "root-intent", "root-kiox", "root-kiox-lock", "root-package-json", + "root-intent", "root-package-json", "root-pnpm-lock", "root-pnpm-workspace", "root-readme", "root-turbo", - "tooling-eslint", "tooling-tsconfig", "tooling-wire"], + "tooling-deploy", "tooling-eslint", "tooling-tsconfig", "tooling-wire"], "02-foundation": ["cli", "contracts", "contracts-tests", "db", "db-tests", "notifications-client", "notifications-client-tests", "policy-engine", "policy-engine-tests", "sdk", "shared", "testing", "webhook-verifier"], @@ -92,7 +92,7 @@ WAS = { # `root-agents` is the product's AGENTS.md (saas-build-panel BV4): the page an # agent handed the product reads first. ADDED = {"01-scaffold": ["discovery-roots", "root-agents"], "05-edge": ["platform-limits-tests"]} -HOOK_ONLY = {"04-workers-restore", "08-docs"} +HOOK_ONLY = {"08-docs"} by_name = {p["name"]: p for p in phases} names = [p["name"] for p in phases] @@ -175,10 +175,10 @@ for p in phases: # This replaces BE1's "every flows/phases folder has a phase declared here". # The folders are gone (BE4), and the thing that can now drift out from under # a reader is `docs/phases/`: a page for a phase nobody runs, or a phase -# nobody documented. `04-workers-restore` is deliberately covered by +# nobody documented. `03-infrastructure-database` is deliberately covered by # `04-workers.md`, and `03-infrastructure-database` by `03-infrastructure.md` # — each pair of landings is one story, filed under one milestone. -DOC_SHARED = {"04-workers-restore": "04-workers", "03-infrastructure-database": "03-infrastructure"} +DOC_SHARED = {"03-infrastructure-database": "03-infrastructure"} docs_dir = root / "docs" / "phases" pages = {f.stem for f in docs_dir.glob("*.md")} - {"README", "TIMINGS"} for p in phases: diff --git a/testing/placement.test.sh b/testing/placement.test.sh index 4608ac3..7c9c9c3 100755 --- a/testing/placement.test.sh +++ b/testing/placement.test.sh @@ -73,9 +73,19 @@ if ! orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" "${sets[@]}" fi # ── the gates that ride inside the placement ─────────────────────────────── -# `orun new` prints this line only after running validate + plan --dry-run in -# the produced tree. Its absence means the tier lost a check without failing. -grep -q "repo gate: validate + plan --dry-run passed" "$scratch/place.log" \ +# `orun new` reports this only after running validate + plan --dry-run in the +# produced tree. Its absence means the tier lost a check without failing. +# +# TWO WORDINGS, because the CLI changed its mind about how to say it. Up to +# v2.58.x it printed `repo gate: validate + plan --dry-run passed`; from the +# v2.88.0 floor it prints a summary line instead: +# +# ✓ Verified intent valid · 44 components × 3 envs → 92 jobs +# +# Both mean the gate ran, and neither appears when it did not — which is the +# property this check exists for. Matching only the old one turned a rename +# into a red tier the day the floor moved. +grep -qE "repo gate: validate \+ plan --dry-run passed|Verified +intent valid" "$scratch/place.log" \ || fail "the placement did not report the repo-scale gate — \`orun validate\` and \`orun plan --dry-run\` are Tier 1 checks that ride inside \`orun new\`, and a silent loss of them is exactly the regression BE1a was about" diff --git a/testing/retouch.test.sh b/testing/retouch.test.sh new file mode 100755 index 0000000..31c3667 --- /dev/null +++ b/testing/retouch.test.sh @@ -0,0 +1,199 @@ +#!/usr/bin/env bash +# A RE-RUN PHASE HAS SOMETHING TO LAND. +# +# A phase's convergence can fail AFTER its PR merged, and the merge has already +# put every file the phase places on main. orun derives phase state from the +# files, so a retried build sees the phase placed and a forced re-run of it +# lands an EMPTY diff — and the product's CI plans `--changed`, so a component +# whose files did not change in the push does not deploy. The phase's `retouch` +# hook (tooling/bootstrap/retouch.mjs) is what breaks that: one marker line at +# the end of each affected component.yaml, +# +# # orun: redeploy +# +# replaced rather than accumulated, so the landing has a diff and exactly the +# phase's components are in the changed set. The marker is a deploy trigger and +# nothing reads it back; phase state stays derived, never stored. +# +# This drives the real retouch.mjs over a two-component tree, then checks that +# every component the blueprint's retouch hooks name resolves in THIS tree — +# the layout a product is placed with. +# Needs: node. No network. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" +retouch="$root/tooling/bootstrap/retouch.mjs" + +command -v node >/dev/null || { echo "retouch.test.sh needs node" >&2; exit 1; } + +fail=0 +ok() { echo " ok $*"; } +bad() { echo " ✕ $*" >&2; fail=1; } + +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT + +# A product tree with two components in two of the lanes the blueprint places +# into, a test package that shares a directory name with the first (as +# tests/ does with apps/) and must NOT be touched, and the +# hand-written re-trigger line the fleet carried before this tool existed. +mkdir -p "$tmp/apps/alpha" "$tmp/infra/beta" "$tmp/tests/alpha" "$tmp/node_modules/x" +cat > "$tmp/apps/alpha/component.yaml" <<'Y' +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: alpha +spec: + type: cloudflare-worker-turbo + labels: + team: platform +# ci: re-trigger deploy (batch A — runner-starvation recovery 20260622T115650Z) +Y +# No trailing newline on purpose: the tool must add one, and only one. +printf 'apiVersion: sourceplane.io/v1\nkind: Component\nmetadata:\n name: beta\nspec:\n type: terraform' > "$tmp/infra/beta/component.yaml" +printf 'kind: Component\nmetadata:\n name: alpha-tests\n' > "$tmp/tests/alpha/component.yaml" +printf 'kind: Component\nmetadata:\n name: alpha\n' > "$tmp/node_modules/x/component.yaml" +cp "$tmp/apps/alpha/component.yaml" "$tmp/alpha.orig" +cp "$tmp/infra/beta/component.yaml" "$tmp/beta.orig" + +markers() { grep -c '^# orun: redeploy ' "$1" || true; } + +echo "── retouch: one marker, last, replaced not appended" +(cd "$tmp" && ORUN_RUN_ID=run-one node "$retouch" --phase 04-workers --components alpha,beta) > "$tmp/one.log" 2>&1 \ + || { bad "first run failed:"; sed 's/^/ /' "$tmp/one.log" >&2; } +for f in apps/alpha infra/beta; do + [ "$(markers "$tmp/$f/component.yaml")" = 1 ] || bad "$f: $(markers "$tmp/$f/component.yaml") marker lines after one run, want 1" + [ "$(tail -n1 "$tmp/$f/component.yaml")" = "# orun: redeploy 04-workers run-one" ] \ + || bad "$f: last line is '$(tail -n1 "$tmp/$f/component.yaml")'" +done +[ "$(tail -c1 "$tmp/infra/beta/component.yaml" | od -An -c | tr -d ' ')" = '\n' ] \ + || bad "infra/beta: no trailing newline after retouch" +ok "both components carry the marker as their last line" + +(cd "$tmp" && ORUN_RUN_ID=run-two node "$retouch" --phase 04-workers-restore --components alpha,beta) > "$tmp/two.log" 2>&1 \ + || { bad "second run failed:"; sed 's/^/ /' "$tmp/two.log" >&2; } +for f in apps/alpha infra/beta; do + [ "$(markers "$tmp/$f/component.yaml")" = 1 ] || bad "$f: $(markers "$tmp/$f/component.yaml") marker lines after two runs — the marker accumulated" + [ "$(tail -n1 "$tmp/$f/component.yaml")" = "# orun: redeploy 04-workers-restore run-two" ] \ + || bad "$f: second run did not replace the marker: '$(tail -n1 "$tmp/$f/component.yaml")'" +done +grep -q 'replace marker' "$tmp/two.log" || bad "second run did not report a replacement" +ok "a second run replaces the marker (a different phase's too) rather than appending" + +echo "── retouch: every other byte is as it was" +if [ "$(head -n -1 "$tmp/apps/alpha/component.yaml" | cksum)" = "$(cksum < "$tmp/alpha.orig")" ]; then + ok "apps/alpha: the file above the marker is byte-for-byte the original" +else + bad "apps/alpha: bytes above the marker changed" + diff <(head -n -1 "$tmp/apps/alpha/component.yaml") "$tmp/alpha.orig" >&2 || true +fi +if [ "$(head -n -1 "$tmp/infra/beta/component.yaml" | cksum)" = "$(printf '%s\n' "$(cat "$tmp/beta.orig")" | cksum)" ]; then + ok "infra/beta: only a newline was added before the marker" +else + bad "infra/beta: bytes above the marker changed" +fi +grep -q '^# ci: re-trigger deploy' "$tmp/apps/alpha/component.yaml" \ + && ok "the hand-written re-trigger line is left alone" \ + || bad "the hand-written re-trigger line was removed" +[ "$(cat "$tmp/tests/alpha/component.yaml")" = "$(printf 'kind: Component\nmetadata:\n name: alpha-tests\n')" ] \ + && ok "tests/alpha (alpha-tests) was not touched — components resolve by metadata.name" \ + || bad "tests/alpha was touched: a component is its metadata.name, not its directory name" + +echo "── retouch: the same stamp twice is a no-op" +(cd "$tmp" && ORUN_RUN_ID=run-two node "$retouch" --phase 04-workers-restore --components alpha,beta) > "$tmp/again.log" 2>&1 \ + || bad "idempotent re-run failed" +grep -q 'nothing to do' "$tmp/again.log" && ok "re-running with the same stamp reports nothing to do" \ + || bad "re-running with the same stamp did not report a no-op: $(tail -1 "$tmp/again.log")" + +echo "── retouch: the stamp" +(cd "$tmp" && env -u ORUN_RUN_ID ORUN_SESSION_ID=sess-9 node "$retouch" --phase p --components beta) >/dev/null 2>&1 +[ "$(tail -n1 "$tmp/infra/beta/component.yaml")" = "# orun: redeploy p sess-9" ] \ + && ok "ORUN_SESSION_ID stamps when ORUN_RUN_ID is unset" \ + || bad "ORUN_SESSION_ID was not used: '$(tail -n1 "$tmp/infra/beta/component.yaml")'" +(cd "$tmp" && env -u ORUN_RUN_ID -u ORUN_SESSION_ID node "$retouch" --phase p --components beta) >/dev/null 2>&1 +tail -n1 "$tmp/infra/beta/component.yaml" | grep -Eq '^# orun: redeploy p [0-9]{8}T[0-9]{6}Z$' \ + && ok "with neither, a UTC timestamp" \ + || bad "no timestamp stamp: '$(tail -n1 "$tmp/infra/beta/component.yaml")'" + +echo "── retouch: --dry-run writes nothing, --check names what is missing" +before="$(cksum < "$tmp/apps/alpha/component.yaml")" +(cd "$tmp" && ORUN_RUN_ID=dry node "$retouch" --phase p --components alpha --dry-run) > "$tmp/dry.log" 2>&1 \ + || bad "--dry-run failed" +[ "$before" = "$(cksum < "$tmp/apps/alpha/component.yaml")" ] && grep -q 'would replace marker' "$tmp/dry.log" \ + && ok "--dry-run reports the change and leaves the file alone" \ + || bad "--dry-run wrote, or did not say what it would do" + +if (cd "$tmp" && node "$retouch" --phase p --components alpha,gamma --check) > "$tmp/check.log" 2>&1; then + bad "--check passed with gamma absent" +else + grep -q 'gamma' "$tmp/check.log" && ok "--check fails and names gamma" \ + || bad "--check failed without naming the missing component: $(cat "$tmp/check.log")" +fi +if (cd "$tmp" && ORUN_RUN_ID=x node "$retouch" --phase p --components alpha,gamma) > "$tmp/miss.log" 2>&1; then + bad "a run with a missing component succeeded" +else + [ "$(tail -n1 "$tmp/apps/alpha/component.yaml")" != "# orun: redeploy p x" ] \ + && ok "a missing component refuses the whole run before any file is written" \ + || bad "a missing component still wrote the components that exist" +fi +(cd "$tmp" && node "$retouch" --phase p --components alpha,beta --check) >/dev/null 2>&1 \ + && ok "--check passes when every component resolves" || bad "--check failed on a complete set" + +echo "── retouch: --affects reads a task contract" +cat > "$tmp/contract.yaml" <<'Y' +# A contract, as tasks/*.TaskContract.yaml are written. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: Two components converge + affects: + - alpha + # a comment between items + - beta + doneWhen: + - convergence green + gates: [] +Y +(cd "$tmp" && ORUN_RUN_ID=via-contract node "$retouch" --phase 05-edge --affects contract.yaml) > "$tmp/aff.log" 2>&1 \ + || { bad "--affects run failed:"; sed 's/^/ /' "$tmp/aff.log" >&2; } +for f in apps/alpha infra/beta; do + [ "$(tail -n1 "$tmp/$f/component.yaml")" = "# orun: redeploy 05-edge via-contract" ] \ + || bad "$f: --affects did not touch it" +done +grep -q '2 of 2' "$tmp/aff.log" && ok "spec.affects named both, and both were touched" \ + || bad "--affects touched the wrong number: $(tail -1 "$tmp/aff.log")" +printf 'spec:\n affects: [alpha, beta]\n' > "$tmp/flow.yaml" +(cd "$tmp" && ORUN_RUN_ID=flow node "$retouch" --phase p --affects flow.yaml --check) >/dev/null 2>&1 \ + && ok 'the flow form `affects: [a, b]` reads too' || bad "the flow form of affects did not read" +printf 'spec:\n goal: nothing\n' > "$tmp/none.yaml" +(cd "$tmp" && node "$retouch" --phase p --affects none.yaml --check) >/dev/null 2>&1 \ + && bad "a contract with no affects passed --check" || ok "a contract with no affects refuses" + +# ── THE BLUEPRINT'S OWN HOOKS RESOLVE IN THIS TREE ───────────────────────── +# Every `retouch` hook in repo-blueprint.yaml names the components a phase +# redeploys, through a contract or a list. A product is placed with this +# repository's layout, so each must resolve here — a contract that names a +# component nobody ships, or a component that moved, fails a real bootstrap at +# the landing, an hour in. `{{ .baseline.dir }}` is this checkout. +echo "── the blueprint's retouch hooks, against this tree" +hooks=0 +while IFS= read -r line; do + hooks=$((hooks + 1)) + argv="$(printf '%s' "$line" | sed -e 's/^[[:space:]]*run:[[:space:]]*//' \ + -e "s#{{ \.baseline\.dir }}#$root#g" -e 's#{{ \.phase\.name }}#probe#g')" + if (cd "$root" && node -e ' + const argv = JSON.parse(process.argv[1]); + const { spawnSync } = require("node:child_process"); + const r = spawnSync(argv[0], [...argv.slice(1), "--check"], { stdio: ["ignore", "pipe", "pipe"] }); + process.stdout.write(r.stdout); process.stderr.write(r.stderr); + process.exit(r.status ?? 1); + ' "$argv") > "$tmp/hook.log" 2>&1; then + ok "$(grep -c -- '->' "$tmp/hook.log") component(s): ${argv#*retouch.mjs\", }" + else + bad "a retouch hook does not resolve: $argv"; sed 's/^/ /' "$tmp/hook.log" >&2 + fi +done < <(grep -E '^\s*run: \[.*retouch\.mjs' "$root/repo-blueprint.yaml") +[ "$hooks" -ge 1 ] || bad "no retouch hook in repo-blueprint.yaml — 01-product lands the deployable components and needs one" + +[ "$fail" -eq 0 ] || exit 1 +echo "retouch.test.sh: ok" diff --git a/tooling/bootstrap/cycle-break.mjs b/tooling/bootstrap/cycle-break.mjs deleted file mode 100644 index 9c5ea80..0000000 --- a/tooling/bootstrap/cycle-break.mjs +++ /dev/null @@ -1,168 +0,0 @@ -#!/usr/bin/env node -// Two-pass bootstrap for the service-binding cycle (zero-dependency). -// -// The {billing, membership, events, notifications} workers form a service- -// binding cycle (billing <-> membership; membership -> notifications -> events -// -> membership). On a FRESH Cloudflare account this cluster cannot deploy: -// Cloudflare rejects a deploy whose service binding targets a worker that does -// not exist yet (error 10143), and re-running never resolves it because the -// cycle never breaks on its own. See docs/phases/04-workers.md and the -// ACKNOWLEDGED_BINDING_CYCLES set in -// tests/config-worker/src/deployment-config.test.ts. -// -// This tool removes the two minimal feedback edges so the cluster becomes a -// deployable DAG, then restores them once the targets exist: -// -// 1. node tooling/bootstrap/cycle-break.mjs --strip # pass 1 -// commit + merge -> cluster deploys (policy -> billing -> membership -// -> events -> notifications) -// 2. node tooling/bootstrap/cycle-break.mjs --restore # pass 2 -// commit + merge -> billing + membership redeploy with full bindings -// -// Each removed binding (object + its separator comma) is replaced in place by a -// single-line `//` marker that base64-encodes the exact removed text, so -// --restore reproduces the original template byte-for-byte. The marker is a -// line comment, so the stripped template is still valid wrangler JSONC and -// still parses under the deployment-config test's comment-stripping reader. -// -// Modes: -// --strip break the cycle (idempotent: skips edges already stripped) -// --restore put the bindings back (idempotent: no-op if none stripped) -// --check report which edges are currently stripped (exit 0) - -import * as fs from "node:fs"; -import * as path from "node:path"; - -// The minimal feedback edge set. Mirrors ACKNOWLEDGED_BINDING_CYCLES in -// tests/config-worker/src/deployment-config.test.ts — keep the two in sync. -// Removing `from`'s service binding to `to` makes the cluster acyclic. -const FEEDBACK_EDGES = [ - { from: "billing-worker", to: "membership-worker" }, - { from: "membership-worker", to: "notifications-worker" }, -]; - -const MARKER = "@cycle-break"; - -function usage() { - console.error("usage: cycle-break.mjs --strip | --restore | --check"); - process.exit(2); -} - -function wranglerPath(component) { - return path.join("apps", component, "wrangler.template.jsonc"); -} - -// Find the [start, end) span of the service-binding object whose `service` -// targets `toComponent` (with or without a brand prefix), extended to include -// one separator comma — the trailing comma if present, else the leading one — -// so removal leaves a valid array with no dangling comma. -function findBindingSpan(text, toComponent, fromIndex) { - const re = new RegExp( - `"service"\\s*:\\s*"(?:[a-z0-9-]+-)?${toComponent}-(?:stage|prod|dev)"`, - "g", - ); - re.lastIndex = fromIndex; - const m = re.exec(text); - if (!m) return null; - - // Service objects are flat ({ "binding": …, "service": … }) — no nested - // braces — so the enclosing object is the nearest { before and } after. - let open = text.lastIndexOf("{", m.index); - let close = text.indexOf("}", m.index); - if (open < 0 || close < 0) return null; - let start = open; - let end = close + 1; - - // Prefer a trailing comma; otherwise take a leading one. - let after = end; - while (after < text.length && /\s/.test(text[after])) after++; - if (text[after] === ",") { - end = after + 1; - } else { - let before = start - 1; - while (before >= 0 && /\s/.test(text[before])) before--; - if (text[before] === ",") start = before; - } - return { start, end }; -} - -function strip() { - let total = 0; - for (const { from, to } of FEEDBACK_EDGES) { - const file = wranglerPath(from); - if (!fs.existsSync(file)) { - console.warn(`cycle-break --strip: ${file} absent — skipping ${from} -> ${to}`); - continue; - } - let text = fs.readFileSync(file, "utf8"); - let removed = 0; - // Repeatedly remove each remaining (stage/prod/…) binding to `to`. - for (;;) { - const span = findBindingSpan(text, to, 0); - if (!span) break; - const slice = text.slice(span.start, span.end); - const b64 = Buffer.from(slice, "utf8").toString("base64"); - const marker = `// ${MARKER}:${from}->${to}:${b64}`; - text = text.slice(0, span.start) + marker + text.slice(span.end); - removed++; - } - if (removed > 0) { - fs.writeFileSync(file, text); - console.log(`cycle-break --strip: ${from} -> ${to}: removed ${removed} binding(s) in ${file}`); - total += removed; - } else { - console.log(`cycle-break --strip: ${from} -> ${to}: already stripped (no live binding)`); - } - } - console.log( - total > 0 - ? `cycle-break --strip: done (${total} binding(s)). Commit + merge to deploy the DAG, then run --restore.` - : "cycle-break --strip: nothing to do (already stripped).", - ); -} - -function restore() { - const re = new RegExp(`// ${MARKER}:[a-z0-9-]+->[a-z0-9-]+:([A-Za-z0-9+/=]+)`, "g"); - let total = 0; - for (const { from } of FEEDBACK_EDGES) { - const file = wranglerPath(from); - if (!fs.existsSync(file)) continue; - let text = fs.readFileSync(file, "utf8"); - let count = 0; - text = text.replace(re, (_m, b64) => { - count++; - return Buffer.from(b64, "base64").toString("utf8"); - }); - if (count > 0) { - fs.writeFileSync(file, text); - console.log(`cycle-break --restore: restored ${count} binding(s) in ${file}`); - total += count; - } - } - console.log( - total > 0 - ? `cycle-break --restore: done (${total} binding(s)). Commit + merge to redeploy with full bindings.` - : "cycle-break --restore: nothing to restore.", - ); -} - -function check() { - const re = new RegExp(`// ${MARKER}:([a-z0-9-]+->[a-z0-9-]+):`, "g"); - let any = false; - for (const { from } of FEEDBACK_EDGES) { - const file = wranglerPath(from); - if (!fs.existsSync(file)) continue; - const text = fs.readFileSync(file, "utf8"); - for (const m of text.matchAll(re)) { - console.log(`stripped: ${m[1]} (${file})`); - any = true; - } - } - if (!any) console.log("cycle-break --check: no edges stripped (full binding topology)."); -} - -const mode = process.argv[2]; -if (mode === "--strip") strip(); -else if (mode === "--restore") restore(); -else if (mode === "--check") check(); -else usage(); diff --git a/tooling/bootstrap/dev-lanes.mjs b/tooling/bootstrap/dev-lanes.mjs new file mode 100755 index 0000000..93da1b5 --- /dev/null +++ b/tooling/bootstrap/dev-lanes.mjs @@ -0,0 +1,113 @@ +#!/usr/bin/env node +// The dev verify lanes stay off main's convergences while a product is being +// bootstrapped (zero-dependency). +// +// intent.yaml activates `dev` on `github-push-main` as well as on pull +// requests: every merge to main re-verifies every component (builds, tests) +// on the dev rung beside the stage and prod deploys. That is the right rule +// for a product that is live. During a bootstrap it proves nothing — the +// content comes from a pinned baseline whose own CI already ran it, and +// every phase's pull request is checked by `plan` alone — and it costs the +// one thing a bootstrap's wall-clock is made of: runner slots. A fleet +// landing's 48 jobs are 22 dev verifies and 13 deploys each on stage and +// prod; auto mode shares `maxLanes` by job count, so dev took eight of +// eighteen lanes and stage and prod got five each (measured on +// pullely/cirrus-timing-4, baseline-v19). +// +// So 01-scaffold defers the trigger and 08-docs, the last landing, puts it +// back, exactly as tooling/bootstrap/promotion.mjs does for prod's gate: +// +// node tooling/bootstrap/dev-lanes.mjs --defer # 01-scaffold, before the first landing +// node tooling/bootstrap/dev-lanes.mjs --restore # 08-docs, the last landing +// node tooling/bootstrap/dev-lanes.mjs --check # prints deferred | active +// +// --defer replaces dev's `- github-push-main` trigger line with one marker +// comment that base64-encodes the exact text removed, so --restore +// reproduces intent.yaml byte-for-byte. Both are idempotent. Pull requests +// keep their dev lanes throughout: only the push-to-main activation moves. +// +// The trigger is deferred, never dropped: a bootstrap that stops before +// 08-docs leaves the marker in intent.yaml, and `--restore` (or a re-run of +// 08-docs) is the whole fix. +import * as fs from "node:fs"; + +const FILE = process.argv.includes("--file") + ? process.argv[process.argv.indexOf("--file") + 1] + : "intent.yaml"; +const MARKER = "@dev-lanes-deferred"; +const TRIGGER = "github-push-main"; + +function usage() { + console.error("usage: dev-lanes.mjs --defer | --restore | --check [--file intent.yaml]"); + process.exit(2); +} + +// The `- github-push-main` line under environments.dev.activation.triggerRefs. +function findDevPushTrigger(text) { + const lines = text.split("\n"); + let inEnvs = false; + let devIndent = -1; + let inDev = false; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (/^environments:\s*$/.test(line)) { + inEnvs = true; + continue; + } + if (!inEnvs) continue; + if (/^\S/.test(line) && line.trim() !== "") break; // left the section + const env = /^(\s+)([A-Za-z0-9_-]+):\s*$/.exec(line); + if (env && (devIndent < 0 || env[1].length <= devIndent)) { + inDev = env[2] === "dev"; + if (inDev) devIndent = env[1].length; + continue; + } + if (!inDev) continue; + if (new RegExp(`^\\s+-\\s+${TRIGGER}\\s*$`).test(line)) return { lines, index: i }; + } + return { lines, index: -1 }; +} + +function defer() { + const text = fs.readFileSync(FILE, "utf8"); + if (text.includes(`# ${MARKER}:`)) { + console.log(`dev-lanes --defer: already deferred in ${FILE}`); + return; + } + const { lines, index } = findDevPushTrigger(text); + if (index < 0) { + console.log(`dev-lanes --defer: dev is not activated on ${TRIGGER} in ${FILE} — nothing to defer`); + return; + } + const original = lines[index]; + const indent = /^(\s*)/.exec(original)[1]; + const b64 = Buffer.from(original, "utf8").toString("base64"); + const marker = `${indent}# ${MARKER}:${b64} (tooling/bootstrap/dev-lanes.mjs --restore puts it back)`; + const out = [...lines.slice(0, index), marker, ...lines.slice(index + 1)].join("\n"); + fs.writeFileSync(FILE, out); + console.log(`dev-lanes --defer: dev's verify lanes stay off main's convergences until --restore (${FILE})`); +} + +function restore() { + const text = fs.readFileSync(FILE, "utf8"); + const re = new RegExp(`^[ \\t]*# ${MARKER}:([A-Za-z0-9+/=]+) \\(tooling/bootstrap/dev-lanes\\.mjs --restore puts it back\\)$`, "m"); + const m = re.exec(text); + if (!m) { + console.log(`dev-lanes --restore: nothing deferred in ${FILE}`); + return; + } + const original = Buffer.from(m[1], "base64").toString("utf8"); + fs.writeFileSync(FILE, text.slice(0, m.index) + original + text.slice(m.index + m[0].length)); + console.log(`dev-lanes --restore: dev verifies every merge to main again (${FILE})`); +} + +function check() { + const text = fs.readFileSync(FILE, "utf8"); + console.log(text.includes(`# ${MARKER}:`) ? "deferred" : "active"); +} + +const mode = process.argv[2]; +if (mode === "--defer") defer(); +else if (mode === "--restore") restore(); +else if (mode === "--check") check(); +else usage(); diff --git a/tooling/bootstrap/pen-reset.mjs b/tooling/bootstrap/pen-reset.mjs new file mode 100755 index 0000000..6fbc026 --- /dev/null +++ b/tooling/bootstrap/pen-reset.mjs @@ -0,0 +1,106 @@ +#!/usr/bin/env node +// Clear a landing's own pen branch when an earlier run left one behind +// (zero-dependency). +// +// WHAT THIS FIXES, exactly. `orun.pr/land@v1` lands a phase on the provenance +// pen's branch, `orun/-`, with a plain `git push -u`. +// If a build STOPS between that push and the merge — the token expires, the +// host goes away, somebody closes the window — the branch and its pull +// request are left on the remote, pointing at a commit of that run's. +// +// A retry re-places the phase and makes a FRESH commit on the same parent. +// The two commits are siblings, not ancestors, so the push is rejected: +// +// ! [rejected] orun/BASE-5-04-workers -> orun/BASE-5-04-workers (non-fast-forward) +// hint: Updates were rejected because the tip of your current branch is +// hint: behind its remote counterpart. +// +// and it is rejected identically on every retry, for ever. Observed on +// pullely/multi-tenant-saas (2026-10-25): the build stopped after 04-workers' +// PR went green, and every "Retry from 04-workers" after it died on this push +// without reaching a single step of the phase's real work. Git's hint is +// misleading, too — the branches have DIVERGED, so `git pull` is not the fix; +// it would merge the abandoned commit back in and land a doubled diff. +// +// So each landing clears its own branch first. The branch belongs to this +// phase's task: nothing else writes it, and deleting it closes the pull +// request that was going nowhere. The next push creates it fresh. +// +// node pen-reset.mjs --branch orun/BASE-5-04-workers [--remote origin] +// node pen-reset.mjs --branch orun/BASE-5-04-workers --check # report only +// +// A branch whose remote tip is already an ancestor of HEAD is LEFT ALONE: it +// merged, and the push that follows fast-forwards. Only a diverged one is +// deleted, and only under `orun/` — the guard below makes it impossible for a +// mistemplated argument to delete `main`. +// +// Best effort by design: a remote this cannot reach, or a git that refuses +// the delete, is reported and exits 0. The landing is what reports a real +// failure; a cleanup must not be the thing that stops a build. + +import { spawnSync } from "node:child_process"; + +function arg(name, fallback) { + const i = process.argv.indexOf(`--${name}`); + return i >= 0 && process.argv[i + 1] !== undefined ? process.argv[i + 1] : fallback; +} + +function git(...args) { + const r = spawnSync("git", args, { encoding: "utf8" }); + return { ok: r.status === 0, out: (r.stdout ?? "").trim(), err: (r.stderr ?? "").trim() }; +} + +const branch = arg("branch", ""); +const remote = arg("remote", "origin"); +const checkOnly = process.argv.includes("--check"); + +if (!branch) { + console.error("pen-reset: --branch is required"); + process.exit(2); +} +// The guard. Only the pen's own namespace, and never a ref with a path escape +// or a wildcard in it. +if (!/^orun\/[A-Za-z0-9._-]+$/.test(branch)) { + console.error(`pen-reset: refusing to touch "${branch}" — only orun/- pen branches`); + process.exit(2); +} + +const ls = git("ls-remote", "--heads", remote, branch); +if (!ls.ok) { + console.log(`pen-reset: could not reach ${remote} (${ls.err.split("\n")[0] || "no detail"}); leaving ${branch} alone`); + process.exit(0); +} +if (ls.out === "") { + console.log(`pen-reset: no ${branch} on ${remote}; nothing to clear`); + process.exit(0); +} + +const tip = ls.out.split(/\s+/)[0]; + +// Is the remote tip already in this history? Fetch it by sha-less ref first — +// a shallow or fresh clone may not have the object. +git("fetch", "--quiet", remote, branch); +const reachable = git("merge-base", "--is-ancestor", tip, "HEAD").ok; +if (reachable) { + console.log(`pen-reset: ${branch} (${tip.slice(0, 8)}) is already in this history; the push will fast-forward`); + process.exit(0); +} + +if (checkOnly) { + console.log(`pen-reset: ${branch} (${tip.slice(0, 8)}) has diverged — a push would be rejected non-fast-forward`); + process.exit(1); +} + +const del = git("push", remote, "--delete", branch); +if (!del.ok) { + console.log( + `pen-reset: ${branch} (${tip.slice(0, 8)}) has diverged but could not be deleted ` + + `(${del.err.split("\n")[0] || "no detail"}). The landing's push will be rejected; ` + + `delete it by hand — git push ${remote} --delete ${branch} — and re-run this phase.`, + ); + process.exit(0); +} +console.log( + `pen-reset: deleted ${branch} (${tip.slice(0, 8)}) — an earlier run left it behind, ` + + `and its pull request with it. This landing opens a fresh one.`, +); diff --git a/tooling/bootstrap/promotion.mjs b/tooling/bootstrap/promotion.mjs new file mode 100755 index 0000000..8905490 --- /dev/null +++ b/tooling/bootstrap/promotion.mjs @@ -0,0 +1,124 @@ +#!/usr/bin/env node +// Stage and prod deploy side by side while a product is being bootstrapped +// (zero-dependency). +// +// intent.yaml gates prod behind stage: `environments.prod.promotion.dependsOn: +// [stage]`, which orun plans as an in-run edge from every prod job to the +// same component's stage job. That is the right rule for a product that is +// live — a change reaches prod only after it deployed to stage. During a +// bootstrap it protects nothing (both environments are empty, and every phase +// is watched to green before the next one starts) and it doubles the length +// of every convergence: each worker's prod deploy waits out its stage deploy, +// and 04-workers is twelve workers' worth of that. +// +// So 01-scaffold defers the gate and 08-docs, the last landing, puts it back: +// +// node tooling/bootstrap/promotion.mjs --defer # 01-scaffold, before the first landing +// node tooling/bootstrap/promotion.mjs --restore # 08-docs, the last landing +// node tooling/bootstrap/promotion.mjs --check # prints deferred | enforced +// +// --defer replaces the prod `promotion:` block with one marker comment that +// base64-encodes the exact text removed, so --restore reproduces intent.yaml +// byte-for-byte. Both are idempotent. Restoring is a change to intent.yaml's +// `environments` section only, which `orun plan --changed` (intent impact +// `watch`, the default) maps to no component: the landing that restores it +// deploys nothing. +// +// The gate is deferred, never dropped: a bootstrap that stops before 08-docs +// leaves the marker in intent.yaml, and `--restore` (or a re-run of 08-docs) +// is the whole fix. docs/phases/08-docs.md says so. + +import * as fs from "node:fs"; + +const FILE = process.argv.includes("--file") + ? process.argv[process.argv.indexOf("--file") + 1] + : "intent.yaml"; +const MARKER = "@promotion-deferred"; + +function usage() { + console.error("usage: promotion.mjs --defer | --restore | --check [--file intent.yaml]"); + process.exit(2); +} + +// The `promotion:` block of the `prod:` environment: from its `promotion:` +// line up to (not including) the next line indented at or above it. +function findProdPromotion(text) { + const lines = text.split("\n"); + let inEnvs = false; + let prodIndent = -1; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (/^environments:\s*$/.test(line)) { + inEnvs = true; + continue; + } + if (!inEnvs) continue; + if (/^\S/.test(line) && line.trim() !== "") break; // left the section + const prod = /^(\s+)prod:\s*$/.exec(line); + if (prod) { + prodIndent = prod[1].length; + continue; + } + if (prodIndent < 0) continue; + const indent = line.length - line.trimStart().length; + if (line.trim() !== "" && indent <= prodIndent) { + prodIndent = -1; // left prod without finding one + continue; + } + const m = /^(\s+)promotion:\s*$/.exec(line); + if (!m) continue; + const own = m[1].length; + let end = i + 1; + while (end < lines.length) { + const l = lines[end]; + if (l.trim() !== "" && l.length - l.trimStart().length <= own) break; + end++; + } + return { lines, start: i, end, indent: m[1] }; + } + return null; +} + +function defer() { + const text = fs.readFileSync(FILE, "utf8"); + if (text.includes(MARKER)) { + console.log(`promotion --defer: already deferred in ${FILE}`); + return; + } + const found = findProdPromotion(text); + if (!found) { + console.log(`promotion --defer: prod has no promotion block in ${FILE} — nothing to defer`); + return; + } + const { lines, start, end, indent } = found; + const removed = lines.slice(start, end).join("\n"); + const b64 = Buffer.from(removed, "utf8").toString("base64"); + const marker = `${indent}# ${MARKER}:${b64} (tooling/bootstrap/promotion.mjs --restore puts it back)`; + const out = [...lines.slice(0, start), marker, ...lines.slice(end)].join("\n"); + fs.writeFileSync(FILE, out); + console.log(`promotion --defer: prod no longer waits on stage until --restore (${FILE})`); +} + +function restore() { + const text = fs.readFileSync(FILE, "utf8"); + const re = new RegExp(`^[ \\t]*# ${MARKER}:([A-Za-z0-9+/=]+).*$`, "m"); + const m = re.exec(text); + if (!m) { + console.log(`promotion --restore: nothing deferred in ${FILE}`); + return; + } + const original = Buffer.from(m[1], "base64").toString("utf8"); + fs.writeFileSync(FILE, text.slice(0, m.index) + original + text.slice(m.index + m[0].length)); + console.log(`promotion --restore: prod waits on stage again (${FILE})`); +} + +function check() { + const text = fs.readFileSync(FILE, "utf8"); + console.log(text.includes(MARKER) ? "deferred" : "enforced"); +} + +const mode = process.argv[2]; +if (mode === "--defer") defer(); +else if (mode === "--restore") restore(); +else if (mode === "--check") check(); +else usage(); diff --git a/tooling/bootstrap/retouch.mjs b/tooling/bootstrap/retouch.mjs new file mode 100755 index 0000000..97e5284 --- /dev/null +++ b/tooling/bootstrap/retouch.mjs @@ -0,0 +1,254 @@ +#!/usr/bin/env node +// Give a re-run phase something to land (zero-dependency). +// +// A phase lands as a pull request and is verified by the convergence run that +// follows the merge. When that convergence FAILS — a provider error, a runner +// starved out, a smoke that raced route propagation past its retries — the +// merge has already happened, so every file the phase places is on main. orun +// derives phase state from the files on disk (never from a stored record), so +// a retried build finds the phase placed, and even a forced re-run of it +// produces an EMPTY diff: `orun.pr/land@v1` has nothing to commit, and the +// product's CI (`orun plan --changed`) deploys a component only when one of +// its files changed in the push. Nothing lands, nothing redeploys, and the +// operator is told the phase is fine. +// +// This tool is what the phase's `retouch` hook runs before it stages and +// lands: for each component the phase deploys, it rewrites ONE trailing line +// in that component's `component.yaml`, +// +// # orun: redeploy +// +// replacing the previous marker if there is one (never accumulating), so the +// landing has a diff and exactly those components are in the changed set. The +// same convention was hand-edited before this existed (`# ci: re-trigger +// deploy (batch A — …)` lines, duplicated by hand across the fleet); this is +// that edit with a name, a stamp, and a phase to answer for it. +// +// THE MARKER IS A DEPLOY TRIGGER, NOT STATE. Nothing reads it back: orun does +// not learn from it whether a phase ran, and this repository's invariant — +// phase state is DERIVED from the tree, never stored in it — holds. Delete the +// line and nothing is lost but the next redeploy's reason to happen. +// +// node retouch.mjs --phase 04-workers --affects tasks/04-workers.TaskContract.yaml +// node retouch.mjs --phase 04-workers --components billing-worker,membership-worker +// +// Options: +// --phase the phase the marker names (required) +// --components a,b,c the components to touch, by `metadata.name` … +// --affects … or read them from a TaskContract's `spec.affects` +// --check resolve every component and exit non-zero naming +// any without a component.yaml; write nothing +// --dry-run print what would change; write nothing +// +// The stamp is ORUN_RUN_ID if set, else ORUN_SESSION_ID, else a UTC timestamp +// (YYYYMMDDTHHMMSSZ) — whichever identifies the run that asked for the deploy. +// +// Runs in the product checkout (the phase hooks' working directory). A +// component is found by the `metadata.name` its component.yaml declares, not +// by directory: `apps/admin-worker` and `tests/admin-worker` both carry one, +// and only the first is named `admin-worker`. + +import * as fs from "node:fs"; +import * as path from "node:path"; + +const MARKER_RE = /^# orun: redeploy \S+ \S+\r?$/; +const SKIP_DIRS = new Set(["node_modules", ".git", ".orun", "dist", ".next", ".open-next", ".turbo"]); +const MAX_DEPTH = 4; + +function usage(msg) { + if (msg) console.error(`retouch: ${msg}`); + console.error( + "usage: retouch.mjs --phase (--components a,b,c | --affects ) [--check] [--dry-run]", + ); + process.exit(2); +} + +function parseArgs(argv) { + const opts = { phase: null, components: null, affects: null, check: false, dryRun: false }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + const next = () => { + if (i + 1 >= argv.length) usage(`${a} needs a value`); + return argv[++i]; + }; + if (a === "--phase") opts.phase = next(); + else if (a === "--components") opts.components = next(); + else if (a === "--affects") opts.affects = next(); + else if (a === "--check") opts.check = true; + else if (a === "--dry-run") opts.dryRun = true; + else if (a === "-h" || a === "--help") usage(); + else usage(`unknown argument ${a}`); + } + if (!opts.phase) usage("--phase is required"); + if (/\s/.test(opts.phase)) usage("--phase must be a single token"); + if (!opts.components && !opts.affects) usage("one of --components or --affects is required"); + if (opts.components && opts.affects) usage("--components and --affects are exclusive"); + return opts; +} + +// `spec.affects` from a TaskContract, with a reader small enough to need no +// YAML dependency: the contracts are a flat mapping with one block sequence. +// Accepts the block form (`affects:` then `- name` lines indented under it) +// and the flow form (`affects: [a, b]`). +function readAffects(file) { + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch (e) { + console.error(`retouch: cannot read ${file}: ${e.message}`); + process.exit(1); + } + const lines = text.split(/\r?\n/); + const names = []; + for (let i = 0; i < lines.length; i++) { + const m = /^(\s*)affects:\s*(.*?)\s*$/.exec(lines[i]); + if (!m) continue; + const indent = m[1].length; + const inline = m[2].replace(/\s+#.*$/, ""); + if (inline.startsWith("[")) { + const body = inline.replace(/^\[/, "").replace(/\]\s*$/, ""); + for (const part of body.split(",")) { + const v = part.trim().replace(/^["']|["']$/g, ""); + if (v) names.push(v); + } + break; + } + for (let j = i + 1; j < lines.length; j++) { + const line = lines[j]; + if (/^\s*(#.*)?$/.test(line)) continue; + const lead = /^(\s*)/.exec(line)[1].length; + if (lead <= indent) break; + const item = /^\s*-\s*(.+?)\s*$/.exec(line); + if (!item) break; + names.push(item[1].replace(/\s+#.*$/, "").replace(/^["']|["']$/g, "")); + } + break; + } + if (names.length === 0) { + console.error(`retouch: ${file} declares no spec.affects — nothing to touch`); + process.exit(1); + } + return names; +} + +// `metadata.name` from a component.yaml, read the same minimal way. +function componentName(file) { + const lines = fs.readFileSync(file, "utf8").split(/\r?\n/); + for (let i = 0; i < lines.length; i++) { + const m = /^(\s*)metadata:\s*$/.exec(lines[i]); + if (!m) continue; + const indent = m[1].length; + for (let j = i + 1; j < lines.length; j++) { + const line = lines[j]; + if (/^\s*(#.*)?$/.test(line)) continue; + const lead = /^(\s*)/.exec(line)[1].length; + if (lead <= indent) break; + const nm = /^\s*name:\s*(.+?)\s*$/.exec(line); + if (nm && lead === indent + 2) return nm[1].replace(/^["']|["']$/g, ""); + } + } + return null; +} + +// Every component.yaml in the tree, by the name it declares. +function indexComponents(root) { + const byName = new Map(); + const walk = (dir, depth) => { + let entries; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const ent of entries) { + const full = path.join(dir, ent.name); + if (ent.isDirectory()) { + if (SKIP_DIRS.has(ent.name) || depth >= MAX_DEPTH) continue; + walk(full, depth + 1); + } else if (ent.name === "component.yaml") { + const name = componentName(full); + if (!name) continue; + const rel = path.relative(root, full); + if (byName.has(name)) { + console.error( + `retouch: two component.yaml files declare metadata.name ${name}: ${byName.get(name)} and ${rel}`, + ); + process.exit(1); + } + byName.set(name, rel); + } + } + }; + walk(root, 0); + return byName; +} + +function stamp() { + for (const key of ["ORUN_RUN_ID", "ORUN_SESSION_ID"]) { + const v = (process.env[key] || "").trim(); + if (v) return v.replace(/\s+/g, "-"); + } + return new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z"); +} + +// The file with exactly one marker line, last, and a trailing newline. Every +// other byte is kept as it was. +function retouched(text, marker) { + const hadTrailingNewline = text.endsWith("\n"); + const lines = text.split("\n"); + if (hadTrailingNewline) lines.pop(); + const kept = lines.filter((l) => !MARKER_RE.test(l)); + // A file that was only a marker, or empty, still ends up valid. + const body = kept.length ? kept.join("\n") + "\n" : ""; + return body + marker + "\n"; +} + +function main() { + const opts = parseArgs(process.argv.slice(2)); + const root = process.cwd(); + const wanted = opts.components + ? opts.components.split(",").map((s) => s.trim()).filter(Boolean) + : readAffects(opts.affects); + if (wanted.length === 0) usage("no components named"); + + const index = indexComponents(root); + const missing = wanted.filter((n) => !index.has(n)); + if (missing.length) { + console.error( + `retouch: no component.yaml declares metadata.name for: ${missing.join(", ")} (looked under ${root})`, + ); + process.exit(1); + } + if (opts.check) { + for (const n of wanted) console.log(`retouch --check: ${n} -> ${index.get(n)}`); + console.log(`retouch --check: ${wanted.length} component(s) resolve.`); + return; + } + + const marker = `# orun: redeploy ${opts.phase} ${stamp()}`; + const verb = opts.dryRun ? "would" : ""; + let changed = 0; + for (const n of wanted) { + const rel = index.get(n); + const file = path.join(root, rel); + const before = fs.readFileSync(file, "utf8"); + const after = retouched(before, marker); + const had = before.split("\n").some((l) => MARKER_RE.test(l)); + if (after === before) { + console.log(`retouch: ${rel}: unchanged (marker already ${marker.slice(2)})`); + continue; + } + if (!opts.dryRun) fs.writeFileSync(file, after); + changed++; + console.log(`retouch: ${rel}: ${verb ? "would " : ""}${had ? "replace" : "add"} marker`); + } + console.log( + opts.dryRun + ? `retouch --dry-run: ${changed} of ${wanted.length} file(s) would change; nothing written.` + : changed > 0 + ? `retouch: ${changed} of ${wanted.length} component.yaml file(s) marked "${marker.slice(2)}" — the landing has a diff.` + : `retouch: nothing to do (every marker already current).`, + ); +} + +main(); diff --git a/tooling/deploy/fleet-stubs.mjs b/tooling/deploy/fleet-stubs.mjs new file mode 100755 index 0000000..176c78d --- /dev/null +++ b/tooling/deploy/fleet-stubs.mjs @@ -0,0 +1,158 @@ +#!/usr/bin/env node +// Placeholders for the fleet's service-binding targets (zero-dependency). +// +// Cloudflare refuses a deploy whose service binding names a Worker that does +// not exist yet (code 10143), and the fleet's bindings form cycles (billing +// <-> membership; membership -> notifications -> events -> membership), so on +// a fresh account no order of first deploys works. 04-workers used to break +// this by deploying the fleet once with the feedback edges stripped from the +// wrangler config (`cycle-break.mjs --strip`) and again, as a second landing +// and a second convergence, with them restored. +// +// This does it with ONE deploy each instead, and 04-workers-restore is gone +// with it. policy-worker binds to nothing, and every worker that holds a +// binding waits on it (an enforced `dependsOn` on main). Its pre-deploy step +// runs this tool, which uploads a placeholder script for every binding target +// in this environment that does not exist yet. Every real deploy then starts +// after the placeholders exist, carries its full bindings, and replaces its +// own placeholder. +// +// Nothing else deploys while this runs (every binding holder waits on it), +// so a placeholder never overwrites a real Worker. On a live product every +// target exists and the tool uploads nothing. +// +// node tooling/deploy/fleet-stubs.mjs --root ../.. # deploy step +// node tooling/deploy/fleet-stubs.mjs --root . --env stage --list +// +// The targets come from every apps/*/wrangler{.template,}.jsonc: the +// `services[].service` names of the environment's section. The environment is +// --env, else ORUN_ENVIRONMENT (set by orun on every job). The account and +// token are CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN, as the deploy step +// has them; CLOUDFLARE_API_BASE_URL overrides the API (tests). + +import * as fs from "node:fs"; +import * as path from "node:path"; + +const COMPAT_DATE = "2025-05-01"; +const STUB = `// Placeholder created by tooling/deploy/fleet-stubs.mjs so that the Workers +// binding to this one could deploy first. Its own first deploy replaces it. +export default { + async fetch() { + return new Response("not deployed yet", { status: 503 }); + }, +}; +`; + +function arg(name, fallback) { + const i = process.argv.indexOf(name); + return i >= 0 ? process.argv[i + 1] : fallback; +} + +// JSONC → JSON: drop // and /* */ comments outside strings, then trailing +// commas. Enough for wrangler configs; not a general parser. +export function parseJsonc(text) { + let out = ""; + let inStr = false; + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (inStr) { + out += c; + if (c === "\\") out += text[++i] ?? ""; + else if (c === '"') inStr = false; + continue; + } + if (c === '"') { + inStr = true; + out += c; + } else if (c === "/" && text[i + 1] === "/") { + while (i < text.length && text[i] !== "\n") i++; + out += "\n"; + } else if (c === "/" && text[i + 1] === "*") { + i = text.indexOf("*/", i + 2); + if (i < 0) break; + i++; + } else { + out += c; + } + } + return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1")); +} + +// Every service-binding target named by the environment's section of any +// worker config under /apps, sorted and de-duplicated. +export function bindingTargets(root, env) { + const apps = path.join(root, "apps"); + const targets = new Set(); + for (const app of fs.readdirSync(apps).sort()) { + for (const name of ["wrangler.template.jsonc", "wrangler.jsonc"]) { + const file = path.join(apps, app, name); + if (!fs.existsSync(file)) continue; + const config = parseJsonc(fs.readFileSync(file, "utf8")); + const services = [...(config.services ?? []), ...(config.env?.[env]?.services ?? [])]; + for (const s of services) if (s?.service) targets.add(s.service); + break; // the template when there is one; the rendered file is its output + } + } + return [...targets].sort(); +} + +async function main() { + const root = arg("--root", "."); + const env = arg("--env", process.env.ORUN_ENVIRONMENT || ""); + if (!env) { + console.error("fleet-stubs: no environment (--env or ORUN_ENVIRONMENT)"); + process.exit(2); + } + const targets = bindingTargets(root, env); + if (process.argv.includes("--list")) { + for (const t of targets) console.log(t); + return; + } + if (targets.length === 0) { + console.log(`fleet-stubs: no service bindings in ${env}; nothing to do`); + return; + } + + const account = process.env.CLOUDFLARE_ACCOUNT_ID; + const token = process.env.CLOUDFLARE_API_TOKEN; + if (!account || !token) { + console.error("fleet-stubs: CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN are required"); + process.exit(2); + } + const base = (process.env.CLOUDFLARE_API_BASE_URL || "https://api.cloudflare.com/client/v4").replace(/\/$/, ""); + const auth = { Authorization: `Bearer ${token}` }; + const script = (name) => `${base}/accounts/${account}/workers/scripts/${encodeURIComponent(name)}`; + + const created = []; + for (const name of targets) { + const res = await fetch(`${script(name)}/settings`, { headers: auth }); + if (res.ok) continue; + if (res.status !== 404) { + // Not "missing" and not "there": refuse to guess, or a placeholder + // could replace a real Worker the check failed to see. + console.error(`fleet-stubs: checking ${name}: HTTP ${res.status} ${await res.text()}`); + process.exit(1); + } + const form = new FormData(); + form.append("metadata", new Blob([JSON.stringify({ main_module: "stub.mjs", compatibility_date: COMPAT_DATE })], { type: "application/json" })); + form.append("stub.mjs", new Blob([STUB], { type: "application/javascript+module" }), "stub.mjs"); + const put = await fetch(script(name), { method: "PUT", headers: auth, body: form }); + if (!put.ok) { + console.error(`fleet-stubs: creating ${name}: HTTP ${put.status} ${await put.text()}`); + process.exit(1); + } + created.push(name); + } + console.log( + created.length + ? `fleet-stubs: ${created.length} placeholder(s) in ${env}, replaced by each Worker's first deploy: ${created.join(", ")}` + : `fleet-stubs: all ${targets.length} binding targets in ${env} exist; nothing to do`, + ); +} + +if (import.meta.url === `file://${process.argv[1]}`) { + main().catch((err) => { + console.error(`fleet-stubs: ${err?.message ?? err}`); + process.exit(1); + }); +}