diff --git a/.baseline/product/AGENTS.md b/.baseline/product/AGENTS.md new file mode 100644 index 0000000..df70a01 --- /dev/null +++ b/.baseline/product/AGENTS.md @@ -0,0 +1,78 @@ +# AGENTS.md — {{ .productname }} + +You are working in `{{ .githuborg }}/{{ .reponame }}`, a multi-tenant SaaS on +Cloudflare Workers and Supabase Postgres. It is an Orun desired-state repo: +every directory with a `component.yaml` is a component, and merging to `main` +is what deploys it. + +## Read first, in this order + +1. [`ai/context/operations.md`](ai/context/operations.md) — the operating + contract: how a merge deploys, the secrets model, how to verify, common + operations. +2. [`ai/context/deployment.md`](ai/context/deployment.md) — this product's + live facts: URLs, workspace, secrets by name. Generated, so it is only as + current as its last refresh. +3. [`intent.yaml`](intent.yaml) — the environments (`dev` verify-only, + `stage`, then `prod`), the pinned composition catalog, the workspace. +4. `apps/api-edge/docs/` — the one public entry point and how it routes to + the workers. Every app has the same three pages: overview, architecture, + runbook. +5. `apps/cms/docs/` — the CMS, which is the console: the Payload admin + with Lumen sign-in and the account and billing pages, how it deploys, + how the owner opens its admin, and how to change a collection (a + migration, never a push). +6. `apps/web-console-next/docs/` — the old console URL, now a redirect + Worker into the CMS. + +## Layout + +- `apps/api-edge` is public; the twelve `apps/*-worker` are reached only + through it, over service bindings. +- `apps/cms` — the product: Payload CMS on Workers (OpenNext), public on + its own hostname. Its admin is the console: a Lumen account signs in + (no Payload passwords), and the account, organization, notifications, + security activity and billing pages call `api-edge` server to server + over the `LUMEN_API` service binding. No worker calls the CMS. Its schema is `cms`, changed only by migrations in + `packages/db`. +- `apps/web-console-next` — a small redirect Worker: every old console + path answers 308 to its place in the same environment's CMS. +- `packages/*` — contracts, SDK, CLI, database harness, policy engine. +- `infra/terraform/*` — Supabase, Hyperdrive, KV, and the CMS's own + Hyperdrive (`cloudflare-hyperdrive-cms`); `infra/db-migrate` — the schema + migrations. +- `tests/*` — one suite per component. + +## How a change lands + +- One task, one branch, one pull request into `main`. +- Locally: `pnpm install`, then `pnpm typecheck`, `pnpm lint`, `pnpm test` + and `pnpm build`. +- `orun plan --changed --intent intent.yaml` lists the component lanes your + change plans — what CI will run. A change that touches no component plans + nothing and deploys nothing. +- The pull request's CI plans and verifies. Merging deploys `stage`, then + `prod`. A green run is not proof: check the URLs and the published wiring + the way `operations.md` shows. +- A new component is a directory under `apps/`, `packages/`, `infra/` or + `tests/` with a `component.yaml`; Orun discovers it on the next plan. +- Secrets are never committed. Provider credentials are brokered per run; + runtime secrets are set with `orun secrets set`. + +## Do not touch + +- `execution.state` in `intent.yaml` (`workspace`, `backendUrl`, + `requireOrg`): CI's credential-free sign-in depends on it. +- `.rebrand/values.json` — this product's identity record; the docs refresh + reads it. +- `ai/context/deployment.md`, and the README between the `08-docs` markers: + both are regenerated, and hand edits are overwritten. +- `.github/workflows/ci.yml` beyond its version pins. CI runs `orun plan` and + `orun run`, never pnpm, Wrangler or Terraform directly. +- `pnpm-lock.yaml` by hand — run `pnpm install`. +- A worker's `wrangler.jsonc` where a `wrangler.template.jsonc` sits beside + it: edit the template; the render is gitignored. +- The service bindings between billing, membership, notifications and events + form a loop that deploys in two passes on a fresh account. The loop is + pinned in `tests/config-worker/src/deployment-config.test.ts`; do not grow + it. diff --git a/.baseline/product/README.md b/.baseline/product/README.md new file mode 100644 index 0000000..65fc371 --- /dev/null +++ b/.baseline/product/README.md @@ -0,0 +1,78 @@ +# {{ .productname }} + +`{{ .githuborg }}/{{ .reponame }}` — a multi-tenant SaaS on Cloudflare Workers +and Supabase Postgres, run as an [Orun](https://github.com/sourceplane/orun) +component-native desired-state repo. Identity, organizations, projects, RBAC, +audit, metering, billing, webhooks and notifications are separate +bounded-context Workers behind one public edge API. The product opens in its +Payload CMS admin, which is the console: a Lumen account signs in, and the +account, organization, notifications and billing pages live inside it. + +## Live deployment + + +Not recorded yet. The build's last phase writes the live URLs, the workspace +and the secrets inventory into +[ai/context/deployment.md](ai/context/deployment.md); how the product deploys +and how to operate it is in +[ai/context/operations.md](ai/context/operations.md). + + +## Working on it + +Start at [AGENTS.md](AGENTS.md). It is written for a coding agent and is the +shortest way in for a person too: what to read first, how a change lands, and +what not to touch. + +## What is here + +| Path | What it is | +|---|---| +| `apps/api-edge` | The one public HTTP entry point; reaches the workers over service bindings | +| `apps/*-worker` | Twelve bounded-context Workers — identity, membership, projects, policy, events, config, metering, billing, notifications, webhooks, integrations, admin. Never public | +| `apps/cms` | The product and its console: Payload CMS on Workers (OpenNext), signed in with a Lumen account; content, media on R2, and the account and billing pages, calling the edge server to server | +| `apps/web-console-next` | The old console URL, now a redirect Worker: every path answers 308 to its place in the CMS | +| `packages/*` | Shared libraries: contracts, SDK, CLI, the database harness, the policy engine, the notifications client, the webhook verifier | +| `infra/terraform/*` | The data plane: Supabase projects, Hyperdrive for the fleet and a cache-disabled one for the CMS, the CMS's R2 media bucket, the edge's idempotency KV, and the custom-domain component (parked until a domain is set) | +| `infra/db-migrate` | Database migrations — planned on pull requests, applied on merge | +| `tests/*` | Per-component contract and verifier suites | +| `intent.yaml` | The environments, the pinned composition catalog, and the Orun workspace this repository deploys into | + +`stage` and `prod` are provisioned and deployed; `dev` is verify-only. + +## Getting started + +Node.js 20 or later and pnpm 10. + +```bash +pnpm install +pnpm typecheck +pnpm lint +pnpm test +pnpm build +``` + +## How it deploys + +Merges to `main` converge through Orun: `.github/workflows/ci.yml` runs +`orun plan --changed`, then one `orun run` lane per planned component. A pull +request plans and verifies; a push to `main` deploys `stage`, then `prod` once +`stage` has converged on the same commit. No pnpm, Wrangler or Terraform +command runs directly in CI. + +The pipeline holds one credential, GitHub's own `GITHUB_TOKEN`. Cloudflare and +Supabase credentials are brokered per run from the workspace's connections; +nothing provider-shaped is stored in the repository or in GitHub. + +## The first CMS admin + +The admin opens to nobody until its owner says so: the first admin is created +with a one-time setup token the owner sets, and every later person is let in +from inside the admin. [Open the admin](apps/cms/docs/runbook.md#open-the-admin-first-admin) +is the step, per environment. + +## Custom domain + +The product answers on workers.dev from its first deploy. Setting a domain is +one pull request, later: +[Setting the domain later](ai/context/operations.md#setting-the-domain-later). diff --git a/.baseline/product/deployment.md b/.baseline/product/deployment.md new file mode 100644 index 0000000..f46ce9a --- /dev/null +++ b/.baseline/product/deployment.md @@ -0,0 +1,8 @@ +# {{ .reponame }} — live deployment manifest + +> Not rendered yet. The bootstrap's `08-docs` phase probes every live URL — +> the edge, the CMS that is the console, and the console URL that redirects +> into it — 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 new file mode 100644 index 0000000..9ba28c1 --- /dev/null +++ b/.github/workflows/baseline.yml @@ -0,0 +1,144 @@ +name: Baseline CI + +# THE FACTORY'S OWN LANES — tiers 0 to 2 (saas-bootstrap-engine BE5, BE6; +# ported from cirrus). +# +# These test the BASELINE: that its build document parses with the orun a +# bootstrap actually runs, that every component it ships is placed by exactly +# one phase, that a placed tree comes up branded and answering, and that a +# product carries nothing it should not. +# +# ─── WHY THIS IS NOT IN ci.yml ────────────────────────────────────────── +# +# `repo-blueprint.yaml`'s `github-workflows` module copies the WHOLE `.github` +# directory, so every workflow here travels into every product built from this +# repository — unless the blueprint's `ignore` names it, which it does for this +# file. These jobs run `testing/*.sh`, and `testing/` is deliberately not +# placed — so in a product they would be steps that cannot pass, red on its +# very first pull request, in a repository whose owner has no idea what a +# "blueprint" is. +# +# `ci.yml` carried exactly that until now, as its `flows-contract` job. It +# keeps `plan` and `run`: those are the orun component lanes, and a product +# genuinely needs them. +# +# The split is enforced, not remembered: `testing/coverage.test.sh` fails on +# any workflow that reads a path under `testing/` and is not in the blueprint's +# `ignore` list. + +on: + push: + branches: [main] + pull_request: + +concurrency: + group: baseline-ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read + +jobs: + # The baseline's contract suite, run directly rather than through a + # component. It used to ride a `tests/flows` component whose `quick-check` + # profile runs setup, install and a package-structure check — and no tests + # (observed live on cirrus: `4 passed, 0 failed`, none of them a test). + # These scripts need bash, python3 and git and nothing else — no workspace + # install, no network, no credential. + # + # THIS is the job that makes the suite able to fail a PR. + baseline-contract: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - 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 retouch bootstrap-defer fleet-stubs pen-reset; do + echo "── $t" + bash "testing/$t.test.sh" + done + + # THE BLUEPRINT PARSES WITH THE BINARY A BOOTSTRAP ACTUALLY RUNS. + # + # Every other test here reads the YAML with PyYAML, which will parse anything + # well-formed. On cirrus that let a blueprint reach main that no released orun + # could read a word of: + # + # ✕ unknown flag: --phase + # ✕ parse blueprint: yaml: unmarshal errors: + # line 613: cannot unmarshal !!map into []scaffold.Hook + # + # So this job pins the same version the bootstrap does and makes orun itself + # answer. `--status` derives every phase's state: it parses the document, + # validates each phase's hooks against the action registry, compiles every + # `when` and every narration template, and writes nothing. It does not probe + # — derivation asks the tree, not the network — so it needs no credential. + blueprint-parses: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: sourceplane/orun-action@v1.2.0 + with: + # 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 + orun --version + # Inputs that are `required: true` must be supplied for the document + # to resolve; the values are arbitrary and nothing is written. No + # domain: the console asks for none, so the document must resolve + # without one. + orun new --blueprint repo-blueprint.yaml --status \ + --out "$(mktemp -d)" \ + --set reponame=acme-cloud \ + --set "productname=Acme Cloud" \ + --set githuborg=acme-inc + # Tier 1's leak gate. It derives what every phase WOULD place and gates + # that set — so it needs orun, which is why it rides this job rather than + # the bash-only one above. + - name: the leak gate — what a product carries + run: bash testing/leak.test.sh + # Tier 1's other half. This one PLACES the tree, brands it exactly as + # 01-scaffold's hooks do, and runs the phases that follow. It needs node + # for rebrand alongside orun, and about thirty seconds. Still offline: + # placement writes files, and a run with hooks off does not probe. + - uses: actions/setup-node@v6 + with: + node-version: "20" + - name: Tier 1 — the tree is placed, branded, and made to answer + run: bash testing/placement.test.sh + + # TIER 2 — THE PLACED, BRANDED PRODUCT COMPILES AND PASSES ITS OWN SUITES. + # + # Placement proves a product comes out branded and that orun accepts it. It + # cannot prove the product's CODE survived the rebrand, and here the rebrand + # renames code: the CMS names the platform `lumen` in every case-form — a + # Payload field and the column derived from it, route and module + # directories, a binding, a cookie, a migration — and every one of those + # must still agree after it. So this places the whole blueprint, brands it + # as the phases do, and asks the product: a frozen install, every package + # typechecked, every suite run. About three minutes; no credential. + branded-fork: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: sourceplane/orun-action@v1.2.0 + with: + version: v2.88.0 + # pnpm's version is package.json's `packageManager`, as in the product. + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v6 + with: + node-version: "22" + - name: Tier 2 — the branded product installs, typechecks and passes its suites + run: bash testing/branded-fork.test.sh diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml new file mode 100644 index 0000000..3bf216b --- /dev/null +++ b/.github/workflows/tag.yml @@ -0,0 +1,103 @@ +name: Baseline tag + +# CUTS A `baseline-vN` TAG FOR THIS REPOSITORY. +# +# A baseline tag is what the platform's registry resolves and what every +# product bootstrapped from this repository is built out of, so it is cut by a +# workflow rather than by hand: the version must look like a baseline tag, an +# existing tag is never moved, and the commit is resolved here, once. +# +# Whether a commit is fit to release is decided outside this repository, by +# whoever cuts the tag; nothing here asks for proof beyond a green `main`. +# +# No console is published with it. The Lumen baseline also packs a prebuilt +# console per tag so a bootstrap can fetch it instead of building; this +# baseline's console is the CMS, which every product builds itself. + +on: + workflow_dispatch: + inputs: + version: + description: "The tag to cut, e.g. baseline-v25." + required: true + type: string + ref: + description: "Branch, tag or sha to cut it from. Defaults to main." + required: false + default: main + type: string + +concurrency: + group: baseline-tag + cancel-in-progress: false + +permissions: + contents: read + +jobs: + cut: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v6 + with: + # Full history: the ref being cut from may be any commit, and a + # shallow clone cannot resolve one it did not fetch. + fetch-depth: 0 + ref: ${{ inputs.ref }} + + - name: the version must look like a baseline tag + run: | + set -euo pipefail + # Refused here rather than by the API, because the API's error for a + # malformed ref says nothing about the convention it broke — and a + # tag that does not match `baseline-v*` is invisible to the backstop + # above, which is the one shape of mistake that disables the gate. + case "${{ inputs.version }}" in + baseline-v[0-9]*) ;; + *) echo "✕ '${{ inputs.version }}' is not a baseline-vN tag" >&2; exit 1 ;; + esac + + - name: resolve the commit + id: commit + run: | + set -euo pipefail + sha="$(git rev-parse HEAD)" + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "Cutting ${{ inputs.version }} from ${{ inputs.ref }} = $sha" + + - name: the tag must not already exist + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + code="$(curl -sS -o /dev/null -w '%{http_code}' \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/git/ref/tags/${{ inputs.version }}")" + if [ "$code" = "200" ]; then + echo "✕ ${{ inputs.version }} already exists. A baseline tag is never moved:" >&2 + echo " products resolve it, and repointing one changes what a build that" >&2 + echo " already shipped was made of. Cut the next number." >&2 + exit 1 + fi + # Anything other than 200 or 404 means the question was not answered, + # and "it probably does not exist" is not a thing to guess about a + # tag that is about to be created. + [ "$code" = "404" ] || { echo "✕ could not check for the tag (HTTP $code)" >&2; exit 1; } + + - name: cut the tag + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + curl -sS -X POST --fail-with-body \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/git/refs" \ + -d "$(printf '{"ref":"refs/tags/%s","sha":"%s"}' \ + "${{ inputs.version }}" "${{ steps.commit.outputs.sha }}")" + echo "" + echo "✓ ${{ inputs.version }} → ${{ steps.commit.outputs.sha }}" + echo " Next: move the registry row in orun-cloud's infra/baselines-registry/baselines.yaml." diff --git a/AGENTS.md b/AGENTS.md index 3eec4e0..23928f5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,6 +25,26 @@ is what deploys it. 6. `apps/web-console-next/docs/` — the old console URL, now a redirect Worker into the CMS. +## This repository is also a baseline + +Products are built from it by `repo-blueprint.yaml` ([BOOTSTRAP.md](BOOTSTRAP.md)). +The factory — `blueprint.yaml`, `repo-blueprint.yaml`, `.baseline/product/`, +`tooling/rebrand/`, `tooling/bootstrap/`, `hooks/`, `testing/`, +`docs/phases/`, `tasks/0*.TaskContract.yaml`, `.github/workflows/baseline.yml` +and `tag.yml` — never ships to a product. Two consequences for any change: + +- **A new component needs a module and a phase** in `repo-blueprint.yaml`, + or no product gets it: `testing/coverage.test.sh` fails until it has one. +- **Code that names the platform is renamed in every product.** The rebrand + turns `lumen` in any case-form — `lumenUserId`, `lumen_user_id`, `LUMEN_API`, + `LumenLogin`, `lib/lumen/`, "Lumen account" — into the product's name, paths + included. Keep a bare `lumen` out of identifier positions (a variable named + `lumen` becomes a slug, which is not an identifier); `testing/branded-fork.test.sh` + places a product and runs its typecheck and suites, and catches it. + +Run the gates with `bash testing/.test.sh` (leak, placement and +branded-fork need `orun` ≥ v2.88.0 on `PATH`; branded-fork needs `pnpm`). + ## Layout - `apps/api-edge` is public; the twelve `apps/*-worker` are reached only @@ -64,7 +84,7 @@ is what deploys it. - `execution.state` in `intent.yaml` (`workspace`, `backendUrl`, `requireOrg`): CI's credential-free sign-in depends on it. - `.rebrand/values.json` — this product's identity record; the docs refresh - reads it. + reads it, and the rebrand reads it as the baseline's own names. - `ai/context/deployment.md`, and the README between the `08-docs` markers: both are regenerated, and hand edits are overwritten. - `.github/workflows/ci.yml` beyond its version pins. CI runs `orun plan` and diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md new file mode 100644 index 0000000..271527d --- /dev/null +++ b/BOOTSTRAP.md @@ -0,0 +1,458 @@ +# BOOTSTRAP — fresh product from this baseline, in phases + +How to go from **nothing** to a **fully deployed, documented baseline** — +the Supabase and Cloudflare data plane, the 12-worker fleet, api-edge, and +the Payload CMS that is the product's console (with its own Hyperdrive path +and media on R2), live on stage and prod — with two provider consents +(Cloudflare and Supabase) and the GitHub App. What is left for the owner +afterwards is opening the CMS admin (§4). + +There is one artifact: **`repo-blueprint.yaml`**. It declares what to place, +in what order, what each phase needs first, and what to say while it runs. +`orun new` is the whole runtime — the phases below are its `--phase` names, +not separate workflows. Everything the old shell layer ("the flows") did is +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: **23 minutes**, the sum of the phases' own `expectedMinutes` — +**derived, not timed end to end**: no bootstrap of this baseline has run as +a whole yet. Seven of the eight phases are the Lumen baseline's, file for +file, and carry its measured run (18 minutes, 2026-10-26). `06-console` is +the one this baseline changes: it BUILDS Payload, where Lumen fetches a +prebuilt console, and its 7 minutes is this repository's own measured CMS +deploys (6m06s–7m12s from merge to stage and prod). Supabase project +creation (5–7m per environment) is still the longest wait nobody can +shorten. The runs, phase by phase: +[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.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 + rendered bool; v2.58.5 is the first that can bootstrap at all — it writes + each phase's files on that phase's turn, its landing commits, seeds an + empty repository and deletes the branch it merged, and a convergence + watches the commit it landed (`sha:`); v2.58.6 is the first whose landing + waits for a PR's whole CI run — every phase here is a pull request that + must go green before it merges; v2.58.7 checks that the workspace's GitHub + connection is to the account that owns the repository (`githubOwner`), + without which no PR is ever seen by the platform; v2.58.8 looks for the + published secrets on the project's environments, where the infrastructure + publishes them (`secrets/exists` `environments`); v2.58.10 treats a project + the bootstrap has not created yet as "not yet" rather than a failed + 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. 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 + that owns the repo: the platform sees a product's pull requests only + through it. +- **Cloudflare.** An account on the Workers paid plan (the fleet needs it) + and its **Account API token** — the console's Connect recipe lists the + permission groups. Four keys are minted from it and a minted child can + never exceed its parent, so the token must cover Workers Scripts Write, + Workers KV Storage Write, **Hyperdrive Write**, **Workers R2 Storage + Write** (the CMS's media bucket, `r2-data`) and Account Settings Read. R2 + must be enabled on the account once, in the dashboard, before the first + bucket can be created. +- **Supabase.** An organization with room for two more projects + (`-stage` and `-prod`), connected by OAuth consent — + or by a pasted personal access token. The connection is anchored on ONE + organization, and that is where both projects are created: for an account + in several organizations, the OAuth consent, where you pick one, is the way + to be sure which. +- **An Orun Cloud workspace** for the product — `orunWorkspace`, or the + workspace the build runs in (ORUN_WORKSPACE) when that is unset — with an + **admin-role API key** for headless runs. Builder and viewer keys can read, + but their secret writes are denied (masked as `not_found`), and the first + write is `03-infrastructure`'s: a sub-admin key gets through two phases + and stops at the third. +- **The repo linked to the workspace.** `01-scaffold` tries `orun cloud link` + and then gates on `orun cloud check`. With a user session the link heals + itself; a workspace-scoped key cannot write links, so the repo must be + allow-listed in the console (Settings → Git repos) — do it up front, or + the phase stops and names this step. Everything else is headless. + +## 1. One command: `--resume` + +The whole bootstrap, unattended. `--resume` places every phase not already +derived as done, in dependency order, honouring each phase's barrier: + +```bash +git clone --depth 1 --branch https://github.com/sourceplane/lumen-payload +cd lumen-payload + +orun new --blueprint repo-blueprint.yaml \ + --out ~/sourceplane/acme --run-hooks --resume \ + --set reponame=acme --set productname="Acme Cloud" \ + --set githuborg=sourceplane \ + --set orunWorkspace=ws_XXXXXXXX \ + --set subdomain= +``` + +`subdomain` is the workers.dev subdomain of the Cloudflare account you deploy +into, not the product name. Every generated URL and the api-edge CORS +allowlist derive from it, so a wrong value ships a product that deploys +cleanly and is unreachable at every address it advertises. Find it under +Workers & Pages in the dashboard. + +A build started from the console, or with `orun baseline new --from bst_…`, +never asks for it: the platform reads it from the workspace's Cloudflare +connection, the same one the deploy tokens mint from. Only a hand-run build +like this one passes it. + +**No domain is asked.** The blueprint's required inputs are `reponame`, +`productname` and `githuborg`; the domain is not one of them. The product +goes live on workers.dev, and `productdomain` defaults to empty, which brands +the reserved placeholder `.example.com` wherever the domain goes +(intent's `BASE_DOMAIN` and `CONSOLE_CUSTOM_DOMAIN`, the edge and identity +console origins, the mail sender, the billing return URLs) for an owner to +replace later (§4). With no domain the CLI's default API is the product's own +prod edge, `https://-api-edge-prod..workers.dev`. Pass +`--set productdomain=` only for a product that already has its domain; the +CLI then defaults to `https://api.`. + +**`--run-hooks` is the difference between placing files and bootstrapping a +product.** Without it `orun new` writes the tree and stops: no repo is +created, nothing is landed, no convergence is watched, and no phase probes +its preconditions. That is deliberate — it is what makes a dry instantiation +of this baseline possible in CI with no workspace and no provider. + +`--resume` is safe to re-run from anywhere, including a fresh container with +a fresh `--out`: **phase state is derived from the tree, never stored.** A +phase whose files are all present but differ from the blueprint — which is +every phase after `01-scaffold` brands the tree — derives as `drifted`, and +`--resume` leaves it placed rather than reverting your product's identity to +`lumen-payload`. + +## 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`, `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 — +**place its modules → land them as a PR that must go green → watch the +convergence → verify the outcome** — and each carries its own narration. +Full guide: [docs/phases/README.md](docs/phases/README.md), with a page per +phase in that folder. + +```bash +# phase 01 takes the identity once: +orun new --blueprint repo-blueprint.yaml --out ~/sourceplane/acme --run-hooks \ + --phase 01-scaffold \ + --set reponame=acme --set productname="Acme Cloud" \ + --set githuborg=sourceplane \ + --set orunWorkspace=ws_XXXXXXXX --set subdomain= + +# 01 committed the answers as .rebrand/values.json, keyed by the blueprint's +# own inputs. The required inputs are still validated on every invocation, +# so that file is the easiest --values for every later phase: +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, +# 05-edge, 06-console, 08-docs. +``` + +The flags that shape a run: + +| flag | what it does | +|---|---| +| `--status` | derives and prints every phase's state and writes nothing. This is the preview — it parses the document, validates each hook against the action registry, compiles every `when` and every narration template, and does **not** probe. It needs no credential and no network | +| `--phase ` | places exactly that phase. Its `requires.phases` still gates: a predecessor that is `pending` refuses the run and names it | +| `--until ` | places every phase through that one and stops | +| `--resume` | places every phase not already derived as done | +| `--values ` / `--set k=v` | inputs; `--set` overrides the file | +| `--run-hooks` | runs the hooks — probes, secrets, landings, watches. Without it, placement only | + +What lands in the product is PRODUCT-ONLY: source, infra, CI, configs, and +its own docs. None of this baseline's machinery ships — not the blueprint or +the card, not the rebrand, bootstrap, fork or migration tooling, not +`tasks/`, `hooks/`, `testing/`, `specs/`, `agents/`, `docs/phases/` or this +file, and only two files of `ai/context/` (`deployment.md`, `operations.md`). +Nothing in the product presents it as a copy of anything. That promise is a +test: `testing/leak.test.sh` derives what every phase *would* place and gates +the set. + +The workspace needs its three integrations connected once. `01-scaffold` +waits for GitHub; `03-infrastructure`'s `requires.probe` polls for all three +for up to 10 minutes, so the consents can be clicked while it waits: + +- **Cloudflare**: paste the Account API token (in-console recipe). If its + permission groups miss one a template needs — Hyperdrive Write is the + usual gap — that mint is refused (`parent_grant_insufficient`) and + `03-infrastructure` stops with the message. Re-issue the token, re-connect, + re-run the phase. +- **Supabase**: OAuth consent; pick the organization that owns this + product's projects. Changing the OAuth app's scopes later revokes every + existing connection of that app — the brokered secrets go `orphaned`; + re-connect and re-run `03-infrastructure`. + +`03-infrastructure`'s five secret hooks are a *reconcile*: keys that exist +are kept, keys that are missing are minted against the ACTIVE connection. + +| key | provider | template | +|---|---|---| +| `CLOUDFLARE_API_TOKEN` | cloudflare | `workers-deploy` | +| `CLOUDFLARE_HYPERDRIVE_TOKEN` | cloudflare | `hyperdrive-edit` — the deploy token deliberately cannot touch Hyperdrive | +| `CLOUDFLARE_ACCOUNT_ID` | cloudflare | `account-id` — a connection fact, not a secret | +| `SUPABASE_ACCESS_TOKEN` | supabase | `management-access` | +| `SUPABASE_ORG_ID` | supabase | `org-id` — a connection fact, not a secret | + +## 2. Headless / container mode (Daytona, CI, any sandbox) + +The blueprint's source is this repo itself (`sources: [{kind: dir, path: .}]`), +so the container contract is a shallow clone at a pinned tag plus two tokens. +orun pins the checkout by digest into its object store before any module +reads it, so the run is reproducible and provenanced. + +```bash +# The whole container contract: +export ORUN_TOKEN=… # orun auth, headless +export GITHUB_TOKEN=… # fine-grained PAT (scopes below) + +git clone --depth 1 --branch https://github.com/sourceplane/lumen-payload +cd lumen-payload + +orun new --blueprint repo-blueprint.yaml \ + --out /work/acme --run-hooks --resume --progress json \ + --values /work/acme.values.yaml +``` + +`--progress` is four renderings of ONE stream — they differ in what they +show, never in what happened. `json` emits the raw event objects, one JSON +object per line, `schema: bootstrap-event/v1` (a hosted runner or a console +build page reads these); `plain` prints the narration alone, one line per +event, for a CI log; `verbose` adds every detail line; `auto` is narration +with the engine's facts under it. + +**The stream is hook execution, not placement.** A run WITHOUT `--run-hooks` +emits one `skipped` event per declared-but-unplaced phase and nothing else — +so `--resume --progress json` with hooks off, which places every phase and +skips none, prints no events at all. That is not a broken flag: the events +describe phases starting, waiting, finishing and failing, and with hooks off +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.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-payload` (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 | +| workdir | `--out` is the product tree and is stable across phases and re-runs. The baseline checkout is `{{ .baseline.dir }}` to every hook | +| classic-token caveat | a CLASSIC PAT or gh OAuth token additionally needs the `workflow` scope to push the CI files under `.github` (hit live); fine-grained PATs need only `contents: write` | +| identity | commits fall back to `bootstrap-bot` when no git identity is configured | + +> **Contract change.** Earlier Lumen baselines — this one's parent — were bootstrapped from a shell +> layer: one workflow file per phase, run by remote reference, and one more +> that ran them all. There are no per-phase files any more: one pinned +> artifact, selected with `--phase `. What the old inputs became: +> +> | then | now | +> |---|---| +> | `workspace` | `orunWorkspace` (or the workspace the build runs in) | +> | `out` / `repo` | `--out` / `githuborg` + `reponame` | +> | `githuborg` defaulting to `sourceplane` | `githuborg` REQUIRED, no default | +> | `epicslug` | `epicSlug` | +> | `dryrun=true` | drop `--run-hooks`, or `--status` | +> | `from`, `fresh` | `--resume`, `--phase`, `--until` | +> | `track` | gone — every landing is tracked | +> | `watch=false` | gone — the watch falls back to REST on its own, and reports rather than hangs if even that is blocked | + +## 3. The console path + +The console renders **`blueprint.yaml`**, the card, and never this file or +the blueprint directly. The card owns the build contract: the overview, the +three integrations and the admin key role it requires, the inputs the form +collects, a read-only preview of the six brokered secrets and of the +programme (the epic and its seven milestones), and `bootstrap.blueprint: +repo-blueprint.yaml` — the document a runner places. The registry row in +orun-cloud owns identity and the pinned tag; the card is fetched *at* that +tag, which is why it carries none. + +What that means for a console build: + +- `reponame` and `githuborg` come from the repository the operator picked; + `subdomain` from the workspace's Cloudflare connection + (`from: connection.cloudflare.workersSubdomain` — the connection the build + is bound to, so it names the account the deploy tokens mint from); only + `productname` is typed. +- No domain is asked. `productdomain` and `apibaseurl` (which the card + derived from it, and a card can only derive from inputs it declares) left + the card in baseline-v30: the product is born with the placeholder + `.example.com` where the domain goes, and its CLI defaults to its + own prod edge on workers.dev. An owner sets the domain later (§4). +- `orunWorkspace` is not on the form — it cannot be. The build runs inside + the workspace, and `from: workspace` (orun ≥ v2.58.11) fills it from there. +- There is no `domain` input. The custom-domain component lands in + `06-console`, parked, on every build, and an owner wires it later in an + ordinary PR (§4). +- The runner hands its refreshed token over through `ORUN_TOKEN_FILE` + (`bootstrap.tokenChannel`), so a session that rotates mid-build does not + end it. + +`testing/manifest.test.sh` holds the card to the blueprint rather than to a +copy of itself: the secrets it previews are compared to the reconcile hooks +that mint them, and its programme and inputs to the blueprint's. + +## 4. After the baseline is live + +- **The first CMS admin — the owner's, once per environment.** The CMS + answers from its first deploy, and a signed-in person with no role is + pending; the first admin is made with a setup token only the owner holds. + Set `CMS_SETUP_TOKEN` (16+ characters, yours) as a workspace secret for + the environment, deploy the CMS once (Actions → CI → Run workflow, + component `cms`), visit `https://-cms-..workers.dev/setup?token=` + and sign in: the account that signs in with that cookie while no admin + exists becomes the admin. Delete the secret afterwards. The product's + `apps/cms/docs/runbook.md` ("Open the admin") is the step. The bootstrap + does not do it on purpose: it would mean a build holding an admin's + credential. +- **Payment provider**: billing reads, plans and invoices work without one; + checkout and the customer portal need the provider's credentials as the + billing worker's runtime secrets (below). +- **Deployment record**: `08-docs` is the close-out, and safe to re-run any + time as a live-state refresh. +- **Custom domain**: a product built without one carries the placeholder + `.example.com` wherever the domain goes; replacing it + (`git grep -l .example.com`) is the first step, and the + product's `ai/context/operations.md`, "Setting the domain later", lists + every place and step. The `cloudflare-domain` component is already in the + product, landed by `06-console`: parked (it subscribes to no environment) + and mid-migration to provider v5. Create the product zone in + Cloudflare, finish the v5 resource and restore the component's + commented-out `subscribe` block in an ordinary PR (see + [docs/phases/06-console.md](docs/phases/06-console.md#the-custom-domain--parked)), + and re-run `--phase 08-docs` once it converges so the docs pick up the + domain URLs. +- **Runtime secrets** (OAuth client secrets, billing keys, …): seed with + `orun secrets set --org --env `; the next deploy pushes + them to the workers (`wire-now-seed-later` — nothing blocks on them). +- **Incremental rollouts**: normal PRs — merges to `main` converge + automatically. + +## 5. Changing this baseline (maintainers) + +This repository's own CI is **`baseline.yml`**, and it never ships: the +blueprint's `ignore` list keeps it out of the `.github` copy, and +`testing/coverage.test.sh` fails on any workflow that reads `testing/` +without being listed there. `ci.yml` is the product's — `plan` and `run`, +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` (every case-form of the platform word renamed and still agreeing, paths with it, migrations re-sealed), `retouch`, `bootstrap-defer`, `fleet-stubs`, `pen-reset` | +| `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) | +| `branded-fork` | Tier 2: the whole blueprint placed from the fixture and branded as the phases brand it, then the product asked about itself — the lockfile refreshed, a frozen install, every package typechecked, every Worker config rendered from its fixture, every suite run. It exists because this baseline's rebrand renames code, not just words: a Payload field and its column, route and module directories, a binding, a cookie, a migration | + +All of it runs locally with no credential — `bash testing/.test.sh` +from the repo root. Leak and placement need `orun` on `PATH` at the floor +version, and placement needs `node` as well; `branded-fork` needs `pnpm` and +the npm registry, and nothing else. + +### What this baseline does not have yet + +Cirrus, the Lumen baseline's Cloudflare-only sibling, has three things +neither Lumen nor this baseline has ported, and their absence is worth +stating rather than leaving implied: + +- **No tier-3 rehearsal.** Nothing here bootstraps a whole product from + nothing on a schedule (Cirrus: `testing/rehearsal/`, `rehearsal.yml`). The + highest tier this baseline's CI reaches is the branded fork's own suites, + offline from every provider. +- **No tag gate.** A `baseline-v*` tag is cut by hand; nothing refuses one + from a commit no real bootstrap has proven (Cirrus: `tag.yml`, + `testing/tag-gate.sh`). Until there is, a tag is only as proven as the last + bootstrap someone watched end to end. +- **No teardown.** A trial product — the repo, two Supabase projects, the + KV namespaces, Hyperdrive configs and R2 buckets, the workers — is removed + by hand + (Cirrus: `testing/teardown.sh`). + +## Troubleshooting + +Most rows were hit on real bootstraps of Lumen or its sibling Cirrus, which +runs the same engine; the rest are refusals the blueprint now makes on +purpose, written down so they read as instructions rather than breakage. + +| Symptom | Cause → fix | +|---|---| +| `01-scaffold` parks: `waiting for github for (connected: )` | The workspace's GitHub connection is to a different account than the one the product repository will live under, so the platform would never see its pull requests. Connect the GitHub App installation on `` to the workspace (console → Integrations → GitHub), then `--resume`. | +| `01-scaffold` stops: `/ is not linked to workspace ` | The credential could not link the repo and the platform has not. Allow-list it (console → Settings → Git repos) or `orun cloud link --org ` with a user session, then re-run the phase. Without the link every convergence lane dies at the OIDC exchange. | +| `03-infrastructure` waits on connections, then stops | Consent not granted yet — console → Integrations, then re-run the phase. The probe is a *wait*, not a failure. | +| `03-infrastructure` reconcile refused: `parent_grant_insufficient` | The Cloudflare token's permission groups do not cover a template (usually Hyperdrive Write, or Workers R2 Storage Write for `CLOUDFLARE_R2_TOKEN`'s `r2-data`). Re-issue the token, re-connect, re-run the phase. | +| `cloudflare-r2-cms` apply fails, asking for R2 to be enabled | R2 has never been enabled on the Cloudflare account. Enable it once in the dashboard (R2 → Get started), then resume the convergence. | +| A phase refuses with `requires: 02-foundation (pending)` | Its predecessor has not been placed into this `--out`. Run that phase, or `--resume`. A predecessor that is `drifted` SATISFIES the requirement — its files are all there. | +| `--resume` prints "leaving 01-scaffold as placed" | Expected after branding. Every file is present but differs from the blueprint, so the phase is `drifted` and re-placing it would revert your product's identity. Re-place one deliberately with `--phase `. | +| Secrets listed `orphaned` | Their connection was revoked or replaced (e.g. the Supabase OAuth app's scopes changed). Re-connect the provider and re-run `--phase 03-infrastructure`: the reconcile re-mints only the missing keys against the ACTIVE connection. | +| Secret WRITE fails `not_found` while listings work | The API key's role is below ADMIN (resource-hiding masks the denial). Re-mint the key with the admin role; the reconcile is idempotent. | +| Supabase lane: `does not support oauth access` on `/billing/addons` | Provider ≥ 1.6.0 sneaked in — the root pins `~> 1.5.1`; keep the pin. | +| Supabase lane: duplicate project name | The organization already has `-` (a half-torn-down previous attempt). Adoption imports it automatically when it is the *same* product re-bootstrapping; otherwise delete the stray project. Adopting resets the database password (see [03-infrastructure.md](docs/phases/03-infrastructure.md)). | +| 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`. | +| `06-console`: the CMS `/health` answers 503 `{"secret":"missing"}` | `PAYLOAD_SECRET` is not on the Worker: `cloudflare-hyperdrive-cms` (03-db) has not published `CMS_PAYLOAD_SECRET` for that environment. Re-run `03-infrastructure-database`, whose verify names it, then resume the console's convergence. `{"db":"error"}` instead means Payload started and schema `cms` did not answer: check db-migrate applied migration 200. | +| `06-console`: CMS deploy fails `Authentication error [code: 10000]` on `/r2/buckets/…` | wrangler tried to provision the media bucket with the deploy token, which has no R2 permission. The CMS sets `skipResourceProvisioning: true`, which needs stack-tectonic ≥ 0.21.0 — check the pin in `intent.yaml`. | +| `06-console` verify: the console URL answers 200 or 404, not 308 | 308 is the redirect into the CMS, and the probe does not follow it. A 404 is a host the redirect does not serve: check the rebrand renamed its `CMS_WORKER_PREFIX` and host pattern. | +| `db-migrate` refuses: `Checksum mismatch for 206_…` | A migration's file no longer hashes to the checksum `packages/db/src/manifest.ts` records. The rebrand re-seals each migration it rewrites; a mismatch after it is a hand edit to a migration — revert it and add a new migration instead. | +| `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` | 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"` / `"checks"` / `"secrets"` / `"background"` | The CLI is below the v2.88.0 floor. This blueprint is not readable by an older one. | +| A phase's `verify` reports `no such host` for every URL, with a GREEN convergence | The deploy worked; the addresses are wrong. `subdomain` must be the Cloudflare account's own workers.dev subdomain — a deploy lane smokes the URL wrangler actually returned, so a wrong `subdomain` passes every lane and first surfaces here. Check it with `curl -s -o /dev/null -w '%{http_code}\n' https://-api-edge-stage..workers.dev/health`: `000` means the name does not resolve. Fix `subdomain` in `.rebrand/values.json`, re-run `rebrand.mjs`, and re-run the phase. Seen on a build that carried `test-lum`, which is not a claimed subdomain. | +| `fleet-stubs: could not create placeholder …` with Cloudflare `10037` | The account is at its 500-Worker limit. The pre-deploy continues (a placeholder it cannot make is not policy-worker's failure), but no new script can be created, so the deploys that need one fail next with the same code. Delete unused Workers on the account; nothing in the repo can work around an account limit. | +| `! [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). | +| Console/edge smoke fails right after the FIRST deploy of a worker | workers.dev route propagation race — the deploy lane's smoke retries with backoff (stack-tectonic ≥ 0.18.2); a convergence resume clears older pins. | +| Terraform lane: "state already locked" by ITS OWN plan | Backend lock-release race — a convergence resume clears it. | +| Lanes fail with NO logs at all | GitHub Actions billing or spending limit. The message lives only in the check-run annotations (`gh api repos///check-runs//annotations`). | +| Environment cannot observe GitHub Actions (gh 403) | `orun.pr/land@v1` and `orun.run/watch@v1` fall back to plain REST automatically. If even REST Actions is blocked, the watch reports it rather than hanging — verify the run out of band before the next phase. | +| Many lanes queued, none claiming | Runner-pool starvation — `max-parallel: 8` in `ci.yml` is deliberate (the resolve herd); patience, or check the run is not superseded. | + +## Architecture invariants this depends on + +- **Phase state is derived, never stored.** Nothing in `--out` records which + phases have run; the engine asks the tree. A stored file would be a cache, + and it must always be safe to delete — which is what makes a phase runnable + alone, months later, from a fresh container. The one record a later phase + reads, `.rebrand/values.json`, is product content, committed, and says who + the product is — not how far its bootstrap got. +- **The product's CI holds one credential: `GITHUB_TOKEN`.** Provider + credentials are brokered per run from workspace integrations; terraform + state lives on the platform (`backend "http"`, run-token auth); terraform + outputs travel as lease-published job-output secrets. No AWS, no Secrets + Manager, no long-lived provider tokens on any deploy path. The bootstrap's + own secret hooks hold no value either: a brokered secret is a pointer at a + connection and a scope template, minted just-in-time at resolve. +- **Every phase is a pull request that is verified, then merged.** PR runs + carry remote state so lanes resolve their secrets there too; nothing + mutating runs on a PR (deploy and apply profiles are gated on a push to + `main`). That is the reason phase 03 is two landings. +- **Resume-capable CI**: exec-id is the GitHub run id (no attempt suffix) and + every re-run lane passes `--retry` — `gh run rerun --failed` is a true + resume. +- **`cloudflare-domain` is the only component parked by design**; every + other component deploys on the merge that lands it. diff --git a/README.md b/README.md index 7d0f749..d69da5b 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,38 @@ Start at [AGENTS.md](AGENTS.md). It is written for a coding agent and is the shortest way in for a person too: what to read first, how a change lands, and what not to touch. +## A baseline: products from this repository + +This repository is also the **Multi-tenant Payload CMS baseline**: a product +is born from it — its own repository, Supabase projects, Workers and CMS, live +on stage and prod — by one artifact, [`repo-blueprint.yaml`](repo-blueprint.yaml), +run by `orun new` ([BOOTSTRAP.md](BOOTSTRAP.md) → +[docs/phases/](docs/phases/README.md)). Eight idempotent phases — scaffold, +foundation, infrastructure, database, workers, edge, console, docs — each land +a verified pull request, and each is selectable with `--phase `. The +console phase is this baseline's own: it lands the Payload CMS and the console +URL that redirects into it. What the owner does afterwards is open the CMS +admin with a setup token only they hold. + +A product receives **product-only content**, branded with its own name: the +source, infrastructure and CI, its own README, AGENTS.md and operating guide. +None of the factory below ships, and nothing in a product says `lumen`: the +CMS names the platform `lumen` in its code (`lib/lumen/`, `lumenUserId`, +`LUMEN_API`), and the rebrand renames every form of it — paths included — into +the product's, so a Payload field and the column it maps to, a route and the +URLs that reach it, still agree. + +| Path | What it is | +|---|---| +| `blueprint.yaml` | The card the console renders: overview, providers, inputs, the six brokered secrets, the programme | +| `repo-blueprint.yaml` | The build: every module, the eight phases and their hooks | +| `BOOTSTRAP.md`, `docs/phases/` | How to run it, phase by phase, and what each phase proves | +| `.baseline/product/` | The product's README, AGENTS.md and deployment stub, rendered with its name | +| `tooling/rebrand/` | The rename engine: this repository's own identity (`.rebrand/values.json`) into the product's | +| `tooling/bootstrap/`, `hooks/` | The hooks' scripts: promotion and dev-lane deferral, redeploy markers, the deployment record | +| `testing/` | The baseline's own gates, run by `.github/workflows/baseline.yml`: the card against the build, every component placed once, a product placed and branded offline, and that product installed, typechecked and tested | +| `tasks/0*.TaskContract.yaml` | The contract each phase's task is opened with | + ## What is here | Path | What it is | diff --git a/apps/cms/component.yaml b/apps/cms/component.yaml index 9b7545b..b24f732 100644 --- a/apps/cms/component.yaml +++ b/apps/cms/component.yaml @@ -54,6 +54,10 @@ spec: - mode: advisory when: triggerRef: github-pull-request + # Bundled at build time (@saas/contracts). Without the edge, `orun plan + # --changed` keys on `path:` alone and the CMS could ship a copy of the + # package that has since changed underneath it. + - component: contracts # Runtime secrets, pushed to the Worker by secrets-live after each deploy. # PAYLOAD_SECRET generated by cloudflare-hyperdrive-cms; nobody types it. # CMS_SETUP_TOKEN the owner's, and only if they want to open first-user diff --git a/blueprint.yaml b/blueprint.yaml new file mode 100644 index 0000000..70a813b --- /dev/null +++ b/blueprint.yaml @@ -0,0 +1,208 @@ +# The Multi-tenant Payload CMS card: the CONTRACT the platform's bootstrap door reads +# and the console renders, screen for screen (epic saas-bootstrap-console, BC3). +# +# Everything the console shows about this baseline comes from this file. Adding +# a provider to `requires` grows a row in the Providers step; adding a key to +# `secrets` grows a row in the Secrets step. Neither needs a console change. +# +# The registry (orun-cloud `infra/baselines-registry/baselines.yaml`) owns +# identity and commerce — id, visibility, tier, the pinned tag. This file owns +# the build contract. (The registry owned two more paths, the brief and the +# umbrella, until the flows layer they named was deleted. This baseline is +# blueprint-driven: `spec.bootstrap` declares neither, and the registry row +# that fetches this file declares neither either.) NEITHER RESTATES THE +# OTHER, which is why there is no `tag` here: this file is fetched *at* the tag +# the registry pins, so a tag here could only rot — as it did, reading +# `baseline-v17` against a live `baseline-v27`, ten releases adrift. +apiVersion: orun.io/v1 +kind: Blueprint +metadata: + name: lumen-payload + displayName: Multi-tenant Payload CMS + description: > + Cloudflare + Supabase multi-tenant SaaS whose console is Payload CMS: + 12 bounded-context Workers behind one edge API, Payload on Workers with + its own Hyperdrive path and media on R2, signed in with the product's own + accounts, terraform data plane, migrations, CI that converges on merge. + Live on stage+prod in about 23 minutes (derived, not timed end to end). + tags: [saas, cms, cloudflare, supabase, payload, nextjs] +spec: + source: + repo: sourceplane/lumen-payload + # No `tag`. See the header: the registry pins it, this file is fetched at it. + # ── What the operator reads first (the flow's step 1) ─────────────────── + overview: + lede: > + A multi-tenant SaaS that opens in its CMS: Payload on Cloudflare + Workers is the console, signed in with the product's own accounts, + over the same twelve-Worker fleet and Supabase Postgres. + architecture: + - layer: Console + items: [Payload CMS (admin, REST, GraphQL), console URL → CMS] + - layer: Edge + items: [api-edge] + - layer: Services + items: ["12 bounded-context Workers"] + - layer: Data + items: [Supabase Postgres, Hyperdrive (fleet + CMS), KV, R2 media] + - layer: Delivery + items: [Terraform, GitHub Actions, db-migrate] + outcome: + - Live on stage and prod + - A Payload admin as the console, with account, organization and billing pages + - Media on R2, schema `cms` applied by migrations on merge + + requires: + # GitHub arrives as the App installation plus the repo link; Cloudflare + # and Supabase are the two provider connections phase 03 asks for. + integrations: [github, cloudflare, supabase] + apiKeyRole: admin # secret writes need the admin floor + + inputs: + # Every input is collected by the console (inputs v3). `askedBy` is gone: + # it divided inputs into ones a form collects and ones an agent asked for + # in the session, and there is no agent in the build path any more. + # + # The cost lands here. An `askedBy: agent` input was exempt from `pattern`, + # because prose asked for it and prose does not validate. Every input now + # carries the rule its value is checked against before Continue. + # + # THE DOMAIN IS NOT ASKED. The product goes live on workers.dev, and a + # domain is an owner's step after the bootstrap: `productdomain` defaults + # to empty in repo-blueprint.yaml, and the rebrand writes the reserved + # placeholder `.example.com` wherever the domain goes (intent's + # BASE_DOMAIN and CONSOLE_CUSTOM_DOMAIN, the edge and identity origins, the + # mail sender, the billing return URLs) for the product's + # ai/context/operations.md, "Setting the domain later", to replace. Nothing + # that needs a domain is removed — it waits for one. `apibaseurl` went with + # it: it was derived from `{productdomain}`, and a card can only derive + # from inputs it declares. With no domain, the CLI's default API is the + # product's own prod edge on workers.dev (rebrand.mjs). + - key: reponame + label: Repo name + pattern: "^[a-z][a-z0-9-]{1,38}$" + # The console already has this: the operator picked the repository. Say + # so rather than making the flow ask for the name printed above the + # field — and say it HERE, because the only alternative was for the + # console to special-case this key by name, which would make the console + # the authority on what a baseline's own input means. + from: repo.name + - key: productname + label: Product display name + pattern: "^[A-Za-z0-9][A-Za-z0-9 .,'&-]{1,48}$" + help: The name people will see — in the console header, the emails, the docs. + example: Acme Cloud + - key: githuborg + label: GitHub organisation + pattern: "^[A-Za-z0-9][A-Za-z0-9-]*$" + help: The GitHub org or user the product repository is created under. + # DERIVED FROM THE CHOSEN REPOSITORY, not asked. The operator picks the + # product repo in step 1, and its owner IS this value — a form field for + # it would be a second chance to get it wrong. `repo-blueprint.yaml` + # requires it, so a card that did not declare it would hand a build + # every field it showed and still die on `input "githuborg" is required`. + from: repo.owner + - key: subdomain + label: workers.dev subdomain + pattern: "^[a-z0-9][a-z0-9-]{0,62}$" + help: The workers.dev subdomain on the Cloudflare account this builds into. + example: acme + # READ FROM THE CLOUDFLARE CONNECTION, not asked. The subdomain belongs + # to the account the same way its id does, and there is exactly one + # right answer — a typed one could only be wrong, and wrong showed up + # after deploy, in CORS, OAuth origins, smoke checks and the verify URLs + # below. The integration reads it from Cloudflare at connect and on its + # hourly health check; the bootstrap door fills this input from the + # connection the build is BOUND to, the same one CLOUDFLARE_ACCOUNT_ID + # and the deploy tokens mint from, so all three name one account. + # + # No orun action and no `probe:` is needed, because the platform already + # holds the fact. An account with no workers.dev subdomain refuses the + # build at the door, naming the fix, before anything is created. + from: connection.cloudflare.workersSubdomain + + # ── PREVIEW ONLY. `repo-blueprint.yaml`'s `integrations/reconcile` hooks + # mint these, brokered, during phase 03. ──────────────────────────────── + # Transcribed from those hooks' own `keys:` and `template:` values, so + # `testing/manifest.test.sh` compares this list to the document that mints + # them rather than to a copy of itself — it used to compare against a shell + # script's `create` calls, and that script is gone with `flows/`. + # The console renders them read-only: they are minted from the workspace's + # connections at build time, so no credential is ever typed, shown or stored + # in the console. Keys that already exist are kept. + secrets: + - key: CLOUDFLARE_API_TOKEN + provider: cloudflare + template: workers-deploy + why: Workers + KV deploys + - key: CLOUDFLARE_HYPERDRIVE_TOKEN + provider: cloudflare + template: hyperdrive-edit + why: Hyperdrive — the deploy token deliberately cannot touch it + - key: CLOUDFLARE_R2_TOKEN + provider: cloudflare + template: r2-data + why: The CMS media bucket — the deploy token cannot create or read one + - key: CLOUDFLARE_ACCOUNT_ID + provider: cloudflare + template: account-id + why: Connection fact, not a secret + fact: true + - key: SUPABASE_ACCESS_TOKEN + provider: supabase + template: management-access + why: Project create and migrations + - key: SUPABASE_ORG_ID + provider: supabase + template: org-id + why: Connection fact, not a secret + fact: true + + # ── PREVIEW ONLY. Each phase's `orun.task/ensure@v1` hook opens + # 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. + # 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}" + milestones: + - name: 01-scaffold + - name: 02-foundation + - name: 03-infrastructure + - name: 04-workers + - name: 05-edge + # The custom-domain component lands in 06-console, parked (it + # subscribes to no environment until an owner wires a zone), so the + # optional 07-domain milestone and the `domain` input that switched it + # on are gone. The numbering keeps its gaps so 08 keeps its name. + - name: 06-console + - name: 08-docs + + bootstrap: + # THE BUILD DOCUMENT: the file whose phases a runner places. This baseline + # has no umbrella and no agent brief — the flows layer they named is gone + # — so this is the only entry point, and without it a runner that fetched + # this repo at its pinned tag would have nothing to run. `manifestPath` in + # 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. + # + # DERIVED, NOT TIMED END TO END. No bootstrap of this baseline has been + # run as a whole yet. Phases 01–05 and 08 are the Lumen baseline's, file + # for file, and carry that run's measured minutes (18 in all, 2026-10-26). + # 06-console is the one this baseline changes — it builds Payload instead + # of fetching a prebuilt console — and its 7 is this repository's own + # main-branch convergences that built and deployed the CMS to stage and + # prod: 6m06s to 7m12s over four runs. The CMS's Hyperdrive config and + # bucket apply in lanes beside 03's and 03-db's (1.5 to 2.4 minutes on + # their own), so they add no time. docs/phases/TIMINGS.md has the runs. + expectedMinutes: 23 + tokenChannel: ORUN_TOKEN_FILE # how a runner hands over its refreshed token + verify: + urls: + - "https://{reponame}-api-edge-{env}.{subdomain}.workers.dev/health" + - "https://{reponame}-cms-{env}.{subdomain}.workers.dev/health" + envs: [stage, prod] diff --git a/docs/components/REVIEW.md b/docs/components/REVIEW.md new file mode 100644 index 0000000..7e0d34f --- /dev/null +++ b/docs/components/REVIEW.md @@ -0,0 +1,142 @@ +# Component review — what each one declares, and how fully it is documented + +Every one of this repository's **49 components** — the Lumen baseline's 45 +and the four the CMS adds — scored on five measurable signals. Generated +against the tree on 2026-10-30, not typed by hand, so a number here is a fact +about the repository rather than an impression of it. + +## The rubric + +One point each, out of five: + +| | signal | why it is the bar | +|---|---|---| +| 1 | `docs/overview.md` exists | the catalog's primary page for the component | +| 2 | `metadata.description` is set | without it the catalog row has no summary; orun emits the `Repo` entity from `description` alone | +| 3 | the overview carries 3+ headings | a title and one paragraph is a stub, however well written | +| 4 | the overview runs to 100+ words | enough to say what it is, what it needs and what breaks | +| 5 | 2+ further `docs.pages` are declared (architecture, runbook) | somewhere to put what the overview should not carry | + +A 5 is not a ceiling on quality and a 3 is not a failing component — a small +pure package may deserve a short page. The scores are here to show **where the +documentation is thinnest**, not to rank the code. + +## Scores + +| component | domain | type | score | overview words | headings | description | +|---|---|---|---|---|---|---| +| `cloudflare-hyperdrive-cms` | infra | terraform | **5/5** | 169 | 4 | yes | +| `cloudflare-r2-cms` | infra | terraform | **5/5** | 179 | 4 | yes | +| `api-edge` | starter-runtime | cloudflare-worker-turbo | **5/5** | 222 | 3 | yes | +| `billing-worker` | starter-runtime | cloudflare-worker-turbo | **5/5** | 104 | 3 | yes | +| `cms` | starter-runtime | cloudflare-worker-turbo | **5/5** | 392 | 4 | yes | +| `integrations-worker` | starter-runtime | cloudflare-worker-turbo | **5/5** | 104 | 3 | yes | +| `membership-worker` | starter-runtime | cloudflare-worker-turbo | **5/5** | 159 | 3 | yes | +| `policy-worker` | starter-runtime | cloudflare-worker-turbo | **5/5** | 151 | 3 | yes | +| `projects-worker` | starter-runtime | cloudflare-worker-turbo | **5/5** | 104 | 3 | yes | +| `cms-tests` | starter-tests | turbo-package | **5/5** | 550 | 3 | yes | +| `web-console-next` | starter-ui | cloudflare-workers-assets-turbo | **5/5** | 202 | 4 | yes | +| `cloudflare-domain` | infra | terraform | **4/5** | 64 | 3 | yes | +| `cloudflare-hyperdrive` | infra | terraform | **4/5** | 83 | 3 | yes | +| `cloudflare-kv` | infra | terraform | **4/5** | 52 | 3 | yes | +| `supabase` | infra | terraform | **4/5** | 70 | 3 | yes | +| `contracts` | starter-contracts | turbo-package | **4/5** | 257 | 2 | yes | +| `db` | starter-data | turbo-package | **4/5** | 205 | 2 | yes | +| `admin-worker` | starter-runtime | cloudflare-worker-turbo | **4/5** | 57 | 3 | yes | +| `config-worker` | starter-runtime | cloudflare-worker-turbo | **4/5** | 70 | 3 | yes | +| `events-worker` | starter-runtime | cloudflare-worker-turbo | **4/5** | 78 | 3 | yes | +| `identity-worker` | starter-runtime | cloudflare-worker-turbo | **4/5** | 90 | 3 | yes | +| `metering-worker` | starter-runtime | cloudflare-worker-turbo | **4/5** | 72 | 3 | yes | +| `notifications-worker` | starter-runtime | cloudflare-worker-turbo | **4/5** | 81 | 3 | yes | +| `webhooks-worker` | starter-runtime | cloudflare-worker-turbo | **4/5** | 71 | 3 | yes | +| `admin-worker-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `api-edge-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `billing-worker-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `config-worker-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `contracts-tests` | starter-tests | turbo-package | **4/5** | 118 | 2 | yes | +| `db-tests` | starter-tests | turbo-package | **4/5** | 118 | 2 | yes | +| `identity-worker-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `integrations-worker-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `membership-worker-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `metering-worker-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `notifications-client-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `notifications-worker-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `platform-limits-tests` | starter-tests | turbo-package | **4/5** | 334 | 2 | yes | +| `policy-engine-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `policy-worker-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `projects-worker-tests` | starter-tests | turbo-package | **4/5** | 121 | 2 | yes | +| `db-migrate` | infra | db-migrate | **3/5** | 53 | 2 | yes | +| `cli` | starter-cli | turbo-package | **3/5** | 32 | 2 | yes | +| `sdk` | starter-sdk | turbo-package | **3/5** | 43 | 2 | yes | +| `notifications-client` | starter-shared | turbo-package | **3/5** | 58 | 2 | yes | +| `policy-engine` | starter-shared | turbo-package | **3/5** | 54 | 2 | yes | +| `shared` | starter-shared | turbo-package | **3/5** | 37 | 2 | yes | +| `testing` | starter-shared | turbo-package | **3/5** | 41 | 2 | yes | +| `webhook-verifier` | starter-shared | turbo-package | **3/5** | 55 | 2 | yes | +| `web-console-next-tests` | starter-tests | turbo-package | **3/5** | 96 | 1 | yes | + +Distribution: **5/5**: 11 · **4/5**: 29 · **3/5**: 9. + +## What the CMS added + +- **The four CMS components score 5/5**: `cms`, `cms-tests`, + `cloudflare-hyperdrive-cms` and `cloudflare-r2-cms` each carry an overview + with its headings and a runbook, and the CMS's runbook is where the owner's + first-admin step lives. +- **`web-console-next` rose to 5/5** when it became the redirect Worker: its + pages describe the 308 into the CMS and nothing else. +- **`web-console-next-tests` fell to 3/5**: its suite is now the redirect's + table, and its overview shrank with it (96 words, one heading). It is the + thinnest page in the repository. + +## The finding that is not a documentation problem + +**26 components subscribe with `profile: quick-check`, and that profile runs no +tests.** The Lumen baseline observed it directly on its own CI (a `db-tests · +dev · Verify` lane that ran setup, install and a 0.0s package-structure check, +and no tests), and it is true here, component for component: the suites live +in `preBuildCommand`, which `quick-check` skips, and the lane is still named +`· Verify`. + +**This repository has its own evidence now.** `tests/platform-limits` pins the +deepest service-binding chain, and the CMS's sign-in binding to api-edge +(lumen-payload-console PX1) made `cms` one hop deeper than the edge — a +deliberate change the suite asks to be recorded. It went unrecorded for three +pull requests, because `platform-limits-tests` is on `quick-check` and its +suite never ran. `testing/branded-fork.test.sh`, which runs every suite of a +placed product, found it; the depth is recorded now (`cms`, 9, under the +fleet's budget of 12). + +The fix is one word per component — `profile: verify` — and it is **not in +this change on purpose**, for the reason the Lumen baseline gave: it turns on +suites that have never run in a product's CI, and the right change for that is +one that can watch what it turns on. The baseline's own CI runs every suite of +a placed product instead (`branded-fork`), so a product is not born with a red +one. + +Components on `quick-check`: `admin-worker-tests`, `api-edge-tests`, `billing-worker-tests`, `cli`, `config-worker-tests`, `contracts`, `contracts-tests`, `db`, `db-tests`, `identity-worker-tests`, `integrations-worker-tests`, `membership-worker-tests`, `metering-worker-tests`, `notifications-client`, `notifications-client-tests`, `notifications-worker-tests`, `platform-limits-tests`, `policy-engine`, `policy-engine-tests`, `policy-worker-tests`, `projects-worker-tests`, `sdk`, `shared`, `testing`, `web-console-next-tests`, `webhook-verifier`. + +## Declared product URLs + +This repository's own environment doors, probed 2026-10-30 (read-only GETs): + +| URL | answer | +|---|---| +| `lumen-payload-api-edge-stage…workers.dev/health` | 200 | +| `lumen-payload-api-edge-prod…workers.dev/health` | 200 | +| `lumen-payload-cms-stage…workers.dev/health` | 200 | +| `lumen-payload-cms-prod…workers.dev/health` | 200 | +| `lumen-payload-web-console-next-stage…workers.dev` | 308 → the CMS | +| `lumen-payload-web-console-next-prod…workers.dev` | 308 → the CMS | + +These are `environments..url` and `links` in `intent.yaml`, which +`rebrand.mjs` rewrites per product; a product's own answer after `06-console` +is what its build's probes check. + +## Catalog ref collisions (orun v2.89.0) + +v2.89.0 refuses a domain, system or environment whose name gives it a +component's catalog ref — the component would be hidden in Orunbase. This +repository is clean: its domains are `infra, starter-cli, starter-contracts, +starter-data, starter-runtime, starter-sdk, starter-shared, starter-tests, +starter-ui`, and no component shares a name with any of them. diff --git a/docs/phases/01-scaffold.md b/docs/phases/01-scaffold.md new file mode 100644 index 0000000..6c4dd71 --- /dev/null +++ b/docs/phases/01-scaffold.md @@ -0,0 +1,209 @@ +# Phase 01 — scaffold + +Births the product repo from `repo-blueprint.yaml`'s `01-scaffold` phase and +connects it to its Orun Cloud workspace. After this phase the repo exists on +GitHub, CI runs on every push and pull request, and every later phase can +find the product's identity inside the repo itself. + +This is the only phase that creates anything on GitHub, and the only one +whose inputs are the product's identity rather than a reading of it. + +## What it lands + +The repo ROOT — no deployable components yet: + +- `intent.yaml`, with the product's workspace written into `workspace:`; + `ci.yml` (resume-capable CI: exec-id = run id, `--retry` on re-run + attempts, `max-parallel: 8`, `--remote-state` on pull requests too, lane + pin orun v2.56.2) +- `tooling/` — ONLY what product builds use: `eslint`, `tsconfig`, `wire` + (the deploy-time wrangler renderer) +- `ai/context/deployment.md` (the placeholder `08-docs` fills) and + `ai/context/operations.md` (the standing operating contract) — exactly + these two files, one module each, so a new file in `ai/context/` cannot + 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`, `.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 + next, how a change lands, what not to touch) +- empty discovery roots `apps/ infra/ packages/ tests/` (with `.gitkeep`) so + `orun new`'s repo-scale gate and the product CI can plan from birth + +**What deliberately does NOT land**: this baseline's machinery — +`repo-blueprint.yaml`, `blueprint.yaml`, `BOOTSTRAP.md`, this repository's +own `README.md`, `docs/phases/`, `agents/`, `specs/`, `tasks/`, `hooks/`, +`testing/`, `.vscode/` (its agent loop), the rebrand, bootstrap, fork and +migration tooling, and `baseline.yml` (the factory's own CI, which +the blueprint's `ignore` list keeps out of the `.github` copy). A product +carries product files only, and its docs never present it as a copy of +anything. `testing/leak.test.sh` derives what every phase would place and +gates the set, so the promise is a test rather than a claim. + +## Inputs + +| input | example | notes | +|---|---|---| +| `--out` | `$HOME/sourceplane/acme` | a flag, not an input; created if absent | +| `reponame` | `acme` | REQUIRED. Lowercase slug (`^[a-z][a-z0-9-]*$`); repo becomes `/` | +| `productname` | `Acme Cloud` | REQUIRED. Display name | +| `productdomain` | — (default empty) | NOT ASKED. Empty brands the placeholder `.example.com` where the domain goes, for an owner to replace later; pass it only for a product that already has its domain | +| `githuborg` | `sourceplane` | REQUIRED. The org or user the repo is created under | +| `orunWorkspace` | `ws_ABCD1234` | workspace id. Unset, the workspace the build runs in (ORUN_WORKSPACE); with none anywhere, the placeholder `ws_SET_ME` | +| `subdomain` | `rahulvarghesepullely` | workers.dev subdomain of the Cloudflare account you deploy into — every URL derives from it (worker names are brand-prefixed, so keeping the baseline's account is supported). A console or `--from bst_…` build reads it from the Cloudflare connection; pass it only for a hand-run build | +| `apibaseurl` | — (default empty) | CLI default API base; empty derives `https://api.`, or with no domain the prod edge, `https://-api-edge-prod..workers.dev` | +| `repoPrivate` | `true` (default) | visibility at creation only | +| `epicSlug` | `infra-baselining` (default) | the epic every phase files its task under | + +The full set, rebrand overrides included, is in the +[phases README](README.md#inputs) and `repo-blueprint.yaml`'s `inputs:` +block. + +## Steps + +1. **requires.probe** — `orun.doctor/check@v1` with `providers: [github]` + and `githubOwner: `, waiting up to 10 minutes. The platform + learns of a pull request only through the GitHub App installation on the + account that OWNS the repository; a workspace connected to some other + account passes "github is connected" and never sees a single PR of the + product it builds. So the owner's connection is asked for before a repo + exists, and waited for like any other consent. +2. **pre** — `orun.task/ensure@v1` twice: the epic (by `epicSlug`), then this + phase's task under it. +3. **place** — the engine writes this phase's modules into `--out`. +4. **the identity chain**, as `post` hooks in order: `git init` → `git add` + → `tooling/rebrand/rebrand.mjs --values .rebrand/values.json` → the + `orun-workspace` rewrite of `intent.yaml` → `git add` → `rebrand.mjs + --verify` → `pnpm install --lockfile-only`. The chain was the blueprint's + global `postInstantiate` once, because a one-shot instantiation has only + one end; in a phased bootstrap the end of `01-scaffold` IS that moment. + It is also why every later phase derives as `drifted` rather than `done`. + + The `workspace:` rewrite exists because rebrand classifies the orun state + backend as org-owned and leaves it alone — without it the product's CI + would claim the BASELINE's workspace on every remote operation. It fails + only when `intent.yaml` has no `workspace:` line; a line that already + names the workspace (a build into the one the baseline declares, or a + re-run) is nothing to do. +5. **repo — THE GitHub repo creation step**, an `orun.repo/ensure@v1` hook. + Three states are supported: + - `origin` already wired locally → push; + - the repo was **pre-created on GitHub** (org policy may restrict repo + creation to admins — create it empty, no README) → the action finds + it, wires `origin`, and pushes; + - nothing exists anywhere → it is created under `githuborg`, private + unless `repoPrivate=false`. + + Requires a `GITHUB_TOKEN` with repo-creation (or at least push) rights + on `githuborg`. +6. **link** — `orun cloud link --org ` (best effort), then + `orun cloud check --org ` as the gate. Every convergence lane + authenticates over GitHub OIDC, and the platform resolves that token + through the repo link; an unlinked repo fails every lane of the first + real convergence with `OIDC exchange rejected: Not found`. The link is + best effort because a workspace-scoped key may not write links (the + platform may have linked the repo already); the check is not, so an + unlinked repo stops here, naming the fix, instead of an hour later in + every lane. +7. **land** — `orun.pr/land@v1`. The empty repo is seeded with one commit on + `main`, and the scaffold arrives as PR #1 from `orun/BASE--01-scaffold`, + bound to the phase's task. It merges once that PR's CI run is green — + which it is trivially, since the scaffold carries no components to plan. + +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` +passes, and the phase's task is on the epic. The first CI run plans zero +components and is trivially green. + +## Re-running + +Idempotent: placement is additive, rebrand is a no-op on branded files, and +`git init` / the workspace rewrite / repo-ensure / link are guarded. Once the tree is branded this +phase derives as **`drifted`**, not `done` — so `--resume` leaves it alone +rather than reverting the product's identity to `lumen-payload`. Re-place it +deliberately with `--phase 01-scaffold`. + +## Troubleshooting + +- **Parks with `waiting for github for (connected: )`** — the + workspace's GitHub connection is to a different account than the one the + repo will live under. Connect the GitHub App installation on `` to the + workspace (console → Integrations → GitHub); the probe picks it up while + it waits, or re-run the phase. +- **`link` fails: `/ is not linked to workspace `** — the + credential could not link it and the platform has not either. Allow-list + the repo (console → Settings → Git repos) or run `orun cloud link --org + ` with a user session, then re-run the phase. +- **`intent.yaml` says `workspace: ws_SET_ME`, or the secret refs name the + repository (`secret:///…`)** — `orunWorkspace` was empty and the + build did not run inside a workspace. Set it, or run inside the workspace + with a CLI ≥ v2.58.11, which fills it from there. +- **A classic PAT is refused pushing CI files** — classic PATs and gh OAuth + tokens need the `workflow` scope to push anything under `.github`; + fine-grained PATs need only `contents: write`. + +## Example commands + +From the baseline checkout (local mode): + +```bash +orun new --blueprint repo-blueprint.yaml \ + --out $HOME/sourceplane/acme --run-hooks --phase 01-scaffold \ + --set reponame=acme \ + --set productname="Acme Cloud" \ + --set githuborg=sourceplane \ + --set orunWorkspace=ws_ABCD1234 \ + --set subdomain=rahulvarghesepullely +``` + +Headless (fresh container / no checkout — see BOOTSTRAP.md §2): clone the +baseline at a tag and run the same command, with `ORUN_TOKEN` + +`GITHUB_TOKEN` exported: + +```bash +export ORUN_TOKEN="$(orun auth token | tail -1)" GITHUB_TOKEN=… +git clone --depth 1 --branch https://github.com/sourceplane/lumen-payload +cd lumen-payload +orun new --blueprint repo-blueprint.yaml \ + --out /work/acme --run-hooks --phase 01-scaffold \ + --values /work/acme.values.yaml +``` + +Preview with zero side effects: drop `--run-hooks` — the phase places files +into `--out` and stops, with no `git init`, no rebrand, no repo and no +landing. `--status` derives every phase's state and writes nothing at all. + +From here on, the product's own `.rebrand/values.json` is a complete values +file for every later phase (`--values $HOME/sourceplane/acme/.rebrand/values.json`). + +## Next + +[Phase 02 — foundation](02-foundation.md). diff --git a/docs/phases/02-foundation.md b/docs/phases/02-foundation.md new file mode 100644 index 0000000..efc90a1 --- /dev/null +++ b/docs/phases/02-foundation.md @@ -0,0 +1,97 @@ +# Phase 02 — foundation + +Lands the **shared packages** — thirteen modules (`repo-blueprint.yaml`, +phase `02-foundation`) — that everything later builds on. Nothing deploys and no +provider connection is needed — the PR's verify lanes (turbo builds and +tests) are the whole gate, run once on the PR and again on `main`. + +## What it lands + +`packages/`: `cli`, `contracts`, `db`, `notifications-client`, +`policy-engine`, `sdk`, `shared`, `testing`, `webhook-verifier` — plus the +test suites for `contracts`, `db`, `notifications-client` and +`policy-engine` under `tests/`. Each is a `turbo-package` component whose +lanes build and test it in CI. + +`packages/db` carries the Postgres schema and its migrations, but nothing +applies them yet: the migration runner (`infra/db-migrate`) lands in +`03-infrastructure-database`, once there is a database to apply them to. + +## Inputs + +`--out` is the product repo. The blueprint's required inputs — `reponame`, +`productname`, `githuborg` — are validated before any phase +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). + +## Steps + +1. **requires** — `01-scaffold` must be placed in `--out`. +2. **pre** — `orun.task/ensure@v1`: this phase's task under the epic. +3. **place** — the engine writes this phase's modules into `--out`. They + arrive speaking `lumen-payload`, because `01-scaffold`'s rebrand ran before they + existed. +4. **brand** — `git add -A` → `rebrand.mjs --values .rebrand/values.json` → + `git add -A` → `rebrand.mjs --verify`, which refuses a landing with the + baseline's identity left in it. +5. **lockfile** — `pnpm install --lockfile-only`. `01-scaffold` wrote the + lockfile for the projects that existed then, and the lanes install with + `--frozen-lockfile`; without this step every package was refused before + a test ran (`ERR_PNPM_OUTDATED_LOCKFILE`). +6. **land** — `orun.pr/land@v1`: PR `phase(02-foundation): shared packages`, + waits for its verify lanes, merges. +7. **converge** — `orun.run/watch@v1` (an `await` hook) watches the run for + the merged commit and resumes transient lanes up to three times. + +## Verify / done means + +The main convergence run is green — every package builds and its tests +pass in the product repo. + +## Troubleshooting + +- **PR lanes fail building a package**: the baseline's packages are + self-contained; a failure here usually means a partial placement (re-run + the phase — placement is additive) or lockfile drift. +- **`ERR_PNPM_OUTDATED_LOCKFILE`**: the lockfile step did not run or did not + land. Re-run the phase; `pnpm install --lockfile-only` is idempotent. +- **`rebrand --verify` refuses**: a placed file still carries the baseline's + identity. The message names the file. That is a rebrand rule missing in + this baseline, not something to hand-edit in the product. +- **The landing picks up edits you did not intend**: commit or stash your + local changes in the product repo before running a phase. + `orun.pr/land@v1` lands what is in the tree, and a phase is meant to land + its own modules, not your work in progress. + +## Example commands + +From the baseline checkout: + +```bash +orun new --blueprint repo-blueprint.yaml --out $HOME/sourceplane/acme \ + --run-hooks --phase 02-foundation \ + --values $HOME/sourceplane/acme/.rebrand/values.json +``` + +Headless (fresh container / no checkout — see BOOTSTRAP.md §2): clone the +baseline at a tag and run the same command, with `ORUN_TOKEN` + +`GITHUB_TOKEN` exported: + +```bash +export ORUN_TOKEN="$(orun auth token | tail -1)" GITHUB_TOKEN=… +git clone --depth 1 --branch https://github.com/sourceplane/lumen-payload +cd lumen-payload +orun new --blueprint repo-blueprint.yaml --out /work/acme \ + --run-hooks --phase 02-foundation --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, the landing finds +nothing new, and the `await` hooks re-assert. + +## Next + +[Phase 03 — infrastructure](03-infrastructure.md). diff --git a/docs/phases/03-infrastructure.md b/docs/phases/03-infrastructure.md new file mode 100644 index 0000000..b4ce7dd --- /dev/null +++ b/docs/phases/03-infrastructure.md @@ -0,0 +1,257 @@ +# Phase 03 — infrastructure (two landings) + +The first phase that **deploys**: it lands the data plane and converges it +against real providers — a Supabase Postgres project, a KV namespace, the +CMS's R2 media bucket, two Hyperdrive configs (the fleet's, and a +cache-disabled one for the CMS) and the schema migrations, schema `cms` +included, on stage and prod. Its +terraform outputs are published as job-output secrets that every later phase +consumes. + +It is two phases in `repo-blueprint.yaml`, landed one after the other and +filed under one milestone: + +| phase | places | publishes | +|---|---|---| +| `03-infrastructure` | `supabase`, `cloudflare-kv`, `cloudflare-r2-cms` | `SUPABASE_PROJECT_REF`, `SUPABASE_DB_PASSWORD`, `SUPABASE_DB_URL`, `WIRING_CLOUDFLARE_KV`, `WIRING_CLOUDFLARE_R2_CMS` | +| `03-infrastructure-database` | `cloudflare-hyperdrive`, `cloudflare-hyperdrive-cms`, `db-migrate` | `WIRING_CLOUDFLARE_HYPERDRIVE`, `WIRING_CLOUDFLARE_HYPERDRIVE_CMS`, `CMS_PAYLOAD_SECRET` (and the applied schema) | + +## Why two landings + +Hyperdrive and db-migrate READ the database the first landing creates. Their +lanes resolve `SUPABASE_PROJECT_REF`, `SUPABASE_DB_PASSWORD` and +`SUPABASE_DB_URL` — Hyperdrive to build its origin, db-migrate to connect — +and those three are **job-output secrets of the supabase terraform APPLY**. +An apply runs only on `main`, after a merge. And a job's secret refs are +resolved before its first step whatever its profile does, so a PR lane that +only plans still needs them. + +On a fresh product, then, a PR that places all four modules is red by +construction: the Hyperdrive and db-migrate lanes ask for secrets that +cannot exist until that same PR has merged. The shell layer this blueprint +replaced placed all four here anyway and merged the PR without waiting on its +checks, leaving the convergence on `main` as the only gate. That also meant +the phase could never be verified before it merged. + +Every phase is now a pull request that is verified, then merged. So the two +consumers move to a follow-on phase that runs once supabase's outputs exist, +and each landing is one whose every lane can be green. It is a second phase +rather than more hooks on the first because `post` hooks all run before +`await` — "land, converge, *then* land the rest" cannot be one phase's hook +list — and because two units of work that land separately, with their own PR +and their own task, are two phases here. + +Supabase project creation takes five to seven minutes per environment and +dominates the first landing. Nothing on our side shortens it. + +## Prerequisites + +The three integrations ACTIVE in the workspace — the phase's +`requires.probe` polls up to 10 minutes, so the consents can be clicked +while it waits: + +- **GitHub** — the App installation on `githuborg` (already required by + `01-scaffold`). +- **Cloudflare** — the account's **Account API token**, on the Workers paid + plan (the fleet needs it). Four keys are minted from it, and a minted + child can never exceed its parent, so its permission groups must cover + all three token templates: `workers-deploy` needs Workers Scripts Write, + Workers KV Storage Write and Account Settings Read; `hyperdrive-edit` + needs Hyperdrive Write and Account Settings Read; `r2-data` needs Workers + R2 Storage Write. A token without them gets its mint refused as + `parent_grant_insufficient`. R2 must have been enabled on the account + once, in the dashboard, before the first bucket can be created. +- **Supabase** — the OAuth consent, picking the organization that will own + `-stage` and `-prod`; a pasted personal access token + (`sbp_…`) works too. The connection is anchored on ONE organization, and + `SUPABASE_ORG_ID` is that organization's id — both projects are created + there, so it needs capacity for two more. For an account in several + organizations, the OAuth consent, where you pick one, is the way to be + sure which. + +Check first with: + +```bash +orun integrations list --org ws_ABCD1234 --json +``` + +## `03-infrastructure` + +### What it lands + +- `infra/terraform/supabase` — a Supabase project per environment, + `-`, in the component's `supabaseRegion` + (`ap-southeast-1` in this baseline), with a database password terraform + generates. The provider is pinned `~> 1.5.1` (see failure modes). +- `infra/terraform/cloudflare-kv` — api-edge's idempotency namespace per + environment. +- `infra/terraform/cloudflare-r2-cms` — the CMS's private media bucket per + environment, applied with `CLOUDFLARE_R2_TOKEN`. It reads nothing anyone + publishes, which is why it lands here rather than with the CMS. + +All three roots carry the self-healing `adopt.tf` import machinery. The +merge's convergence applies them in parallel, and on success each apply +lease-publishes its outputs to the project's **environment** rungs (stage and +prod), not to the workspace: supabase publishes `SUPABASE_PROJECT_REF`, +`SUPABASE_DB_PASSWORD`, `SUPABASE_DB_URL`; kv publishes `WIRING_CLOUDFLARE_KV`; +the bucket publishes `WIRING_CLOUDFLARE_R2_CMS`, which the CMS renders its +`R2_MEDIA` binding from. + +### Steps + +1. **requires** — `02-foundation` placed, and a `requires.probe`: + `orun.doctor/check@v1` for `github`, `cloudflare` and `supabase`, with + `githubOwner`, up to 10 minutes. A declared precondition, not a + preamble: a consent nobody has clicked is a *wait*, and the phase says so + rather than failing. +2. **pre** — the phase's task, then two `orun.integrations/reconcile@v1` + hooks, one per connection, each minting its keys under their own scope + templates: + + | key | provider | template | read by | + |---|---|---|---| + | `CLOUDFLARE_API_TOKEN` | cloudflare | `workers-deploy` | kv, every worker deploy | + | `CLOUDFLARE_HYPERDRIVE_TOKEN` | cloudflare | `hyperdrive-edit` | both Hyperdrive configs (next phase) | + | `CLOUDFLARE_R2_TOKEN` | cloudflare | `r2-data` | the CMS media bucket | + | `CLOUDFLARE_ACCOUNT_ID` | cloudflare | `account-id` | the Cloudflare lanes — a connection fact, not a secret | + | `SUPABASE_ACCESS_TOKEN` | supabase | `management-access` | supabase, db-migrate | + | `SUPABASE_ORG_ID` | supabase | `org-id` | supabase — a connection fact, not a secret | + + Each key keeps its own scope template, and these are six scopes on + purpose: the deploy token deliberately cannot touch Hyperdrive or R2 — + which is also why the CMS deploys with wrangler's resource provisioning + off. A reconcile, not a create: keys + that exist are KEPT, and missing or orphaned keys are minted against the + current ACTIVE connection. None holds a value — a brokered secret is a + pointer at a connection and a scope template, minted just-in-time at + resolve. `CLOUDFLARE_HYPERDRIVE_TOKEN` is minted here although nothing + reads it until the next phase: this is the phase that asks for the + connections, and a key minted with its siblings is one the console card + lists in one place. +3. **place** → **brand** → **lockfile** → **land** — the standard contract + (PR `phase(03-infrastructure): supabase, kv, media bucket`). The PR's terraform plan + lanes resolve the minted keys over remote state; the landing merges only + on green. +4. **converge** — `orun.run/watch@v1` on the merged commit; this is where + the Supabase projects are created. +5. **verify** — `orun.secrets/exists@v1` asserts `WIRING_CLOUDFLARE_KV`, + `WIRING_CLOUDFLARE_R2_CMS`, `SUPABASE_PROJECT_REF`, `SUPABASE_DB_PASSWORD` and `SUPABASE_DB_URL` on + the project's **stage and prod** environments. The shell layer checked + stage only, and a prod apply that failed passed it. A missing key is + named per environment and means that environment's apply did not + publish — read that lane first. + +## The second landing: `03-infrastructure-database` + +### What it lands + +- `infra/terraform/cloudflare-hyperdrive` — a Hyperdrive config per + environment, pooling connections to that environment's Supabase database. + It binds `CLOUDFLARE_HYPERDRIVE_TOKEN` as its `CLOUDFLARE_API_TOKEN`, + because the deploy token cannot touch Hyperdrive, and reads the project + ref and database password from supabase's outputs. +- `infra/terraform/cloudflare-hyperdrive-cms` — the CMS's own Hyperdrive + config per environment, over the same database with **caching off** (an + admin must read its own writes), and the CMS's `PAYLOAD_SECRET`, generated + by terraform so nobody types one. It reads supabase's outputs exactly as + the fleet's config does, which is why it lands here. +- `infra/db-migrate` — the migration runner, applying the schema in + `packages/db/src/migrations` to stage and prod — the fleet's contexts and + schema `cms` (Payload's tables, converted from Payload's own migrations to + idempotent SQL). It plans on the PR and applies after the merge. The CMS + never migrates itself. + +On success the fleet's Hyperdrive publishes `WIRING_CLOUDFLARE_HYPERDRIVE` +and the CMS's publishes `WIRING_CLOUDFLARE_HYPERDRIVE_CMS` and +`CMS_PAYLOAD_SECRET`, to both environment rungs; the workers and the CMS +render their bindings from them. + +### Steps + +1. **requires** — `03-infrastructure` placed, and a `requires.probe`: + `orun.secrets/exists@v1` for `SUPABASE_PROJECT_REF`, + `SUPABASE_DB_PASSWORD` and `SUPABASE_DB_URL` on stage and prod. This is + the question the split exists to ask: do the outputs these lanes read + exist yet? +2. **pre** — the task, filed under the `03-infrastructure` milestone. +3. **place** → **brand** → **lockfile** → **land** — PR + `phase(03-infrastructure): hyperdrive, db-migrate`. Its plan lanes now + resolve supabase's outputs on the PR, so it can be green before it + merges. +4. **converge** — migrations apply and Hyperdrive is created on both + environments. +5. **verify** — `orun.secrets/exists@v1` asserts + `WIRING_CLOUDFLARE_HYPERDRIVE`, `WIRING_CLOUDFLARE_HYPERDRIVE_CMS` and + `CMS_PAYLOAD_SECRET` on stage and prod. `04-workers` asks the + same question, with `WIRING_CLOUDFLARE_KV`, as its own `requires.probe`, + so it will not start on a half-applied phase 03. + +## Failure modes + +Most of these were hit on real Lumen bootstraps; the rest are the +questions the split and the reconcile now ask up front. + +| symptom | meaning → fix | +|---|---| +| `03-infrastructure` waits on connections, then stops | a consent is not granted yet — console → Integrations, then re-run the phase | +| reconcile refused: `parent_grant_insufficient` | the Cloudflare token's permission groups do not cover a template (Hyperdrive Write is the usual gap) — re-issue the token with them, re-connect, re-run the phase | +| supabase lane: `does not support oauth access` on `/billing/addons` | provider ≥ 1.6 sneaked in; from 1.6.0 it reads a billing endpoint Supabase does not serve to OAuth tokens — the root pins `~> 1.5.1`; keep the pin | +| supabase lane: duplicate project name | the organization already has `-`. The same product re-bootstrapping → `adopt.tf` imports it automatically; a stray half-torn-down project → delete it in Supabase | +| kv, hyperdrive or supabase apply: resource already exists (10014 for a KV title, etc.) with empty platform state | `adopt.tf` imports by name at plan time — present in the kv, hyperdrive and supabase roots; if you removed it, restore it | +| `03-infrastructure-database` refuses: `SUPABASE_*` missing on an environment | that environment's supabase apply did not publish — read its lane in `03-infrastructure`'s convergence, fix, re-run `03-infrastructure` | +| db-migrate: missing `SUPABASE_*` secrets | the supabase lane has not applied for that environment — check it first | +| a migration fails | fix forward with a new migration; never edit an applied one | +| secret resolution: `orphaned` | a provider connection was revoked or replaced — changing the Supabase OAuth app's scopes revokes every connection of that app. Re-connect, then re-run `03-infrastructure`; the reconcile re-mints only what is missing | +| secret WRITE fails `not_found` while listings work | the API key's role is below ADMIN (resource-hiding masks the denial) — re-mint the key as admin; the reconcile is idempotent | +| verify: `WIRING_*` or `SUPABASE_*` keys missing | the corresponding terraform lane failed or was skipped — `gh run view` the convergence run, fix, re-run the phase | + +## Re-bootstrapping an EXISTING product + +Adoption makes both landings safe to repeat against resources that already +exist: the Supabase project, the KV namespace and the Hyperdrive config are +imported at plan time rather than colliding. + +One cutover caveat, and it is real: `random_password` cannot be adopted. +When `adopt.tf` imports an existing Supabase project, the first apply +**resets the database password** and republishes it. db-migrate, Hyperdrive +and the worker fleet re-wire from the new secrets in the same convergence, +but anything outside the platform still holding the old credentials breaks +at that moment. + +## Example commands + +From the baseline checkout: + +```bash +orun new --blueprint repo-blueprint.yaml --out $HOME/sourceplane/acme \ + --run-hooks --phase 03-infrastructure \ + --values $HOME/sourceplane/acme/.rebrand/values.json + +orun new --blueprint repo-blueprint.yaml --out $HOME/sourceplane/acme \ + --run-hooks --phase 03-infrastructure-database \ + --values $HOME/sourceplane/acme/.rebrand/values.json +``` + +Headless (fresh container / no checkout — see BOOTSTRAP.md §2): clone the +baseline at a tag and run the same commands, with `ORUN_TOKEN` + +`GITHUB_TOKEN` exported: + +```bash +export ORUN_TOKEN="$(orun auth token | tail -1)" GITHUB_TOKEN=… +git clone --depth 1 --branch https://github.com/sourceplane/lumen-payload +cd lumen-payload +orun new --blueprint repo-blueprint.yaml --out /work/acme \ + --run-hooks --phase 03-infrastructure --values /work/acme.values.yaml +orun new --blueprint repo-blueprint.yaml --out /work/acme \ + --run-hooks --phase 03-infrastructure-database --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, the reconcile keeps every +key, the landing finds nothing new, and the `await` hooks re-assert. + +## Next + +[Phase 04 — workers](04-workers.md). diff --git a/docs/phases/04-workers.md b/docs/phases/04-workers.md new file mode 100644 index 0000000..e3a62e9 --- /dev/null +++ b/docs/phases/04-workers.md @@ -0,0 +1,172 @@ +# Phase 04 — the worker fleet + +Lands the **12-worker fleet** in ONE landing, and one convergence deploys it +on stage and prod with every service binding in place. + +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 + +`apps/`: `policy-worker`, `membership-worker`, `events-worker`, +`projects-worker`, `identity-worker`, `config-worker`, `webhooks-worker`, +`notifications-worker`, `metering-worker`, `admin-worker`, +`billing-worker`, `integrations-worker` — plus their test suites under +`tests/`. + +Each templated worker's deploy renders its committed +`wrangler.template.jsonc` — `@@wiring(/:)@@` tokens — +from the `WIRING_*` secrets phase 03 published — for the fleet, the +Hyperdrive config id from `WIRING_CLOUDFLARE_HYPERDRIVE` (the KV namespace +is api-edge's, in `05-edge`). Resource ids are never committed. Each +worker reads its own runtime keys wire-now-seed-later: declared now, inert +until seeded, and nothing blocks on them. + +The internal workers set `workers_dev: false` — they have no public URL, and +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 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 on a fresh account no order of first deploys works: +something in the loop is always first. + +`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 + +`--out` is the product repo. The blueprint's required inputs — `reponame`, +`productname`, `githuborg` — are validated before any phase +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). + +## 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 + +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 + +- **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)** — 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 + +From the baseline checkout: + +```bash +orun new --blueprint repo-blueprint.yaml --out $HOME/sourceplane/acme \ + --run-hooks --phase 04-workers \ + --values $HOME/sourceplane/acme/.rebrand/values.json +``` + +Headless (fresh container / no checkout — see BOOTSTRAP.md §2): clone the +baseline at a tag and run the same commands, with `ORUN_TOKEN` + +`GITHUB_TOKEN` exported: + +```bash +export ORUN_TOKEN="$(orun auth token | tail -1)" GITHUB_TOKEN=… +git clone --depth 1 --branch https://github.com/sourceplane/lumen-payload +cd lumen-payload +orun new --blueprint repo-blueprint.yaml --out /work/acme \ + --run-hooks --phase 04-workers --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, 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 +a lighter one ([TIMINGS.md](TIMINGS.md)). A convergence that trips resumes +itself; a failed phase run resumes by re-running the same command with its +own `--phase`. + +## Next + +[Phase 05 — edge](05-edge.md). diff --git a/docs/phases/05-edge.md b/docs/phases/05-edge.md new file mode 100644 index 0000000..2d55aa2 --- /dev/null +++ b/docs/phases/05-edge.md @@ -0,0 +1,107 @@ +# Phase 05 — edge + +Lands the **API edge** (`repo-blueprint.yaml`, phase `05-edge`) — the single +public entry point in front of the worker fleet — and proves it live. + +## What it lands + +- `apps/api-edge` (+ its test suite): the gateway worker, with service + bindings to the ten fleet workers it fronts, the idempotency KV binding + (namespace id from `WIRING_CLOUDFLARE_KV`) and the Hyperdrive binding + (config id from `WIRING_CLOUDFLARE_HYPERDRIVE`), rendered per environment + from `wrangler.template.jsonc`. +- `tests/platform-limits` — structural guards on the platform the fleet + deploys under: account limits, the service-binding chain (it pins + api-edge's chain depth), secret scoping. It reads every app and infra + component, so it lands with the edge, the first phase at which the fleet + it describes is whole. + +**A live api-edge on both environments is proof the fleet exists.** +Cloudflare refuses an api-edge deploy while any worker it binds to is +missing, and those workers' own deploys were refused while anything THEY +bind to (policy-worker among them) was missing. The internal workers set +`workers_dev: false`, so this is otherwise unobservable from outside — +which is why this phase, not phase 04, carries the first probe. The one +worker it cannot vouch for is `admin-worker`, which nothing binds to; its +own deploy lane in phase 04 is the evidence for it. + +## Inputs + +`--out` is the product repo. The blueprint's required inputs — `reponame`, +`productname`, `githuborg` — are validated before any phase +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). + +## Steps + +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`). +4. **converge** — `orun.run/watch@v1` on the merged commit. +5. **verify** — an `orun.http/probe@v1` `await` hook probes + `https://-api-edge-{stage,prod}..workers.dev/health` + and fails on any dead endpoint. The URLs are templated from the + blueprint's own inputs. + +## Verify / done means + +`/health` answers 2xx–4xx on BOTH environments. A 4xx is "alive but +unauthorized", which counts as deployed; a 5xx or a timeout does not. + +## Troubleshooting + +- **Deploy lane fails: `Service binding '_WORKER' … not found`** — a + fleet worker never deployed. This is how a partial phase 04 surfaces: the + edge is the deploy that binds most of the fleet at once (it was + `METERING_WORKER` the time it was found). Resume phase 04's failed + convergence (`gh run rerun --failed `), then re-run this phase. +- **`/health` unreachable on both environments after a green deploy** — + check `subdomain` first. It must be the Cloudflare account's workers.dev + subdomain; a wrong one deploys cleanly to URLs nobody can reach, and the + probe is asking the wrong host. +- **`/health` 5xx after a green deploy** — the edge boots but a downstream + binding misbehaves; check the worker it proxies to. The deploy lane's + smoke already retried over route propagation, so this is real, not + propagation. + +## Example commands + +From the baseline checkout: + +```bash +orun new --blueprint repo-blueprint.yaml --out $HOME/sourceplane/acme \ + --run-hooks --phase 05-edge \ + --values $HOME/sourceplane/acme/.rebrand/values.json +``` + +Headless (fresh container / no checkout — see BOOTSTRAP.md §2): clone the +baseline at a tag and run the same command, with `ORUN_TOKEN` + +`GITHUB_TOKEN` exported: + +```bash +export ORUN_TOKEN="$(orun auth token | tail -1)" GITHUB_TOKEN=… +git clone --depth 1 --branch https://github.com/sourceplane/lumen-payload +cd lumen-payload +orun new --blueprint repo-blueprint.yaml --out /work/acme \ + --run-hooks --phase 05-edge --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, the landing finds +nothing new, and the `await` hooks re-probe. + +On success the verify step has already probed +`https://acme-api-edge-{stage,prod}..workers.dev/health`. + +## Next + +[Phase 06 — console](06-console.md). diff --git a/docs/phases/06-console.md b/docs/phases/06-console.md new file mode 100644 index 0000000..b2f18b5 --- /dev/null +++ b/docs/phases/06-console.md @@ -0,0 +1,189 @@ +# Phase 06 — console + +Lands the **console** (`repo-blueprint.yaml`, phase `06-console`), which in +this baseline is **Payload CMS**: the admin, REST and GraphQL on Workers, +signed in with the product's own accounts and holding the account, +organization, notifications, security-activity and billing pages. The +console's URL lands with it as a small redirect Worker into the CMS, and the +custom-domain component lands parked +([below](#the-custom-domain--parked)). It proves the edge, the CMS and the +redirect live on stage and prod. + +## What it lands + +- `apps/cms` (+ `tests/cms`, whose suite runs inside the CMS lane's build): + Payload 3 on Next.js, built with OpenNext and deployed as + `-cms-` in its own lane per environment. It binds what the + data plane published — its cache-disabled Hyperdrive config + (`cloudflare-hyperdrive-cms`, 03-db), its media bucket + (`cloudflare-r2-cms`, 03), its generated `PAYLOAD_SECRET` — and reaches + `api-edge` (05) over a service binding to check sessions. Its schema, + `cms`, was applied by `db-migrate` in 03-db; the CMS never migrates + itself. The CMS build is the heaviest lane in the product: measured at + 6–7 minutes from merge to both environments deployed + ([TIMINGS](TIMINGS.md)), which is why this phase's convergence watch waits + up to 45 minutes. +- `apps/web-console-next` (+ its suite): the console's URL, kept so links + and bookmarks work. Every path answers **308** with its place in the same + environment's CMS (`/login` → `/admin/login`, `/auth/callback` → the CMS's + sign-in callback, …), and nothing else runs there. It `dependsOn` the CMS, + so one convergence deploys the CMS first. +- `infra/terraform/cloudflare-domain`, parked. + +`testing/phases.test.sh` holds the set. + +## The first admin is the owner's + +The admin opens to **nobody** until the owner says so. Signing in with an +account works from the first deploy, but a person with no role is +*pending*; the first admin is made with a setup token the owner chooses +and gives the CMS as the workspace secret `CMS_SETUP_TOKEN` (per environment +or on the shared rung), deploys the CMS once so the Worker has it, visits +`/setup?token=…` and signs in — the account that signs in with that cookie +while no admin exists becomes the admin. The secret can be deleted after. +Every later person is given a role from inside the admin. The +product's `apps/cms/docs/runbook.md` ("Open the admin (first admin)") is the +step. A bootstrap does not do it — it would mean a build holding an admin's +credential — so this phase's probes check `/health`, not a signed-in page. + +## The custom domain — parked + +`infra/terraform/cloudflare-domain` — the zone lookup and, once wired, a +custom domain per environment for the CMS +(`CONSOLE_CUSTOM_DOMAIN` in the product's `intent.yaml`: +`stage.` and `prod.` after rebrand, empty for +`dev` — and, since the console asks for no domain, `` is the +placeholder `.example.com` until an owner sets one) — lands with +the console and **deploys nothing**, for two reasons that live in the +component rather than in the phase: + +1. **It ships parked.** Its `component.yaml` declares + `subscribe.environments: []`, so CI plans no lanes for it. The product + runs on workers.dev URLs until an owner wires it. +2. **The attachment is fenced off.** The component is midway through a + two-step migration to Cloudflare provider v5: the v4 + `cloudflare_workers_domain` resource was dropped from state and its block + is commented out until the v5 `cloudflare_workers_custom_domain` replaces + it. Un-parked as it stands, the root would look up the zone and attach + nothing. + +It used to land on its own as the optional `07-domain` phase, behind a +`domain` input. That landing deployed nothing either — its convergence was a +green run with nothing in it — so the phase and the switch are gone, and +this phase's task contract leaves the component out of `affects`: there is +nothing in it to re-plan. + +Wiring it is a normal pull request in the product, once the zone exists. +The product's `ai/context/operations.md` ("Setting the domain later") carries +the whole list for its owner: replace the placeholder everywhere it stands +(`git grep -l .example.com` — intent, the edge and identity console +origins, the mail sender, the billing return URLs), then: + +1. **The zone first.** The product zone (e.g. `acme.dev`) must already exist + in the Cloudflare account the product deploys into, created in the + dashboard; zone creation is an account-plan operation the platform does + not broker. The component runs with `zoneMode: existing`: it looks the + zone up by `baseDomain` and manages records and custom domains IN it, not + the zone itself. Without the zone a plan fails with `no zone found` (or + the brokered token's account is not the zone's). +2. **Finish the v5 resource and restore the `subscribe` block** the + component carries commented out — both are described in its own comments, + and its `README.md` says where the migration stands. +3. **Land it.** The convergence on `main` applies it; check the product + resolves on its own domain (DNS propagation applies), then re-run + [`08-docs`](08-docs.md) so the deployment manifest records the + custom-domain URLs. + +## Inputs + +`--out` is the product repo. The blueprint's required inputs — `reponame`, +`productname`, `githuborg` — are validated before any phase +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). + +## Steps + +1. **requires** — `05-edge` placed. +2. **pre** — the phase's task. +3. **place** → **brand** → **lockfile** → **land** — the standard contract + (PR `phase(06-console): the CMS console`). +4. **converge** — `orun.run/watch@v1` on the merged commit. +5. **verify** — two `orun.http/probe@v1` `await` hooks: the edge's and the + CMS's `/health` on stage and prod (200), then the console URL on stage and + prod (**308** — the probe does not follow redirects, so a 200 there would + mean the old console came back). + +## Verify / done means + +Six URLs answer as designed: +`https://-api-edge-{stage,prod}..workers.dev/health` and +`https://-cms-{stage,prod}..workers.dev/health` with 200, +and `https://-web-console-next-{stage,prod}..workers.dev` +with 308. The CMS's `/health` is a real round trip — Payload starts with its +secret and counts `users` through its Hyperdrive config in schema `cms` — so +a 200 means it can serve, not merely that a Worker answered. **This is the +"working baseline" moment**: after this phase the product is live end to +end, waiting only for its owner to open the admin. + +## Troubleshooting + +- **`/health` answers 503 `{"secret":"missing"}`** — the CMS deployed before + its `PAYLOAD_SECRET` was pushed. The deploy lane's `secrets-live` step + pushes it right after the first deploy; a 503 that persists means + `CMS_PAYLOAD_SECRET` is not published for that environment — re-run + `03-infrastructure-database`, whose verify names it. +- **`/health` answers 503 `{"db":…}`** — Payload started and could not reach + schema `cms`: either `db-migrate` has not applied 200 and the CMS's later + migrations, or the Hyperdrive config is wrong. The CMS runbook's "Common + failures" has the checks. +- **The deploy fails with `Authentication error [code: 10000]` on + `/r2/buckets/…`** — wrangler tried to provision the R2 bucket with the + deploy token, which has no R2 permission. The component sets + `skipResourceProvisioning: true` (stack-tectonic 0.21.0 or later); a pinned + catalog older than that does not know the setting. +- **The console URL answers 200 or 404 instead of 308** — the redirect only + serves its own `-web-console-next-` hosts. A 404 on that + host means the Worker deployed under another name; check the rebrand + renamed `CMS_WORKER_PREFIX` and the host pattern in its `src/worker.ts`. +- **The convergence needs its resumes** — the CMS lane is long, and a lane + that dies before its build is resumed by the watch. Resumes spent here are + not a regression by themselves. + +## Example commands + +From the baseline checkout: + +```bash +orun new --blueprint repo-blueprint.yaml --out $HOME/sourceplane/acme \ + --run-hooks --phase 06-console \ + --values $HOME/sourceplane/acme/.rebrand/values.json +``` + +Headless (fresh container / no checkout — see BOOTSTRAP.md §2): clone the +baseline at a tag and run the same command, with `ORUN_TOKEN` + +`GITHUB_TOKEN` exported: + +```bash +export ORUN_TOKEN="$(orun auth token | tail -1)" GITHUB_TOKEN=… +git clone --depth 1 --branch https://github.com/sourceplane/lumen-payload +cd lumen-payload +orun new --blueprint repo-blueprint.yaml --out /work/acme \ + --run-hooks --phase 06-console --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, the landing finds +nothing new, and the `await` hooks re-probe. + +## Next + +[Phase 08 — docs](08-docs.md) records what was built. The owner opens the +admin ([above](#the-first-admin-is-the-owners)); the custom domain is wired +later, in an ordinary PR ([above](#the-custom-domain--parked)). + +Post-baseline: seed runtime worker secrets (`orun secrets set --org + --env `; wire-now-seed-later, nothing blocks on them) and ship +normal PRs. diff --git a/docs/phases/08-docs.md b/docs/phases/08-docs.md new file mode 100644 index 0000000..1561ea5 --- /dev/null +++ b/docs/phases/08-docs.md @@ -0,0 +1,128 @@ +# Phase 08 — docs (record the live deployment) + +Turns the freshly-live baseline into **documented, agent-readable state**: +renders the product's deployment manifest from PROBED facts rather than from +what the blueprint intended, and lands it on `main`. After this phase a +human — or an agent reading the repo through the Orun MCP surface — can +answer "what is deployed, where, and how do I operate it" from the +repository alone. + +It places no modules. `ai/context/deployment.md` and +`ai/context/operations.md` were placed by `01-scaffold`; this phase's work +is a hook that rewrites them, a landing, and a probe. + +## What it writes (in the product repo) + +| file | content | +|---|---| +| `ai/context/deployment.md` | REGENERATED manifest: live URLs with probe results, workspace identity (id and slug), secrets inventory **by name only** per rung, integration statuses, the CI lane pin | +| `ai/context/operations.md` | the standing operating contract (architecture, tenancy resolution, deploy pipeline, secrets model, verification, troubleshooting). Healed from the baseline's copy when the product predates it; never rewritten after that | +| `README.md` | the section between `` / `` markers is replaced (the section is inserted after the title for READMEs that predate the markers) | + +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. +2. **pre** — the phase's task. +3. **render** — a `post` hook runs `hooks/render-deployment-docs.sh . + ` from the baseline checkout. It reads identity from + `.rebrand/values.json`, probes the six public URLs — the edge's and the + CMS's `/health`, and the console URL, reported as the redirect into the + CMS only when it answers 308 (and, when that file + records a domain, `api./health` and `app.`, + reported as pending when they do not answer — a product built without a + domain records none, so they are skipped), lists secrets and integrations by name + with `orun secrets list` / `orun integrations list`, and renders the files + above. It refuses to finish if a `TBD_08DOCS` placeholder survives. +4. **land** — `orun.pr/land@v1`: PR `docs(deployment): record live + deployment state`. A docs-only landing plans ZERO deploy lanes, so this + phase has no convergence to watch — it is the one phase whose `await` is + a probe alone. +5. **verify** — two `orun.http/probe@v1` `await` hooks re-probe the six URLs + the manifest claims — four `/health` endpoints for 200, the two console + URLs for 308 — trusting nothing the render step said about them. + It is `quiet`: the addresses are already on the build page from + 06-console's probe, so it files no second set of them (orun ≥ the + saas-build-panel BV3 release; older orun ignores the key), and its own + line still speaks. + +## When to run (and re-run) + +- Right after [phase 06](06-console.md) — the "working baseline" moment — + to record it. +- Again once the custom domain is wired (see + [06-console](06-console.md#the-custom-domain--parked)) and actually + resolves, so the manifest picks up the custom-domain URLs. +- Any time later as a **live-state refresh**: the manifest is regenerated + from scratch on every run and carries its own render timestamp. The + product's `ai/context/operations.md` carries the same command for its own + operators. + +## Inputs + +`--out` is the product repo. The blueprint's required inputs — `reponame`, +`productname`, `githuborg` — are validated before any phase +runs, so pass them on every invocation; the product's own +`.rebrand/values.json` is a complete values file. The renderer also takes +`orunWorkspace`, which that file records. See +[the phases README](README.md#inputs). + +## Example commands + +From the baseline checkout: + +```bash +orun new --blueprint repo-blueprint.yaml --out $HOME/sourceplane/acme \ + --run-hooks --phase 08-docs \ + --values $HOME/sourceplane/acme/.rebrand/values.json +``` + +Headless (fresh container / no checkout — see BOOTSTRAP.md §2): clone the +baseline at a tag and run the same command, with `ORUN_TOKEN` + +`GITHUB_TOKEN` exported: + +```bash +export ORUN_TOKEN="$(orun auth token | tail -1)" GITHUB_TOKEN=… +git clone --depth 1 --branch https://github.com/sourceplane/lumen-payload +cd lumen-payload +orun new --blueprint repo-blueprint.yaml --out /work/acme \ + --run-hooks --phase 08-docs --values /work/acme.values.yaml +``` + +Without `--run-hooks` this phase does nothing at all: it places no files, +and the render, the landing and the probe are all hooks. The renderer is +also safe to run by hand against a product checkout (`bash +hooks/render-deployment-docs.sh `): it +rewrites the three files in that tree and lands nothing, so `git diff` +there shows what the phase would land. + +## Troubleshooting + +- **verify fails on a URL** — the manifest is honest: something the docs + would claim live is not. Re-run phase 05's or 06's verify to localize it. +- **secrets/integrations listed as "unavailable to this credential"** — the + runner's token cannot list that rung; the manifest still renders (URLs and + identity are the load-bearing parts). Re-run with a fuller-scoped + credential to enrich it. +- **`placeholder tokens remain`** — a `TBD_08DOCS` survived the render in + `ai/context/` or `README.md`; the message lists where. The render refuses + rather than landing a half-filled manifest. +- **The workspace slug shows as `?`** — `orun workspace ` could not be + read with this credential. Cosmetic; the id is still recorded. diff --git a/docs/phases/README.md b/docs/phases/README.md new file mode 100644 index 0000000..2880369 --- /dev/null +++ b/docs/phases/README.md @@ -0,0 +1,294 @@ +# The phases — one blueprint, nine selections + +`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 +the others and no per-phase workflow file: a phase is a selection on one +artifact, which is what makes running one alone, months later, from a fresh +container the same operation as running them all. + +Each phase follows the same contract: + +> **place its modules → brand them → land them as a pull request that must go +> green before it merges → watch the convergence the merge starts +> (auto-resumed) → verify the outcome is actually there.** + +Run from the baseline checkout (the blueprint's only source is `path: .`); +the product repo is wherever `--out` points. + +## Execution order + +The phase number is the EXECUTION order — the root scaffold must exist +before anything else can build or deploy, the database must exist before +anything can read it, and a worker cannot bind to a Hyperdrive config that +has not been created. Each phase's `requires.phases` states this in the +document, and the engine refuses a phase whose predecessor is not placed, +naming it. + +Every phase lands as a pull request that is verified, then merged: each +landing waits for its PR's whole CI run to finish green (the product's PR +runs carry remote state, so lanes that need secrets resolve them on the PR +too), and the convergence after the merge is still watched, because +deploying is what a merge does and a PR cannot. + +| phase | milestone | lands | verified by | +|---|---|---|---| +| [`01-scaffold`](01-scaffold.md) | 01-scaffold | **GitHub repo created** + repo born: intent, CI, tooling, identity | repo pushed + `orun cloud check` | +| [`02-foundation`](02-foundation.md) | 02-foundation | 13 shared packages | convergence green | +| [`03-infrastructure`](03-infrastructure.md) | 03-infrastructure | `supabase`, `cloudflare-kv`, `cloudflare-r2-cms` | `WIRING_CLOUDFLARE_KV` + `WIRING_CLOUDFLARE_R2_CMS` + `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`, `cloudflare-hyperdrive-cms`, `db-migrate` | `WIRING_CLOUDFLARE_HYPERDRIVE` + `WIRING_CLOUDFLARE_HYPERDRIVE_CMS` + `CMS_PAYLOAD_SECRET` published on stage and prod | +| [`04-workers`](04-workers.md) | 04-workers | the 12-worker fleet, two feedback bindings stripped | 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 | the Payload CMS (the console) and its suite, the console URL's redirect into it, and the custom-domain component (parked until a zone is wired) | edge and CMS `/health` 200, console URL 308, 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 | + +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 +was the optional `07-domain` phase lands in `06-console`, parked, and an +owner wires it later in an ordinary PR (see +[06-console](06-console.md#the-custom-domain--parked)). + +One requirement looks odd and is deliberate: + +- **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. + Order in the document is what sequences a run; `requires` is the gate + that catches a phase run against a tree where its predecessor never + happened. `testing/phases.test.sh` refuses a requirement on a hook-only + phase. + +## Inputs + +The keys are the console card's (`blueprint.yaml`), lowercase, so what an +operator types in the console form and what the blueprint declares are the +same words. + +| input | required | notes | +|---|---|---| +| `reponame` | yes | lowercase slug (`^[a-z][a-z0-9-]*$`); the repo becomes `/`, and it prefixes the Supabase projects and every worker. The console fills it from the chosen repository | +| `productname` | yes | display name | +| `productdomain` | — | NOT ASKED, default empty. The product goes live on workers.dev; empty brands the reserved placeholder `.example.com` wherever the domain goes (intent's `BASE_DOMAIN` / `CONSOLE_CUSTOM_DOMAIN`, the edge and identity console origins, the mail sender, the billing return URLs), for an owner to replace later (the product's `ai/context/operations.md`, "Setting the domain later"). Pass it only for a product that already has its domain | +| `githuborg` | yes | the org or user the repo lives under. The console fills it from the chosen repository's owner | +| `subdomain` | — | workers.dev subdomain of the Cloudflare **account** you deploy into. A console or `--from bst_…` build reads it from the Cloudflare connection; pass it only for a hand-run build. The default is a placeholder; see below | +| `apibaseurl` | — | the CLI default API base. Empty, it is `https://api.` when a domain is given, and otherwise the product's own prod edge on workers.dev, `https://-api-edge-prod..workers.dev`. Not on the card: it was derived from the domain | +| `orunWorkspace` | — | workspace id. Unset, it is the workspace the build runs in (`from: workspace`, ORUN_WORKSPACE, which a console build always has); with none anywhere, 01 writes the placeholder `ws_SET_ME`, which fails loudly rather than silently cross-tenanting | +| `epicSlug` | — | default `infra-baselining`; the epic every phase files its task under, found by slug so a fresh run and a resumed run find the same work | +| `repoPrivate` | — | default `true`; applied only when `01-scaffold` creates the repo — an existing repo keeps its visibility | +| `pascalName`, `brandSlug`, `cliBin`, `salesEmail` | — | rebrand overrides. Empty, the first three derive from the names above (`brandSlug`, the worker prefix, from `reponame`); an empty `salesEmail` keeps the baseline mailbox | + +**`subdomain` is not the product name.** Every generated URL and the +api-edge CORS allowlist derive from it, so a wrong value ships a product +that deploys cleanly and is unreachable at every address it advertises — +and the `/health` probes of 05, 06 and 08 fail against hosts that were never +going to exist. Find it under Workers & Pages in the Cloudflare dashboard. +A build started from the console, or with `orun baseline new --from bst_…`, +never asks for it: `blueprint.yaml` declares +`from: connection.cloudflare.workersSubdomain`, so the platform reads it from +the workspace's Cloudflare connection, the same one the deploy tokens mint +from. Only a hand-run build passes it. + +`01-scaffold` writes the answers into the product as +`.rebrand/values.json`, which is committed. Every later phase's rebrand hook +reads it, and it carries `githuborg` and `epicSlug` too, so a phase +run months later in a fresh container can recover what the operator +answered (orun's own record, `.orun/provenance.lock`, is gitignored and does +not survive a container). The blueprint's **required** inputs are still +validated before any phase runs, so they must be supplied on every +invocation, single-phase ones included. The file uses the blueprint's own +input keys, so the simplest values file for a later phase is that file: + +```bash +orun new --blueprint repo-blueprint.yaml \ + --out $HOME/sourceplane/acme --run-hooks --phase 03-infrastructure \ + --values $HOME/sourceplane/acme/.rebrand/values.json +``` + +Drop `--run-hooks` (or use `--status`) to preview. Without it a phase places +files and stops: no repo, no landing, no convergence watch, and no probe — +which is exactly what makes a dry instantiation of this baseline possible in +CI with no workspace and no provider (`testing/placement.test.sh` does this). + +## Headless / container mode + +A fresh container with two env tokens is the entire contract (see +[BOOTSTRAP.md §2](../../BOOTSTRAP.md#2-headless--container-mode-daytona-ci-any-sandbox)). +Clone the baseline at a tag and the tag pins everything: the blueprint, its +modules, and the scripts its hooks run all come from that one commit, and +orun pins the checkout by digest into its object store before any module is +read. + +```bash +export ORUN_TOKEN=… GITHUB_TOKEN=… +git clone --depth 1 --branch https://github.com/sourceplane/lumen-payload +cd lumen-payload +orun new --blueprint repo-blueprint.yaml --out /work/acme --run-hooks \ + --phase 03-infrastructure --values /work/acme.values.yaml +``` + +Inside a baseline checkout the same command uses the local tree: the two +modes are the same files. + +## Unattended: `--resume` + +`--resume` places every phase not already derived as done, in dependency +order, honouring each barrier. **18 measured 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 +(5–7m) is the longest single wait and cannot be engineered away from our +side. Where each number comes from, and which are estimates: +[TIMINGS.md](TIMINGS.md). + +Why it can run unattended: + +- **Idempotence, everywhere.** Landings and the convergence watch fall back + to plain REST when `gh` is degraded, smokes retry route propagation, + and `orun.run/watch@v1` resumes failed lanes up to three times. A phase + that failed partway resumes by being re-run. +- **Waits are declared, not slept.** `01-scaffold` waits for a GitHub + connection to the account that will own the repo; `03-infrastructure` + waits up to 10 minutes for the GitHub, Cloudflare and Supabase consents; + `03-infrastructure-database` will not start until supabase's outputs are + published; `04-workers` will not start until both `WIRING_*` keys are. A + consent nobody has clicked is a *wait*, not a failure. +- **Verification is the phase's own last act.** `await` hooks re-list the + published secrets on both environments and re-probe the live endpoints, + trusting no earlier step's word. + +## Pacing, idempotence, resume + +- Run one phase today and the next whenever. Nothing expires between + phases; each phase re-asks its own preconditions. +- **Phase state is derived from the tree, never stored.** Nothing in + `--out` records which phases have run. A stored file would be a cache, + and it must always be safe to delete. +- A phase whose files are all present but differ from the blueprint derives + as **`drifted`** — which is every phase once `01-scaffold` brands the + tree. Drift SATISFIES a successor's requirement (the files are all + there), and `--resume` leaves a drifted phase placed rather than + reverting your product's identity to `lumen-payload`. Re-place one deliberately + with `--phase `. +- `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 + the push. If a convergence is still red after the watch has spent its + resume budget, the content is already on `main`, so re-running the phase + lands nothing new and no push will redeploy what the failed run left + undeployed. Resume the failed run itself — `gh run rerun --failed + ` is a true resume (the exec-id is the run id and every lane + passes `--retry`) — then re-run the phase so its `await` hooks verify. + This is not hypothetical: a Lumen product bootstrapped before the shell + layer learned it took three full restarts and never deployed six of its + twelve workers — it surfaced only when api-edge's deploy failed on a + service binding to a worker that did not exist. + +## Prerequisites (once) + +1. `orun auth login --device` (approve at app.orun.dev/cli/device), or an + `ORUN_TOKEN` for a headless run. +2. A workspace for the product; note its `ws_…` id. +3. Three integrations connected in that workspace: + - **GitHub** — the App installation on `githuborg`. `01-scaffold` checks + the connection is to the account that will own the repo and waits for + it: the platform sees a product's pull requests only through that + installation. + - **Cloudflare** — the Account API token, pasted through the console's + Connect recipe. + - **Supabase** — the OAuth consent (or a personal access token), bound to + the organization that will own `-stage` and `-prod`. + + `03-infrastructure` polls for all three for up to 10 minutes, so the + consents can be clicked while it waits. Details, including what each + token must be able to mint: [03-infrastructure.md](03-infrastructure.md). +4. An **admin-role** API key. The first credential WRITE is + `03-infrastructure`'s secret reconcile, so a builder/viewer key gets + through `01-scaffold` and `02-foundation` and stops at phase three with + the re-mint-as-admin hint. The shell layer probed this at minute two; + the blueprint does not declare an early write-probe yet. +5. The repo allow-listed in the workspace (console → Settings → Git repos) + when the credential cannot link it itself — a workspace-scoped key + cannot. `01-scaffold`'s `link` hook tries `orun cloud link`, then gates + on `orun cloud check`, and stops naming exactly this step if the check + fails. + +## The mechanism, as typed actions + +Everything the phases do that is not placing files is a **typed action** — +a closed registry inside the orun binary, not a script this repo ships: + +| action | role | +|---|---| +| `orun.task/ensure@v1` | the phase's task in the workspace's task plane: find-or-create by identity under `epicSlug`, contract attached from `tasks/.TaskContract.yaml`. `01-scaffold` also ensures the epic itself | +| `orun.repo/ensure@v1` | create the product repo under `githuborg` if it does not exist (`private: repoPrivate`); a pre-created repo is found and used | +| `orun.pr/land@v1` | commit → `orun/-` branch → PR → wait for the PR's whole CI run (30 minutes by default; 60 for `04-workers`, 45 for `06-console`) → merge → back on `main`, through the provenance pen so the landing binds to the phase's task | +| `orun.run/watch@v1` | watch the run for the commit the landing merged (`sha:`), resuming it through transient failures (`resumeBudget: 3`, 2 for the restore) | +| `orun.doctor/check@v1` | the provider-consent wait — a precondition, not a preamble. With `githubOwner` it also checks the GitHub connection is to the account that owns the repo | +| `orun.secrets/exists@v1` | assert the keys a later phase reads are published, on the project's stage and prod environments | +| `orun.integrations/reconcile@v1` | bring the five brokered provider secrets to their declared state: keys that exist are KEPT, keys that are missing are minted against the ACTIVE connection. It never holds a value — a brokered secret is a pointer at a connection and a scope template | +| `orun.http/probe@v1` | probe the live `/health` and console URLs | + +The `run:` hooks that remain are this baseline's own business rather than a +verb any bootstrap needs, and each resolves the baseline checkout as +`{{ .baseline.dir }}`, so a pinned clone pins them too: + +- `git init` / `git add -A` — `tooling/rebrand/rebrand.mjs` enumerates the + tree with `git ls-files`, so every phase stages before it brands; +- `rebrand.mjs --values .rebrand/values.json`, then `--verify`, in every + phase that places files — orun writes a phase's files on that phase's + turn, so they arrive speaking `lumen-payload` and are branded before they land; +- `01-scaffold`'s `orun-workspace` rewrite of `intent.yaml`'s `workspace:` + (rebrand treats the state backend as org-owned and leaves it alone) and + 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/deploy/fleet-stubs.mjs`, the pre-deploy that makes one fleet + worker landings; +- `hooks/render-deployment-docs.sh`, `08-docs`'s renderer. + +## Tracking the bootstrap as work (BT) + +`01-scaffold`'s first `pre` hook ensures the epic, by `epicSlug`. Every +phase's `pre` hook then ensures its own task under that epic, with the phase +name as its milestone (the two second landings file under 03 and 04) and the +prefix `BASE`, so its branch reads `orun/BASE--`. A run that +starts fresh and a run that resumes find the same work. The contract +templates live in `tasks/` at the repo root, one per landing, named by the +hooks' `contract:` field. `gates: []` is a declaration: merge alone finishes +the task, because the main convergence is the gate the phase *watches*, not +one the plane observes as a PR check. The templates are baseline machinery, +never product content. The whole design: +`specs/epics/saas-baseline-tracking/`. + +The console previews the same programme from `blueprint.yaml`'s +`programme:` block — the epic and its seven milestones. + +## Why there is one document + +Until BE1 each phase carried a `blueprint.yaml` slice derived by +`tooling/blueprint/split-phases.py`, and the derivation had to PRUNE every +cross-phase `dependsOn` edge, because a slice that names a module in +another slice does not parse. + +The prune is what is really gone. orun's phase overlay enforces the same +barrier by REFUSING a dependency that points forward across it, and a +refusal and a deletion are not the same thing — the splitter was deleting +`supabase`'s `dependsOn: [bootstrap]`, an edge to a module that does not +exist and never has, for as long as it ran. A pruned edge to a module in +no phase looks exactly like a pruned edge to a module in an earlier one. + +The same move changed what phase 03 is. The shell layer placed all four +data-plane modules in one phase and merged it without waiting on the PR, +because two of them could never pass there; the blueprint splits them so +that every phase's PR can be verified before it merges. The reasoning is on +[03-infrastructure.md](03-infrastructure.md). + +`testing/phases.test.sh` holds the partition, the order, the narration and +this folder to each other: every phase has a page here and every page a +phase. diff --git a/docs/phases/TIMINGS.md b/docs/phases/TIMINGS.md new file mode 100644 index 0000000..bef9166 --- /dev/null +++ b/docs/phases/TIMINGS.md @@ -0,0 +1,218 @@ +# Bootstrap timings — what a build takes, and where the number comes from + +## This baseline: 23 minutes, derived + +**No bootstrap of this baseline has been timed end to end.** The 23 the card +declares is built from measured parts, and the page says which part is +which: + +- **Seven of the eight phases are the Lumen baseline's, file for file** — + `01-scaffold`, `02-foundation`, `03-infrastructure`, + `03-infrastructure-database`, `04-workers`, `05-edge`, `08-docs` — and + carry the minutes of Lumen's measured run below (16 of its 18). +- **`06-console` is the one this baseline changes.** Lumen fetches a + prebuilt console and measured 2m29s; this phase BUILDS Payload (Next.js + + OpenNext, about 3.3 MiB compressed) in its own lane per environment. Its + 7 is this repository's own convergences on `main` that built and deployed + the CMS to stage and prod: + + | run | what it deployed | merge → green | + |---|---|---| + | [40631071639](https://github.com/sourceplane/lumen-payload/actions/runs/40631071639) | the CMS's first deploy (PC3) | 7m12s | + | [40766175686](https://github.com/sourceplane/lumen-payload/actions/runs/40766175686) | the CMS, api-edge, identity (PX2) | 7m02s | + | [40768519646](https://github.com/sourceplane/lumen-payload/actions/runs/40768519646) | the CMS (PX3) | 6m37s | + | [40771038240](https://github.com/sourceplane/lumen-payload/actions/runs/40771038240) | the CMS and the console redirect (PX4) | 6m06s | + + Rounded up to 7, since a bootstrap's landing and probes come on top. +- **The CMS's data plane adds no phase time.** `cloudflare-r2-cms` and + `cloudflare-hyperdrive-cms` apply in lanes beside `03-infrastructure`'s and + `03-infrastructure-database`'s, and alone they took 1m30s + ([40643492734](https://github.com/sourceplane/lumen-payload/actions/runs/40643492734), + the bucket) and 2m23s + ([40629481445](https://github.com/sourceplane/lumen-payload/actions/runs/40629481445), + the Hyperdrive config) — inside those phases' measured 2m5s and 3m2s, + since a convergence takes its longest lane, not the sum. + +| phase | declared | from | +|---|---|---| +| `01-scaffold` | 1 | Lumen's run | +| `02-foundation` | 3 | Lumen's run | +| `03-infrastructure` | 2 | Lumen's run (the bucket applies beside it) | +| `03-infrastructure-database` | 3 | Lumen's run (the CMS's Hyperdrive applies beside it) | +| `04-workers` | 4 | Lumen's run | +| `05-edge` | 2 | Lumen's run | +| `06-console` | **7** | this repository's CMS deploys, above | +| `08-docs` | 1 | Lumen's run | +| **total** | **23** | | + +The first real bootstrap of this baseline replaces this section with its own +run, the way Lumen's run replaced Lumen's arithmetic. + +## The Lumen phases, measured + +**This page used to open by admitting that no bootstrap had been measured end +to end.** One has: `pullely/multi-tenant-saas-2` built on 2026-10-26, 13:14 → +13:32 UTC, in **18 minutes**, and every number below is that run's own elapsed +rather than arithmetic on older ones. + +The 45 these replace was honest arithmetic and **2.5x the truth**. Two of its +line items were not just conservative but wrong about the shape of the build, +and the run says which: + +- **"Supabase project creation, 5–7m, is the floor and nobody can shorten + it."** `03-infrastructure`, which creates the Supabase project *and* the KV + namespace per environment and applies Terraform, took **2m5s** in total. The + floor was not where the page thought it was. +- **`04-workers` at 14.** The twelve-worker fleet deployed to both + environments in **3m53s**. The budget carried the memory of two convergences + (a strip and a restore); there is one. + +What the run confirms, as designed: **eight landings and no ninth** (PR #1 +through #8 — `04-workers-restore` is gone), and `06-console` at **2m29s** +rather than the ~13 a cold Next.js build took, which is the fetched console +artifact doing what it was built to do. + +## 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 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. + +**These are measured.** The column on the right is what the run took; the +declared number is that, rounded to the nearest whole minute. `08-docs` +finished inside the minute it started, and the card's reader requires a +positive number, so it declares 1. + +| phase | budgeted | declared | measured on multi-tenant-saas-2 | +|---|---|---|---| +| `01-scaffold` | 2 | **1** | 1m15s | +| `02-foundation` | 5 | **3** | 2m30s | +| `03-infrastructure` | 8 | **2** | 2m5s | +| `03-infrastructure-database` | 5 | **3** | 3m2s | +| `04-workers` | 14 | **4** | 3m53s | +| `05-edge` | 4 | **2** | 2m21s | +| `06-console` | 5 | **2** | 2m29s | +| `08-docs` | 2 | **1** | under a minute | +| **total** | **45** | **18** | **18m wall clock** (17m35s of phases) | + +**ONE RUN IS ONE SAMPLE**, and this page should not be read as a promise. What +makes it worth declaring anyway: it was a *fresh* account — no Supabase +project, no KV namespace, no Cloudflare worker, nothing cached — which is the +slow case rather than the fast one. What could still make a build slower than +18: Supabase or Cloudflare having a bad day, a GitHub Actions queue, and the +one condition on `06-console` below. A second measured run belongs on this +page beside the first rather than replacing it. + +**One condition on `06-console`'s 2.** The console is fetched only when the +baseline tag being built from has a published artifact for exactly these +sources — `.github/workflows/tag.yml` publishes one as part of cutting a tag. +Without one, or when a product's console sources have changed, the pin is +absent or stale and the component builds from source: the phase is then its +old ~13 again, and nothing fails. 2 is the tagged case, which is every build +a product actually makes, and the measured run is one of them. + +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 + +1. **Every landing waits for its PR, and that is deliberate.** The flows + went the other way — `--no-wait` on phases 02–06, one convergence per + landing, because PR lanes then deployed the fleet a second time (and, + for 04's restore, a third). That is most of the drop from vela's 04 to + ambient's. Waiting came back once PR lanes stopped deploying and phase 03 + was split so its PRs could pass — the split the old version of this page + proposed as the "check-friendly alternative" to `--no-wait`. +2. **Supabase project creation (5–7m) is irreducible** from our side — + budget for it; nothing to engineer around short of pre-provisioning + projects. +3. **Watch GitHub Actions billing.** A full bootstrap is hundreds of runner + minutes. A tripped spending limit presents as lanes that "fail" with NO + logs anywhere — the message lives only in the check-run ANNOTATIONS + (`gh api repos///check-runs//annotations`). +4. **A session token will not outlive the run.** `orun auth token` mints a + short-lived one (~30m); a full `--resume` is longer. Use the workspace's + admin-role API key as `ORUN_TOKEN`, mint a session token per phase, or — + as the platform's own runner does — point `ORUN_TOKEN_FILE` at a file + something keeps fresh: the CLI re-reads it on every call and prefers it + over `ORUN_TOKEN`. +5. **A convergence that follows a commit touching NO components** plans zero + lanes and reads "green". The phase's verify hook is the real gate; never + trust a green run without one. (It is why the parked custom-domain + component no longer has a landing of its own: as `07-domain` it was + exactly this case. It lands in `06-console` now.) + +## Defect log from the measured runs + +Found and fixed during the two measured bootstraps, and listed so nobody +re-hits them. Some fixes lived in the shell layer and went with it; the +right-hand column says where each one lives now. + +| fix | what broke on a fresh product | now | +|---|---|---| +| #50 | `secret://` refs: segment 1 is the WORKSPACE — the repo-slug rebrand rewrote both segments; every resolve failed `Validation failed` | a rebrand rule | +| #52 | `cloud check` passed without the LOCAL link cache (fresh HOME) | `01-scaffold`'s `link` hook runs `orun cloud link` before the check, every time | +| #53 | the workspace-slug self-heal dirtied the tree before its own clean-tree check | shell-layer only; gone with it | +| #54 | later phases branded fresh baseline content with the product's scaffold-era copy of the rebrand tool | every hook runs `{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs`, and no product carries the tool | +| #55 | supabase `adopt.tf` read `SUPABASE_ORG_ID`, but the job env carries `TF_VAR_supabaseOrgId` | `adopt.tf` accepts either | +| #56/#57 | phase 03's PR lanes structurally red on first boot | then: a `--no-wait` landing. Now: the 03 split | + +What the workspace-scoped (`sk_`) token path surfaced on ambient, all fixed +then: + +1. `sk_` tokens see NO memberships list → slug resolution needs + `orun workspace ` (v2.52.1), the direct org read. +2. `sk_` tokens cannot write repo links → the repo must be linked by the + platform or allow-listed in the console; `01-scaffold`'s `link` is best + effort for exactly this reason and `cloud check` is the gate. +3. The intent declares the project SLUG; config-surface and state routes + take `prj_…` ids → CLI-side slug resolution (v2.52.2 secrets, v2.52.4 + run). The product's `ci.yml` lane pin is v2.56.2 today (the phase + overlay's floor was v2.56.0; v2.56.2 is where a branded tree stopped + refusing its next phase). +4. A step `timeout:` did not kill grandchildren — a wedged git held the + step's pipes past its deadline (15m declared, 71m observed) → process- + group kill + WaitDelay (orun v2.52.3). +5. git has NO transfer timeout → the shell layer set + `http.lowSpeedLimit/Time` on every git call. +6. git's credential `store` fires EVERY configured helper (system + osxkeychain included) → in a keychain-less HOME securityd can raise a + BLOCKING dialog on the console user's screen, hanging the step until a + human clicks. The shell layer used a get-only credential helper. + +Items 5 and 6 were guards on the shell layer's own git calls. The network +git work is now orun's (the landing's pen and `orun.repo/ensure@v1`); this +page has not verified that those carry both guards, and a bootstrap that +hangs on a git push or a keychain prompt should be read with them in mind. diff --git a/hooks/render-deployment-docs.sh b/hooks/render-deployment-docs.sh new file mode 100755 index 0000000..ac42933 --- /dev/null +++ b/hooks/render-deployment-docs.sh @@ -0,0 +1,214 @@ +#!/usr/bin/env bash +# Render the product's LIVE-DEPLOYMENT documentation from verified state. +# Called by phase 08-docs as a `run:` hook (and safe to run by hand). +# Idempotent: the +# generated files and the README section are fully re-rendered on every run, +# so re-running after the custom domain is wired or any redeploy refreshes them. +# +# hooks/render-deployment-docs.sh +# +# What it writes (in ): +# ai/context/deployment.md — REGENERATED: the deployment manifest (URLs +# with live probe results, identity, secrets +# inventory BY NAME, integrations, provenance) +# ai/context/operations.md — healed from the baseline template if absent +# (static operator/agent guide; never rewritten) +# README.md — the section between +# markers is replaced (markers appended if the +# README predates them) +# +# No secret VALUE is ever read or written here — inventories are names only. +set -euo pipefail + +out="${1:?usage: render-deployment-docs.sh }" +ws="${2:?usage: render-deployment-docs.sh }" +L="${3:?usage: render-deployment-docs.sh }" + +cd "$out" +vals=".rebrand/values.json" +[ -f "$vals" ] || { echo "render-docs: $vals missing — is this a scaffolded product?" >&2; exit 1; } + +repo="$(python3 -c "import json;print(json.load(open('$vals'))['reponame'])")" +sub="$(python3 -c "import json;print(json.load(open('$vals'))['subdomain'])")" +domain="$(python3 -c "import json;print(json.load(open('$vals')).get('productdomain',''))")" +# A product is built with no domain (the console asks for none): values.json +# records "" and the tree carries the reserved placeholder .example.com +# until an owner sets one. Neither is a domain to probe. +case "$domain" in *.example.com) domain="" ;; esac + +# Workspace slug via the direct backend read (works for user sessions AND +# workspace-scoped ORUN_TOKENs); tolerate failure — slug then shows as "?". +slug="$( { orun workspace "$ws" 2>/dev/null || true; } | sed -n 's/^ *slug: *//p' | head -1)" +[ -n "$slug" ] || slug="?" + +# CI lane pin (what version the deploy lanes run). +lanepin="$(sed -n 's/^ *version: *\(v[0-9.]*\) *$/\1/p' .github/workflows/ci.yml 2>/dev/null | head -1)" +[ -n "$lanepin" ] || lanepin="?" + +# curl emits the -w format even on connection failure (000) — capture, don't +# append, or a failed probe reads "000000". +probe() { local c; c="$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 "$1" 2>/dev/null)" || true; printf '%s' "${c:-000}"; } +badge() { case "$1" in 2*|3*|401|403) echo "LIVE ($1)" ;; 000) echo "unreachable" ;; *) echo "answering $1" ;; esac; } + +edge_stage="https://${repo}-api-edge-stage.${sub}.workers.dev" +edge_prod="https://${repo}-api-edge-prod.${sub}.workers.dev" +con_stage="https://${repo}-web-console-next-stage.${sub}.workers.dev" +con_prod="https://${repo}-web-console-next-prod.${sub}.workers.dev" +cms_stage="https://${repo}-cms-stage.${sub}.workers.dev" +cms_prod="https://${repo}-cms-prod.${sub}.workers.dev" + +p_es="$(probe "$edge_stage/health")"; p_ep="$(probe "$edge_prod/health")" +p_cs="$(probe "$con_stage")"; p_cp="$(probe "$con_prod")" +p_ms="$(probe "$cms_stage/health")"; p_mp="$(probe "$cms_prod/health")" +# The console URL is a redirect into the CMS: 308 is what it is for, and a 200 +# would mean something else answered there. +redirect() { case "$1" in 308) echo "redirects to the CMS (308)" ;; 000) echo "unreachable" ;; *) echo "answering $1, not the 308 into the CMS" ;; esac; } + +# Custom domain (set later, by an owner): probe only if a domain is recorded; +# an unreachable domain is reported as pending, never a failure. +dom_rows="" +if [ -n "$domain" ]; then + p_da="$(probe "https://api.${domain}/health")" + p_dc="$(probe "https://app.${domain}")" + dom_rows="| edge (custom domain) | https://api.${domain}/health | $( [ "$p_da" = 000 ] && echo 'pending (not wired yet, or DNS propagating)' || badge "$p_da" ) | +| console (custom domain) | https://app.${domain} | $( [ "$p_dc" = 000 ] && echo 'pending (not wired yet, or DNS propagating)' || badge "$p_dc" ) |" +fi + +# Inventories — NAMES/status only, never values. Tolerant: a token that +# cannot list simply yields an "unavailable" note instead of failing docs. +secrets_proj="$( { orun secrets list --org "$ws" --project 2>/dev/null || true; } | awk 'NR>1 && NF {print " - "$1}' )" +secrets_stage="$( { orun secrets list --org "$ws" --env stage 2>/dev/null || true; } | awk 'NR>1 && NF {print " - "$1}' )" +secrets_prod="$( { orun secrets list --org "$ws" --env prod 2>/dev/null || true; } | awk 'NR>1 && NF {print " - "$1}' )" +[ -n "$secrets_proj" ] || secrets_proj=" - (listing unavailable to this credential)" +[ -n "$secrets_stage" ] || secrets_stage=" - (listing unavailable to this credential)" +[ -n "$secrets_prod" ] || secrets_prod=" - (listing unavailable to this credential)" +integrations="$( { orun integrations list --org "$ws" --json 2>/dev/null || true; } | python3 -c " +import json,sys +try: rows=json.load(sys.stdin) +except Exception: rows=[] +out=[f\" - {r.get('provider','?')}: {r.get('status','?')}\" for r in rows] +print('\n'.join(out) if out else ' - (listing unavailable to this credential)')" )" + +now="$(date -u +%Y-%m-%dT%H:%M:%SZ)" + +# Heal the static operator guide from the baseline when the product predates it. +mkdir -p ai/context +if [ ! -f ai/context/operations.md ] && [ -f "$L/ai/context/operations.md" ]; then + cp "$L/ai/context/operations.md" ai/context/operations.md + # The template speaks the source repo's name; the product copy must + # speak the product's, so reuse the rebrand values. (It carried an + # `OPSFLOWS` placeholder that only this heal filled in — the copy every + # product got at 01-scaffold kept the literal `https://github.com/OPSFLOWS`. + # The line names the baseline as `` now, which needs no + # filling: a literal baseline name would itself be rebranded into the + # product's.) + node "$L/tooling/rebrand/rebrand.mjs" --values "$vals" --allow-dirty >/dev/null 2>&1 || true + echo "render-docs: healed ai/context/operations.md" +fi + +cat > ai/context/deployment.md < GENERATED by the docs flow on ${now}; re-run it to refresh (idempotent; +> command in [operations.md](operations.md)). Hand-edits here are +> overwritten. No secret values appear in this file — inventories are +> names only. + +## Identity + +| | | +|---|---| +| product / project slug | \`${repo}\` | +| Orun workspace | \`${ws}\` (slug \`${slug}\`) | +| declared in | \`intent.yaml\` → \`execution.state.workspace\` / \`.project\` | +| CI lane CLI pin | orun \`${lanepin}\` (\`.github/workflows/ci.yml\`) | + +## Public URLs (probed ${now}) + +| surface | URL | status | +|---|---|---| +| edge API (stage) | ${edge_stage}/health | $(badge "$p_es") | +| edge API (prod) | ${edge_prod}/health | $(badge "$p_ep") | +| CMS — the console (stage) | ${cms_stage}/health | $(badge "$p_ms") | +| CMS — the console (prod) | ${cms_prod}/health | $(badge "$p_mp") | +| console URL (stage) | ${con_stage} | $(redirect "$p_cs") | +| console URL (prod) | ${con_prod} | $(redirect "$p_cp") | +${dom_rows} + +A 401/403 on \`/health\` still counts as deployed (alive but unauthorized); +000/5xx does not. The CMS's \`/health\` is a round trip through its own +Hyperdrive config to schema \`cms\`, so LIVE there means it can serve. The \`dev\` environment is verify-only by design — no +deployed URLs. + +## Environments + +- \`stage\` and \`prod\` are fully provisioned (Supabase project, Hyperdrive + for the fleet and for the CMS, idempotency KV, the CMS media bucket, + migrations) and serve the URLs above. +- The CMS admin opens to its first admin only with the owner's setup token + (\`apps/cms/docs/runbook.md\`, "Open the admin"). +- \`dev\` is verify-only: plan/verify lanes run, nothing is deployed. + +## Secrets inventory (names only) + +Project rung: +${secrets_proj} + +Environment \`stage\`: +${secrets_stage} + +Environment \`prod\`: +${secrets_prod} + +Provider secrets are BROKERED (minted per-run from the workspace's +integration connections; no long-lived values at rest). \`WIRING_*\` and +\`SUPABASE_*\` env-rung entries are job-output secrets published by the +infrastructure terraform — deploy lanes resolve them for worker bindings. + +## Workspace integrations + +${integrations} + +## How this deployment changes + +Merges to \`main\` converge automatically: CI plans changed components and +runs each lane via \`orun run --remote-state\` against the workspace above. +See [operations.md](operations.md) for the full operating contract +(convergence, resumes, secrets, verification, troubleshooting). +EOF +echo "render-docs: wrote ai/context/deployment.md" + +# README section between markers (append the section if the README predates it). +python3 - "$repo" <<'PY' +import re, sys +repo = sys.argv[1] +begin, end = "", "" +body = f"""{begin} +This product is **live**. Verified URLs, identity, and the secrets +inventory are recorded in +[ai/context/deployment.md](ai/context/deployment.md) (regenerated by the +docs flow — command in the operating contract); how it deploys and how to +operate it: [ai/context/operations.md](ai/context/operations.md). +{end}""" +s = open("README.md").read() +if begin in s and end in s: + s = re.sub(re.escape(begin) + r".*?" + re.escape(end), body, s, count=1, flags=re.S) +else: + # READMEs that predate the markers get the section right after the title. + lines = s.splitlines(keepends=True) + insert_at = 1 + while insert_at < len(lines) and lines[insert_at].strip() == "": + insert_at += 1 + section = f"\n## Live deployment\n\n{body}\n" + lines.insert(insert_at, section) + s = "".join(lines) +open("README.md", "w").write(s) +print("render-docs: README live-deployment section rendered") +PY + +# The contract for verify: no placeholder tokens survive a render. +if grep -rn "TBD_08DOCS" ai/context README.md 2>/dev/null | grep -v Binary; then + echo "render-docs: placeholder tokens remain (above)" >&2 + exit 1 +fi +echo "render-docs: done" diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml new file mode 100644 index 0000000..0746b18 --- /dev/null +++ b/repo-blueprint.yaml @@ -0,0 +1,2068 @@ +apiVersion: orun.dev/v1 +kind: Blueprint +metadata: + name: lumen-payload-baseline + description: >- + lumen-payload as a Blueprint of itself — instantiate a new Cloudflare + + Supabase multi-tenant SaaS whose console is Payload CMS: the twelve-worker + fleet and API edge it shares with the Lumen baseline, plus Payload on + Workers with its own Hyperdrive path, an R2 media bucket and sign-in with + the product's own accounts. The dependsOn edges below are orun's DAG; the + rename map is tooling/rebrand/rebrand.mjs, applied by every phase's + `rebrand` hook from the templated .rebrand/values.json. See BOOTSTRAP.md for + the steps no script can perform (connections, the first CMS admin, a + domain). + +# ── INPUTS ──────────────────────────────────────────────────────────────── +# The instance-identity contract, transcribed from tooling/rebrand/rebrand.mjs. +# These feed the templated .rebrand/values.json that the `rebrand` hook applies +# across the copied tree. Org-owned identity (GitHub org `sourceplane`, the orun +# state backend, `sourceplane.io` apiVersion, company mailboxes) is intentionally +# NOT an input — rebrand.mjs protects it. +# +# THE KEYS ARE THE MANIFEST'S. They were camelCase here (`repoName`, +# `productName`, `productDomain`, `apiBaseUrl`, `workersDevSubdomain`) while +# `blueprint.yaml` — the card the console renders and the platform hands to +# the build — spells them `reponame`, `productname`, `productdomain`, +# `apibaseurl`, `subdomain`. A console build sent the card's keys to a +# blueprint that did not declare them, and `orun new` answered +# `input "repoName" is required` before placing a file. One spelling, the +# card's, because the card is what the platform actually sends. +inputs: + reponame: + type: string + pattern: "^[a-z][a-z0-9-]*$" + required: true + description: Repo slug (e.g. acme-cloud) — intent metadata.name, Supabase/Hyperdrive project names, worker resource prefixes. + productname: + type: string + required: true + description: Human display name (e.g. "Acme Cloud"). + productdomain: + type: string + default: "" + description: >- + The product's own domain, once it has one (e.g. acme.dev). NOT ASKED: + the product answers on workers.dev from its first deploy, and a domain + is an owner's step after it. Empty, the rebrand writes the reserved + placeholder `.example.com` wherever the domain goes — + intent.yaml's BASE_DOMAIN and CONSOLE_CUSTOM_DOMAIN (the parked + cloudflare-domain's parameters), the api-edge CORS and identity-worker + OAuth console origins (both also allow the workers.dev console, so + sign-in works without it), the notifications sender and the billing + success URLs — so setting it later is replacing that one string; the + product's ai/context/operations.md, "Setting the domain later", says + how. Pass it with --set only to brand a hand-run build with a domain it + already has. + pascalName: + type: string + default: "" + description: SDK class identifier (default derived from productname by rebrand.mjs). + brandSlug: + type: string + default: "" + description: Cloudflare worker resource prefix (default reponame). + cliBin: + type: string + default: "" + description: CLI binary name + env-var prefix source (default reponame). + apibaseurl: + type: string + default: "" + description: >- + CLI default API base. Empty, the rebrand derives it: with a + `productdomain`, https://api.; with none (the console + asks for none), the product's own prod edge on workers.dev, + https://-api-edge-prod..workers.dev, which is + live from the first deploy. + subdomain: + type: string + default: "your-workers-subdomain" + description: >- + workers.dev subdomain for app-config seams. A console or `--from bst_…` + build gets it from the workspace's Cloudflare connection (blueprint.yaml + declares `from: connection.cloudflare.workersSubdomain`); pass it with + --set only for a hand-run build. + salesEmail: + type: string + default: "" + description: Optional sales mailbox retarget; empty keeps the baseline mailbox. + orunWorkspace: + type: string + default: "" + # Unset, it is the workspace the build runs in (ORUN_WORKSPACE — which a + # console build's sandbox always sets, and which the console form cannot + # send). A value set on the command line or recorded by the tree wins. + from: workspace + description: >- + Orun Cloud workspace ID (ws_…, org_… or slug) for this instance's remote + state. rebrand.mjs treats the orun state backend as org-owned and leaves + it alone, so without this the fork inherits the BASELINE's workspace and + its CI would claim another tenant's workspace. Unset, it is the workspace + the build runs in; with none anywhere, the scaffold writes a placeholder + that fails loudly rather than silently cross-tenanting. + # ── The facts the phases below need and the flows used to hold. They were + # workflow inputs (`githuborg`, `epicslug` — and `domain`, gone since the + # custom-domain component lands with the console, parked — on the flows' + # per-phase workflow.yaml), which made them invisible to anything reading + # this file — including the console that has to render a form. + githuborg: + type: string + pattern: "^[A-Za-z0-9][A-Za-z0-9-]*$" + required: true + description: GitHub org or user the product repo is created under. + epicSlug: + type: string + pattern: "^[a-z][a-z0-9-]*$" + default: infra-baselining + description: >- + The epic this bootstrap tracks itself under. Every phase clubs its task + here, so a run that starts fresh and a run that resumes find the same + work — the epic is found by slug, which is why this is an input and not + a generated id. + repoPrivate: + type: boolean + default: true + description: >- + Whether the product repository is created private. Private is the safe + default — a product repo born public is a decision nobody made, and it + cannot be un-made retroactively for anything already pushed. + `orun.repo/ensure@v1` only sets this at creation: an existing repository + keeps whatever visibility it already has. + +# ── SOURCES ─────────────────────────────────────────────────────────────── +# The baseline is this repo itself. Run `orun new` from the Lumen repo root so +# `path: .` resolves to the baseline; orun pins it by digest into the object +# store before any module reads it, so a fork is reproducible + provenanced. +sources: + - name: baseline + kind: dir + path: . + +# Derived build output the baseline must never carry into a fork (the same set +# tooling/fork/components.mjs skips). Declared here so orun's core stays +# ecosystem-neutral — it excludes exactly what the blueprint names, nothing more. +ignore: + - dist + - coverage + - .turbo + - .next + - .wrangler + - .open-next + # Locally-rendered, gitignored artifacts. `orun new` snapshots the working + # tree, not the git index, so without these it copies whatever the operator + # happens to have built — and a fork would ship with the BASELINE's rendered + # config baked in. + # + # For the TEMPLATED workers, wrangler.jsonc is rendered from + # wrangler.template.jsonc at deploy time and carries resolved values + # (baseline domains, and per BF6 the deploy-time binding IDs that must never + # be committed) — those renders are ignored EXPLICITLY, per app. The two + # legacy non-templated workers (policy-worker, web-console-next) COMMIT + # their wrangler.jsonc as the real config; a global ignore silently dropped + # them from forks (their verify lanes then failed `test -f`), which is why + # this list names paths instead of a pattern. + # + # EVERY ENTRY IS `**/`-PREFIXED, AND THAT IS NOT DECORATION. orun matches an + # entry with no glob metacharacter against each path SEGMENT, and only one + # containing a metacharacter against the whole relative path. These read + # `apps/admin-worker/wrangler.jsonc` until now, which no single segment is + # ever equal to — twelve rules that excluded nothing (found on cirrus, which + # was forked from this list; `testing/coverage.test.sh` now refuses a + # path-shaped entry without a glob character). + - "**/apps/admin-worker/wrangler.jsonc" + - "**/apps/api-edge/wrangler.jsonc" + - "**/apps/cms/wrangler.jsonc" + - "**/apps/billing-worker/wrangler.jsonc" + - "**/apps/config-worker/wrangler.jsonc" + - "**/apps/events-worker/wrangler.jsonc" + - "**/apps/identity-worker/wrangler.jsonc" + - "**/apps/integrations-worker/wrangler.jsonc" + - "**/apps/membership-worker/wrangler.jsonc" + - "**/apps/metering-worker/wrangler.jsonc" + - "**/apps/notifications-worker/wrangler.jsonc" + - "**/apps/projects-worker/wrangler.jsonc" + - "**/apps/webhooks-worker/wrangler.jsonc" + - "*.tsbuildinfo" + + # A local credential or provider state on the operator's disk. `.gitignore` + # keeps these out of THIS repository's history, but `orun new` snapshots the + # working tree, so a `.env`, a `.dev.vars`, a `terraform init` cache or a + # local state file in the checkout a build runs from would be copied into + # the product and pushed — a secret published by a build. The same patterns + # the starters carry. This repository ships no `.env.example` or + # `.dev.vars.example`; one that should ship would need these narrowed. + # `.terraform` is a SEGMENT match, so the committed `.terraform.lock.hcl` + # provider locks still ship. + - "**/.env*" + - "**/.dev.vars*" + - .terraform + - "**/*.tfstate*" + + # THE BASELINE'S OWN CI, which is not a product's. + # + # `github-workflows` copies the whole `.github` directory, so anything added + # there ships into every product built from this repository. `baseline.yml` + # runs the FACTORY rather than the product — the contract gates and the + # placement tier, all reading paths under `testing/` that no product is + # placed with. These were inside `ci.yml` (as `flows-contract`) and + # therefore inside every product, where the job is red on the first pull + # request. `ci.yml` keeps `plan` and `run`, which a product needs. + # + # `testing/coverage.test.sh` keeps this list honest: a workflow that reads a + # path under `testing/` must be named here, or the gate is red. + - "**/.github/workflows/tag.yml" + - "**/.github/workflows/baseline.yml" + +# ── MODULES ─────────────────────────────────────────────────────────────── +# One module per component (mode: copy), with dependsOn edges TRANSCRIBED from +# what tooling/fork/components.mjs sniffed (declared dependsOn + wrangler service +# bindings + wiringComponents + workspace package deps + tests-follow-subject). +# orun orders them with its own DAG — the ordering that JS reimplementation is +# retired. +# +# Foundation libraries (packages/{contracts,sdk,db,policy-engine}) are copied so +# the fork is a self-contained workspace. To instead consume them as pinned +# shared packages (the SaaS-factory model, design §4), switch those four modules +# to `mode: consume` and drop their `to:` — they then participate in ordering and +# provenance but emit no bytes. +modules: + - name: admin-worker + mode: copy + source: baseline + from: apps/admin-worker + to: apps/admin-worker + dependsOn: [cloudflare-hyperdrive, contracts, db] + - name: admin-worker-tests + mode: copy + source: baseline + from: tests/admin-worker + to: tests/admin-worker + dependsOn: [admin-worker, contracts, db] + - name: api-edge + mode: copy + source: baseline + from: apps/api-edge + to: apps/api-edge + dependsOn: [billing-worker, cloudflare-hyperdrive, cloudflare-kv, config-worker, contracts, db, events-worker, identity-worker, integrations-worker, membership-worker, metering-worker, notifications-worker, projects-worker, webhooks-worker] + - name: api-edge-tests + mode: copy + source: baseline + from: tests/api-edge + to: tests/api-edge + dependsOn: [api-edge, contracts, db] + - name: billing-worker + mode: copy + source: baseline + from: apps/billing-worker + to: apps/billing-worker + dependsOn: [cloudflare-hyperdrive, contracts, db, policy-worker] + - name: billing-worker-tests + mode: copy + source: baseline + from: tests/billing-worker + to: tests/billing-worker + dependsOn: [billing-worker, contracts, db] + - name: cli + mode: copy + source: baseline + from: packages/cli + to: packages/cli + dependsOn: [sdk, webhook-verifier] + # THE CMS IS THE CONSOLE. Payload on Workers serves the admin, REST and + # GraphQL over schema `cms`, through its own cache-disabled Hyperdrive config + # (cloudflare-hyperdrive-cms) and an R2 bucket for media (cloudflare-r2-cms). + # It signs people in with the product's own accounts over a service binding + # to api-edge, so it lands after the edge. + - name: cms + mode: copy + source: baseline + from: apps/cms + to: apps/cms + dependsOn: [api-edge, cloudflare-hyperdrive-cms, cloudflare-r2-cms, contracts, db-migrate] + # The CMS's suite runs inside the cms lane (its buildCommand), so it ships + # with it, in the same phase. + - name: cms-tests + mode: copy + source: baseline + from: tests/cms + to: tests/cms + dependsOn: [cms, contracts] + - name: cloudflare-domain + mode: copy + source: baseline + from: infra/terraform/cloudflare-domain + to: infra/terraform/cloudflare-domain + dependsOn: [cms] + - name: cloudflare-hyperdrive + mode: copy + source: baseline + from: infra/terraform/cloudflare-hyperdrive + to: infra/terraform/cloudflare-hyperdrive + dependsOn: [supabase] + # The CMS's own database path: a second Hyperdrive config with caching OFF + # (an admin reads its own writes), over the same Supabase database. Its + # apply also generates the CMS's PAYLOAD_SECRET, so nobody types one. + - name: cloudflare-hyperdrive-cms + mode: copy + source: baseline + from: infra/terraform/cloudflare-hyperdrive-cms + to: infra/terraform/cloudflare-hyperdrive-cms + dependsOn: [supabase] + - name: cloudflare-kv + mode: copy + source: baseline + from: infra/terraform/cloudflare-kv + to: infra/terraform/cloudflare-kv + # The CMS's media bucket, per environment. Needs nothing else, so it lands + # with the first half of the data plane. + - name: cloudflare-r2-cms + mode: copy + source: baseline + from: infra/terraform/cloudflare-r2-cms + to: infra/terraform/cloudflare-r2-cms + - name: config-worker + mode: copy + source: baseline + from: apps/config-worker + to: apps/config-worker + dependsOn: [cloudflare-hyperdrive, contracts, db, membership-worker, policy-worker] + - name: config-worker-tests + mode: copy + source: baseline + from: tests/config-worker + to: tests/config-worker + dependsOn: [config-worker, contracts, db] + - name: contracts + mode: copy + source: baseline + from: packages/contracts + to: packages/contracts + - name: contracts-tests + mode: copy + source: baseline + from: tests/contracts + to: tests/contracts + dependsOn: [contracts, testing] + - name: db + mode: copy + source: baseline + from: packages/db + to: packages/db + - name: db-migrate + mode: copy + source: baseline + from: infra/db-migrate + to: infra/db-migrate + dependsOn: [db, supabase] + - name: db-tests + mode: copy + source: baseline + from: tests/db + to: tests/db + dependsOn: [db] + - name: events-worker + mode: copy + source: baseline + from: apps/events-worker + to: apps/events-worker + dependsOn: [cloudflare-hyperdrive, contracts, db, membership-worker, policy-worker] + - name: identity-worker + mode: copy + source: baseline + from: apps/identity-worker + to: apps/identity-worker + dependsOn: [cloudflare-hyperdrive, contracts, db, membership-worker, notifications-client, notifications-worker, policy-worker] + - name: identity-worker-tests + mode: copy + source: baseline + from: tests/identity-worker + to: tests/identity-worker + dependsOn: [contracts, db, identity-worker, notifications-client] + - name: integrations-worker + mode: copy + source: baseline + from: apps/integrations-worker + to: apps/integrations-worker + dependsOn: [billing-worker, cloudflare-hyperdrive, contracts, db, membership-worker, policy-worker, projects-worker] + - name: integrations-worker-tests + mode: copy + source: baseline + from: tests/integrations-worker + to: tests/integrations-worker + dependsOn: [contracts, db, integrations-worker] + - name: membership-worker + mode: copy + source: baseline + from: apps/membership-worker + to: apps/membership-worker + dependsOn: [billing-worker, cloudflare-hyperdrive, contracts, db, notifications-client, policy-worker] + - name: membership-worker-tests + mode: copy + source: baseline + from: tests/membership-worker + to: tests/membership-worker + dependsOn: [contracts, db, membership-worker] + - name: metering-worker + mode: copy + source: baseline + from: apps/metering-worker + to: apps/metering-worker + dependsOn: [cloudflare-hyperdrive, contracts, db, membership-worker, policy-worker] + - name: metering-worker-tests + mode: copy + source: baseline + from: tests/metering-worker + to: tests/metering-worker + dependsOn: [contracts, db, metering-worker] + - name: notifications-client + mode: copy + source: baseline + from: packages/notifications-client + to: packages/notifications-client + dependsOn: [contracts] + - name: notifications-client-tests + mode: copy + source: baseline + from: tests/notifications-client + to: tests/notifications-client + dependsOn: [contracts, notifications-client] + - name: notifications-worker + mode: copy + source: baseline + from: apps/notifications-worker + to: apps/notifications-worker + dependsOn: [cloudflare-hyperdrive, contracts, db, db-migrate, events-worker] + - name: notifications-worker-tests + mode: copy + source: baseline + from: tests/notifications-worker + to: tests/notifications-worker + dependsOn: [contracts, db, notifications-worker] + - name: policy-engine + mode: copy + source: baseline + from: packages/policy-engine + to: packages/policy-engine + dependsOn: [contracts] + - name: policy-engine-tests + mode: copy + source: baseline + from: tests/policy-engine + to: tests/policy-engine + dependsOn: [contracts, policy-engine] + - name: policy-worker + mode: copy + source: baseline + from: apps/policy-worker + to: apps/policy-worker + dependsOn: [contracts, policy-engine] + - name: policy-worker-tests + mode: copy + source: baseline + from: tests/policy-worker + to: tests/policy-worker + dependsOn: [contracts, policy-engine, policy-worker] + - name: projects-worker + mode: copy + source: baseline + from: apps/projects-worker + to: apps/projects-worker + dependsOn: [billing-worker, cloudflare-hyperdrive, contracts, db, membership-worker, policy-worker] + - name: projects-worker-tests + mode: copy + source: baseline + from: tests/projects-worker + to: tests/projects-worker + dependsOn: [contracts, db, projects-worker] + - name: sdk + mode: copy + source: baseline + from: packages/sdk + to: packages/sdk + dependsOn: [contracts] + - name: shared + mode: copy + source: baseline + from: packages/shared + to: packages/shared + - name: supabase + mode: copy + source: baseline + from: infra/terraform/supabase + to: infra/terraform/supabase + # No dependsOn. This read `[bootstrap]`, a module that does not exist and + # never has — orun refuses it (`dependsOn unknown module`). The phase + # splitter never hit it because it pruned every cross-phase edge to make + # each slice parse. Supabase is the root of the data plane: it needs the + # brokered management token, which is a hook's job, not a module's. + - name: testing + mode: copy + source: baseline + from: packages/testing + to: packages/testing + dependsOn: [contracts, db] + # The console's URL, kept: a Worker that answers 308 with the same page's + # place in the CMS of the same environment, so the console address a product + # hands out opens the Payload admin. + - name: web-console-next + mode: copy + source: baseline + from: apps/web-console-next + to: apps/web-console-next + dependsOn: [cms] + - name: web-console-next-tests + mode: copy + source: baseline + from: tests/web-console-next + to: tests/web-console-next + dependsOn: [web-console-next] + - name: webhook-verifier + mode: copy + source: baseline + from: packages/webhook-verifier + to: packages/webhook-verifier + - name: webhooks-worker + mode: copy + source: baseline + from: apps/webhooks-worker + to: apps/webhooks-worker + dependsOn: [cloudflare-hyperdrive, contracts, db, membership-worker, policy-worker] + + # ── Component-less workspace test packages (no component.yaml; ride their + # subject per the tests-follow-subject rule in components.mjs). ────────── + - name: events-worker-tests + mode: copy + source: baseline + from: tests/events-worker + to: tests/events-worker + dependsOn: [events-worker] + - name: webhooks-worker-tests + mode: copy + source: baseline + from: tests/webhooks-worker + to: tests/webhooks-worker + dependsOn: [webhooks-worker] + # Structural guards on the platform the fleet deploys under — account + # limits, the service-binding chain, secret scoping. It reads every app and + # infra component, and pins api-edge's chain depth, so it lands with the + # edge: the first phase at which the fleet it describes is whole. It was + # added after this file was written and no module named it, so no product + # had ever received it — `testing/coverage.test.sh` is what noticed. + - name: platform-limits-tests + mode: copy + source: baseline + from: tests/platform-limits + to: tests/platform-limits + dependsOn: [api-edge] + + + # ── Non-component workspace scaffolding (copied verbatim). ───────────────── + # + # There is deliberately NO composition-stack module. The execution contracts + # are not vendored: `intent.yaml` (copied below) declares + # kind: oci → oci://ghcr.io/sourceplane/stack-tectonic: + # so an instantiated repo resolves the SAME published catalog the baseline + # does, pinned to the same version, with nothing to drift. Composition changes + # are made in sourceplane/stack-tectonic, released there, and adopted by + # bumping the pinned tag — in the fork exactly as in the baseline. + # + # Only the tooling a PRODUCT runs: shared TS/ESLint config and the + # deploy-time wrangler renderer. This was `from: tooling`, the whole + # directory, and every product shipped the factory with it — the rebrand + # 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 + from: tooling/eslint + to: tooling/eslint + - name: tooling-tsconfig + mode: copy + source: baseline + from: tooling/tsconfig + to: tooling/tsconfig + - name: tooling-wire + mode: copy + source: baseline + from: tooling/wire + to: tooling/wire + # ── The product's own context pack, FILE BY FILE. + # + # This was `from: ai` — the whole directory — and it holds this + # repository's own planning state: `current.md`, `decisions.md` and + # `open-risks.md` are about building LUMEN. After rebrand they become + # statements about the customer's product, in the product's own voice, in + # the file an agent is pointed at first. + # + # There is no file list on a copy module, so one module per file. That is the + # feature, not the workaround: adding a file to `ai/context/` can no longer + # ship it by accident, because shipping it means writing a module and saying + # in a diff that a product should have it. + # NOT this repository's own deployment.md. That one is this product's live + # record — its URLs, its workspace, LIVE (200) beside each — and rebranded + # into a fork it would claim the fork's URLs answer before anything is + # deployed. A product starts from the stub, which says nothing is recorded + # yet, and 08-docs renders the real one from probes. + - name: ai-deployment + mode: template + source: baseline + from: .baseline/product/deployment.md + to: ai/context/deployment.md + bind: [deployment.md] + - name: ai-operations + mode: copy + source: baseline + from: ai/context/operations.md + to: ai/context/operations.md + - name: github-workflows + mode: copy + source: baseline + from: .github + to: .github + # No `.vscode` module. It shipped `.vscode/tasks.json`, which is THIS + # repository's agent loop: it runs coding agents with their sandbox and + # approvals bypassed against `agents/orchestrator.md` and `ai/state.json`, + # neither of which a product receives. In a product it was a one-click way + # to run an unsandboxed agent against files that do not exist. The baseline + # keeps it for its own loop; `testing/leak.test.sh` fails if it ships. + + # ── Root files (single-file copies). intent.yaml, package.json et al. carry + # instance identity; they are copied verbatim and rewritten in place by the + # `rebrand` hook (its rename map is the authority, not a per-file template). + # + # `agents/`, `flows/` and `FORKING.md` are gone from this list. The first + # two are the factory; the third did not exist, so `root-forking` was a + # module whose source was missing. + - name: root-intent + mode: copy + source: baseline + from: intent.yaml + to: intent.yaml + - name: root-package-json + mode: copy + source: baseline + from: package.json + to: package.json + - name: root-pnpm-workspace + mode: copy + source: baseline + from: pnpm-workspace.yaml + to: pnpm-workspace.yaml + - name: root-pnpm-lock + mode: copy + source: baseline + from: pnpm-lock.yaml + to: pnpm-lock.yaml + - name: root-turbo + mode: copy + source: baseline + from: turbo.json + to: turbo.json + - name: root-gitignore + mode: copy + source: baseline + from: .gitignore + to: .gitignore + # THE PRODUCT'S OWN FRONT PAGE AND AGENT GUIDE, not this repository's. + # + # `root-readme` copied this README, which describes the BASELINE — how it + # births products, links into `docs/phases/`, `BOOTSTRAP.md` and `specs/` + # (none of which ship), and an AWS layout that is not how a product runs. It + # is the product's catalog front page too (`intent.yaml` `repo.docs.overview`). + # So the product gets its own, from `.baseline/product/`, which nothing else + # reads. Templates rather than copies: both name the product's repository, + # `/`, which the rebrand has no rule for (it would turn + # this repository's `sourceplane/` into `sourceplane/`). + # + # `AGENTS.md` is what an agent handed this product reads first: what it is, + # what to read next, how a change lands and what not to touch. + - name: root-readme + mode: template + source: baseline + from: .baseline/product/README.md + to: README.md + bind: [README.md] + - name: root-agents + mode: template + source: baseline + from: .baseline/product/AGENTS.md + to: AGENTS.md + bind: [AGENTS.md] + + # ── The empty discovery roots, declared. + # orun's repo-scale gate — and later `orun plan` in the product's own CI — + # discovers apps/, infra/, packages/ and tests/, which by design are empty + # until later phases fill them. A missing root is a hard gate failure, so + # the scaffold flow created them with a mkdir and a touch immediately + # before calling `orun new`. That is a file the tree needs in order to be + # valid, which is what a module is for: shell that creates a required file + # is a module nobody wrote down. + - name: discovery-roots + mode: template + files: + apps/.gitkeep: "" + infra/.gitkeep: "" + packages/.gitkeep: "" + tests/.gitkeep: "" + + # ── Instance-identity values file (template) — consumed by the rebrand hook. + # This is the only place blueprint inputs touch the tree at scaffold time; + # everything else is a verbatim copy the hook rewrites. + # + # It is also how a LATER phase recovers what the operator answered. orun + # records the non-secret inputs in .orun/provenance.lock, but `.orun/` is + # gitignored in the product, so it has never survived a container — this + # file is committed, which is why every input a later phase needs must + # appear here. githuborg/epicSlug are here for exactly that: a + # phase run months later in a fresh container reads them back. + - name: rebrand-values + mode: template + files: + ".rebrand/values.json": | + { + "reponame": "{{ .reponame }}", + "productname": "{{ .productname }}", + "productdomain": "{{ .productdomain }}"{{ if .pascalName }}, + "pascalName": "{{ .pascalName }}"{{ end }}{{ if .brandSlug }}, + "brandSlug": "{{ .brandSlug }}"{{ end }}{{ if .cliBin }}, + "cliBin": "{{ .cliBin }}"{{ end }}{{ if .apibaseurl }}, + "apibaseurl": "{{ .apibaseurl }}"{{ end }}, + "subdomain": "{{ .subdomain }}"{{ if .salesEmail }}, + "salesEmail": "{{ .salesEmail }}"{{ end }}, + "orunWorkspace": "{{ .orunWorkspace }}", + "githuborg": "{{ .githuborg }}", + "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 Multi-tenant Payload CMS 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 Payload CMS that + is its 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, a KV namespace and the CMS media bucket applied on stage and prod + - Hyperdrive pooling the database for the fleet and for the CMS, 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 Payload CMS deployed on stage and prod, answering /health through its own Hyperdrive config + - the console URL on stage and prod redirecting into the CMS admin + - 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, media bucket" + brief: >- + Create a Supabase Postgres project, an idempotency KV namespace and the CMS's R2 media bucket 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 — one config for the workers, a cache-disabled one for the CMS — and apply the schema to it, so the workers and the CMS 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): the CMS console" + brief: >- + Land the Payload CMS on Workers, and the console URL that redirects into its admin, and see both 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 +# (`title`), what to budget (`expectedMinutes`), what must already be true +# (`requires`), whether it runs at all (`when`), and the hooks that do its +# work around placement: `pre` before, `post` after, `await` for what is +# still converging when the hooks are done. +# +# THE ORDER HERE IS THE EXECUTION ORDER, and the numbered names are the same +# names the task plane's milestones carry. Before BE1 the two disagreed: this +# file declared `workspace` LAST and `tooling/blueprint/split-phases.py` +# re-mapped it to the folder `01-scaffold`, which runs FIRST. A mapping table +# inside a script is a fact nothing checks, and this is what it was hiding — +# `supabase` declared `dependsOn: [bootstrap]`, a module that does not exist and +# never has. orun refuses that (`dependsOn unknown module`). The splitter +# never hit it because it PRUNED every cross-phase edge to make each slice +# parse, and a pruned edge to a module that is in no phase looks exactly like +# a pruned edge to a module in an earlier one. +# +# So the barrier law is what makes this reorder safe rather than cosmetic: a +# dependency may never point forward across a phase boundary, and orun +# refuses the blueprint if one does — where the splitter deleted the edge and +# carried on. +# +# `03-infrastructure-database` is the same kind of split for a different +# reason: its PR lanes read what 03's apply publishes (see there). +# +# 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 + description: Root manifests, tooling, compositions, and the rebrand values file. + expectedMinutes: 1 + # THE LINES A BUILD PAGE SHOWS, and why every phase's are this short. + # + # The console's build panel prints each hook's `narrate:` verbatim as the + # build's progress, one line per finished step, and a phase's waiting line + # under the step it waits on. So a line is a caption for ONE fact, true at + # the moment it is shown. `start` is one clause. + # + # NO PHASE AUTHORS `await`. That line is ALSO shown while a + # `requires.probe` waits, before any hook has run: "Terraform is applying" + # was printed while 03 waited for a provider connection. With none + # authored, orun writes ": <what it waits on>" from its own reason + # (an engine too old to know the reason says "<phase> is waiting."), which + # is true whichever thing it is waiting on. A generic authored line cannot + # do that: the reasons are whole clauses ("waiting for github to be + # connected…"), so "Waiting on {{ .meta.waitingOn }}" reads twice. + narrate: + 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-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 + # that OWNS the repository. A workspace connected to some other account + # passed "github is connected", and every PR of the product it built was + # invisible to it — no PR rows, nothing filed — found on + # sourceplane/altocumulus, whose workspace was connected only to the user + # account `adampullely`. So the owner's connection is asked for here, + # before a repository is created, and waited for like any other consent. + requires: + probe: + - id: github + uses: orun.doctor/check@v1 + with: + providers: [github] + githubOwner: "{{ .inputs.githuborg }}" + waitSeconds: 600 + pollSeconds: 20 + hooks: + pre: + # THE EPIC IS THE BOOTSTRAP'S OWN CONTAINER, so the bootstrap makes it. + # Every phase's task clubs under `epicSlug`, and until this hook 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 + narrate: 'Epic {{ .hooks.epic.outputs.key }} is open.' + with: + kind: epic + slug: "{{ .inputs.epicSlug }}" + name: "Infra baselining — {{ .inputs.productname }}" + - id: task + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: "{{ .phase.name }}" + name: "phase({{ .phase.name }}): repo born" + prefix: BASE + contract: tasks/01-scaffold.TaskContract.yaml + # The identity chain, moved here from `hooks.postInstantiate`. It was + # global because a one-shot instantiation has only one end; in a phased + # bootstrap the end of 01-scaffold IS that moment — every later phase + # applies into a tree that is already a git repo and already branded. + # + # rebrand.mjs enumerates the tree with `git ls-files`, so the output has + # to be a git repo with a populated index BEFORE it runs. `git add -A` + # only stages; nothing is committed here. The landing makes the commit. + post: + - id: git-init + run: ["git", "init", "-q"] + - id: git-stage + run: ["git", "add", "-A"] + - id: rebrand + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--values", ".rebrand/values.json", "--allow-dirty"] + # Re-tenant the fork. rebrand.mjs classifies the orun state backend as + # org-owned and deliberately leaves it untouched, so intent.yaml would + # keep the BASELINE's `workspace:` — the fork's CI would then claim + # another tenant's workspace on every remote op. Hook argv is not + # templated, so the value travels through .rebrand/values.json, which + # IS a rendered template. + # + # IDEMPOTENT. A missing `workspace:` line is the one real error. A line + # that already names this workspace is nothing to do — a build into + # the workspace the baseline itself declares, or a re-run of this + # phase over a tree it already wrote. This used to test "the text did + # not change", which is both of those AND the real error, so either + # failed the scaffold. + - id: orun-workspace + run: + - node + - -e + - | + const fs = require("fs"); + const values = JSON.parse(fs.readFileSync(".rebrand/values.json", "utf8")); + const ws = String(values.orunWorkspace || "").trim() || "ws_SET_ME"; + const line = /^(\s*workspace:\s*).*$/m; + const before = fs.readFileSync("intent.yaml", "utf8"); + if (!line.test(before)) { + console.error("orun-workspace: no `workspace:` line in intent.yaml — refusing to guess"); + process.exit(1); + } + const after = before.replace(line, "$1" + ws); + if (after !== before) fs.writeFileSync("intent.yaml", after); + console.log( + ws === "ws_SET_ME" + ? "orun-workspace: wrote placeholder ws_SET_ME — set your Orun Cloud workspace before enabling remote state" + : after === before + ? "orun-workspace: intent.yaml already names workspace " + ws + : "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 + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] + - id: pnpm-lockfile + run: ["pnpm", "install", "--lockfile-only"] + # The repo has to exist before there is anywhere to land. + - id: repo + uses: orun.repo/ensure@v1 + # From the action's outputs, not the inputs: the line names the + # repository GitHub answered with, and says whether this build made it. + narrate: '{{ .hooks.repo.outputs.fullName }} is ready{{ if eq .hooks.repo.outputs.created "true" }} — created for this build{{ end }}.' + with: + owner: "{{ .inputs.githuborg }}" + name: "{{ .inputs.reponame }}" + private: "{{ .inputs.repoPrivate }}" + # THE REPOSITORY MUST BE THE WORKSPACE'S before anything lands in it, + # or the product's own CI cannot reach the platform. Every convergence + # lane authenticates over GitHub OIDC, and the platform resolves that + # token through the repo link. With no link, every lane of the first + # real convergence died before running a step: + # + # ✕ remote state auth (oidc exchange): OIDC exchange rejected: + # Not found (code: not_found) + # + # The shell this replaced ended 01-scaffold with exactly this pair (its + # `link` step). BE4 kept the repo step and dropped the link, and + # nothing noticed, because no BE4 run had reached a convergence. + # + # `link` may be refused where the credential cannot write links (a + # workspace key) and the platform has linked the repository already — + # a --via-platform build only builds into a linked one. So `link` is + # best effort and `check` is the gate: an unlinked repository stops + # here, naming the fix, instead of an hour later in every lane. + - id: link + # True whichever half linked it: the line is shown only once `check`, + # the gate, has passed. + narrate: '{{ .inputs.githuborg }}/{{ .inputs.reponame }} is linked to the workspace.' + run: + - bash + - -c + - | + orun cloud link --org "$1" || true + orun cloud check --org "$1" || { + echo "$2 is not linked to workspace $1 — its CI cannot authenticate. Link it (orun cloud link --org $1, or the console's Git Repos) and re-run this phase." >&2 + exit 1 + } + - 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/<task>-<phase>` 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 + # far (orun >= v2.58.6) — and merges only on green. The product's PR + # runs carry remote state (.github/workflows/ci.yml), so a lane that + # needs a secret resolves it on the PR as it would on main. Every + # convergence after a merge is still watched, because deploying is + # what a merge does and a PR cannot. + # + # Every landing's line names its PR, or says there was nothing to land + # (a re-run over a main that already has the phase), and its `label` + # names the PR's row on the build page. + - id: land + uses: orun.pr/land@v1 + label: Scaffold + 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({{ .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: 3 + narrate: + start: 'Placing the shared packages every worker builds on.' + # After the convergence is green: built, not "building". + done: 'The shared packages are on main and built, in {{ .meta.elapsed }}.' + failed: 'The shared packages did not land; the failing step says why.' + modules: [cli, contracts, contracts-tests, db, db-tests, notifications-client, notifications-client-tests, policy-engine, policy-engine-tests, sdk, shared, testing, webhook-verifier] + requires: + phases: [01-scaffold] + hooks: + pre: + - id: task + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: "{{ .phase.name }}" + name: "phase({{ .phase.name }}): shared packages" + 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 <phase> <stamp>` — 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; + # before that it wrote the WHOLE tree up front, and 01-scaffold landed + # the entire product as its first PR). So these files arrive carrying the baseline's identity AFTER 01-scaffold's rebrand + # has run, and landing them as placed would ship `lumen-*` worker + # names into the product. The shell this replaced did the same in + # every phase (apply-blueprint.sh: place, stage, rebrand, stage). + # rebrand.mjs enumerates the tree with `git ls-files`, hence the stage + # before it; --verify then refuses a landing with identity left over. + - id: stage + run: ["git", "add", "-A"] + - id: rebrand + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--values", ".rebrand/values.json", "--allow-dirty"] + - id: restage + run: ["git", "add", "-A"] + - id: rebrand-verify + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] + # The workspace lockfile grows with the tree. 01-scaffold wrote it for + # the three projects that existed then, and the lanes install with + # --frozen-lockfile, so this phase's packages were refused before a + # test ran: `ERR_PNPM_OUTDATED_LOCKFILE … not up to date with + # 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/<task>-<phase>` 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 + 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({{ .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 + narrate: 'The packages built green on main.' + with: + # The run for the commit THIS landing merged, waited for. The + # branch's newest run, read the moment the merge returns, is the + # previous phase's — GitHub registers a push's run seconds later — + # so an unpinned watch reported "converged" for a run that had not + # started. And a wait of 0 parks the phase at once, which ends a + # one-process bootstrap (the platform's driver included) at its + # first convergence; the budget is roughly twice the phase's + # expectedMinutes. + sha: "{{ .phase.hooks.land.outputs.mergeSha }}" + 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: 2 + narrate: + start: 'Creating a Supabase Postgres project, a KV namespace and the CMS media bucket per environment.' + done: 'Supabase, KV and the media bucket are up on stage and prod, their outputs published, in {{ .meta.elapsed }}.' + failed: 'The data layer did not come up; the failing step says why.' + # HALF OF WHAT THIS PHASE USED TO BE, and the half is the point. + # + # The flows placed all four data-plane modules here — supabase, + # cloudflare-kv, cloudflare-hyperdrive, db-migrate — and landed the PR + # with `--no-wait`, because two of the four could never pass on it: the + # hyperdrive and db-migrate PR lanes resolve SUPABASE_PROJECT_REF, + # SUPABASE_DB_PASSWORD and SUPABASE_DB_URL, which are job outputs of the + # supabase APPLY, and an apply only happens on main. On a fresh product + # that PR was red by construction, so the phase could never be verified + # before it merged. + # + # Every phase here is a pull request that is verified, then merged. So + # the two that read supabase's outputs move to the next phase, which runs + # once those outputs exist — and this PR is one whose every lane can be + # green on a product that has nothing yet. + # cloudflare-r2-cms reads nothing anyone publishes, so it lands here, with + # the first half, rather than waiting for supabase. + modules: [cloudflare-kv, cloudflare-r2-cms, supabase] + # The first phase that DEPLOYS. `requires.probe` asks reality the question + # a lock file cannot answer: are the three provider connections live right + # now? + requires: + phases: [02-foundation] + probe: + - id: providers + uses: orun.doctor/check@v1 + with: + providers: [github, cloudflare, supabase] + githubOwner: "{{ .inputs.githuborg }}" + waitSeconds: 600 + pollSeconds: 20 + hooks: + # Brokered, one hook per template: `integrations/reconcile` mints from + # ONE connection with ONE scope template, and these six keys are six + # different scopes on purpose — the deploy token deliberately cannot + # touch Hyperdrive or R2. Collapsing them into one hook would be + # collapsing the scopes. Keys that already exist are kept. + # + # All six are minted here although CLOUDFLARE_HYPERDRIVE_TOKEN is not + # read until the next phase: this is the phase that asks for the + # connections, and a key minted with its siblings is one the card lists + # in one place. + # + # Each says "is in place", which is true whether it was minted now or + # kept from an earlier run. The lines are static: a hook id with a `-` + # cannot be named in a template. + pre: + - id: task + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: "{{ .phase.name }}" + name: "phase({{ .phase.name }}): supabase, kv, media bucket" + prefix: BASE + contract: tasks/03-infrastructure.TaskContract.yaml + # 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: 'The Cloudflare deploy, Hyperdrive, R2 and account keys are in place, brokered from your Cloudflare connection.' + with: + provider: cloudflare + secrets: + - { key: CLOUDFLARE_API_TOKEN, template: workers-deploy } + - { key: CLOUDFLARE_HYPERDRIVE_TOKEN, template: hyperdrive-edit } + # The CMS media bucket's own scope: cloudflare-r2-cms applies + # with it. The deploy token cannot create or read a bucket, which + # is also why the CMS deploys with resource provisioning off. + - { key: CLOUDFLARE_R2_TOKEN, template: r2-data } + - { key: CLOUDFLARE_ACCOUNT_ID, template: account-id } + - id: secrets-supabase + uses: orun.integrations/reconcile@v1 + narrate: 'The Supabase management token and org id are in place, read from your Supabase connection.' + with: + provider: supabase + 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 <phase> <stamp>` — 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"] + - id: rebrand + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--values", ".rebrand/values.json", "--allow-dirty"] + - id: restage + run: ["git", "add", "-A"] + - id: rebrand-verify + 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/<task>-<phase>` 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 + 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({{ .phase.name }}): supabase, kv, media bucket" + # 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 + narrate: 'Terraform applied; the convergence run on main came back green.' + with: + sha: "{{ .phase.hooks.land.outputs.mergeSha }}" + 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 + # failed passed that check. + - id: verify + uses: orun.secrets/exists@v1 + narrate: "Supabase's credentials, the KV wiring and the media bucket's wiring are published on stage and prod." + with: + keys: [WIRING_CLOUDFLARE_KV, WIRING_CLOUDFLARE_R2_CMS, SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD, SUPABASE_DB_URL] + project: "{{ .inputs.reponame }}" + environments: [stage, prod] + + # The other half of the data plane: the pieces that READ the database 03 + # created. Hyperdrive pools a connection to it, and db-migrate applies the + # 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: `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: 3 + narrate: + start: 'Adding the schema migrations and two Hyperdrive configs per environment, the fleet''s and the CMS''s.' + done: 'The schema is applied and both Hyperdrive configs are published for the workers and the CMS, in {{ .meta.elapsed }}.' + failed: 'The database did not come up behind Hyperdrive; the failing step says why.' + # cloudflare-hyperdrive-cms reads supabase's published outputs on its PR + # exactly as cloudflare-hyperdrive does, so it lands with it. + modules: [cloudflare-hyperdrive, cloudflare-hyperdrive-cms, db-migrate] + requires: + phases: [03-infrastructure] + probe: + - id: supabase-outputs + uses: orun.secrets/exists@v1 + with: + keys: [SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD, SUPABASE_DB_URL] + project: "{{ .inputs.reponame }}" + environments: [stage, prod] + hooks: + pre: + - id: task + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 03-infrastructure + name: "phase(03-infrastructure): hyperdrive, db-migrate" + 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 <phase> <stamp>` — 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"] + - id: rebrand + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--values", ".rebrand/values.json", "--allow-dirty"] + - id: restage + run: ["git", "add", "-A"] + - id: rebrand-verify + 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/<task>-<phase>` 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 + 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(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 + narrate: 'Migrations applied and Hyperdrive created; the convergence run on main came back green.' + with: + sha: "{{ .phase.hooks.land.outputs.mergeSha }}" + 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 and the CMS read, and the CMS's generated secret, are published on stage and prod." + with: + keys: [WIRING_CLOUDFLARE_HYPERDRIVE, WIRING_CLOUDFLARE_HYPERDRIVE_CMS, CMS_PAYLOAD_SECRET] + project: "{{ .inputs.reponame }}" + environments: [stage, prod] + + - name: 04-workers + title: The worker fleet + expectedMinutes: 4 + narrate: + start: 'Deploying the twelve-worker fleet, the longest stretch of the build.' + done: 'Twelve workers are live on stage and prod, with their bindings, 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] + hooks: + pre: + - id: task + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: "{{ .phase.name }}" + 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 <phase> <stamp>` — 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"] + - id: rebrand + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--values", ".rebrand/values.json", "--allow-dirty"] + - id: restage + run: ["git", "add", "-A"] + - id: rebrand-verify + 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/<task>-<phase>` 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 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. + # + # 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 + 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({{ .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 + narrate: 'The fleet deployed; the convergence run on main came back green.' + with: + sha: "{{ .phase.hooks.land.outputs.mergeSha }}" + repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" + resumeBudget: 3 + waitSeconds: 3600 + # 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: 2 + 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 which: a red convergence is the deploy; a verify whose addresses do not resolve means the addresses are wrong — check that `subdomain` is this Cloudflare account''s workers.dev subdomain.' + modules: [api-edge, api-edge-tests, platform-limits-tests] + requires: + # 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) + # + # 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: + - id: task + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: "{{ .phase.name }}" + name: "phase({{ .phase.name }}): api-edge" + 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 <phase> <stamp>` — 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"] + - id: rebrand + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--values", ".rebrand/values.json", "--allow-dirty"] + - id: restage + run: ["git", "add", "-A"] + - id: rebrand-verify + 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/<task>-<phase>` 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 + 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({{ .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 + narrate: 'The edge deployed; the convergence run on main came back green.' + with: + sha: "{{ .phase.hooks.land.outputs.mergeSha }}" + 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.' + with: + urls: + - "https://{{ .inputs.reponame }}-api-edge-stage.{{ .inputs.subdomain }}.workers.dev/health" + - "https://{{ .inputs.reponame }}-api-edge-prod.{{ .inputs.subdomain }}.workers.dev/health" + + # THE CONSOLE IS THE CMS. This phase lands Payload (apps/cms, with its + # suite) and the console's URL, which answers 308 into the CMS admin of the + # same environment, in one landing: the redirect `dependsOn` the CMS, so one + # convergence deploys them in that order. The CMS reads everything 03, 03-db + # and 05 published — its Hyperdrive config, its bucket, its generated + # secret, and api-edge for sign-in — which is why it is last. + # + # The custom-domain component lands here too, PARKED: it subscribes to no + # environment until an owner wires a zone (the commented-out `subscribe` + # block in infra/terraform/cloudflare-domain/component.yaml), so a landing of + # its own changed nothing live. It belongs with the last landing that + # converges a deploy because it routes the DEPLOYED console and edge (it + # `dependsOn` cms). It was the optional 07-domain phase, behind + # a `domain` input, until that input was removed; the numbering keeps its + # gap so 08-docs keeps its name. + - name: 06-console + title: The CMS console + # The longest build in the product (Next.js + Payload + OpenNext, about + # 3.3 MiB compressed), in its own lane per environment. MEASURED on this + # repository's own main branch, not on a bootstrap: the four convergences + # that built and deployed the CMS to stage and prod took 6m06s to 7m12s + # (docs/phases/TIMINGS.md). + expectedMinutes: 7 + narrate: + start: 'Building and deploying the Payload CMS and the console URL that opens it.' + done: 'The CMS is live on stage and prod and the console URL opens its admin, in {{ .meta.elapsed }}.' + failed: 'The console did not come up. The failing step says which: a red convergence is the deploy; a verify whose addresses do not resolve means the addresses are wrong — check that `subdomain` is this Cloudflare account''s workers.dev subdomain.' + modules: [cloudflare-domain, cms, cms-tests, web-console-next, web-console-next-tests] + requires: + phases: [05-edge] + hooks: + pre: + - id: task + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: "{{ .phase.name }}" + name: "phase({{ .phase.name }}): the CMS console" + 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 <phase> <stamp>` — 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"] + - id: rebrand + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--values", ".rebrand/values.json", "--allow-dirty"] + - id: restage + run: ["git", "add", "-A"] + - id: rebrand-verify + 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/<task>-<phase>` 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 + 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({{ .phase.name }}): the CMS 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 + # The CMS build is the heaviest lane in the product. + await: + - id: converge + uses: orun.run/watch@v1 + narrate: 'The console deployed; the convergence run on main came back green.' + with: + sha: "{{ .phase.hooks.land.outputs.mergeSha }}" + 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 + # /health is a real round trip: Payload starts with its secret, and + # counts `users` through HYPERDRIVE_CMS in schema `cms`, so a 200 means + # the CMS can serve — not merely that a Worker answered. + - id: verify + uses: orun.http/probe@v1 + narrate: 'The edge and the CMS answered /health on stage and prod.' + with: + urls: + - "https://{{ .inputs.reponame }}-api-edge-stage.{{ .inputs.subdomain }}.workers.dev/health" + - "https://{{ .inputs.reponame }}-cms-stage.{{ .inputs.subdomain }}.workers.dev/health" + - "https://{{ .inputs.reponame }}-api-edge-prod.{{ .inputs.subdomain }}.workers.dev/health" + - "https://{{ .inputs.reponame }}-cms-prod.{{ .inputs.subdomain }}.workers.dev/health" + # The console's URL answers 308 into the CMS admin, and nothing else: + # the probe does not follow redirects, so a 200 here would mean the + # old console came back. + - id: verify-console + uses: orun.http/probe@v1 + narrate: 'The console URL redirects into the CMS admin on stage and prod.' + with: + expectStatus: 308 + urls: + - "https://{{ .inputs.reponame }}-web-console-next-stage.{{ .inputs.subdomain }}.workers.dev" + - "https://{{ .inputs.reponame }}-web-console-next-prod.{{ .inputs.subdomain }}.workers.dev" + + # Places nothing. It records what the other phases built, from PROBED facts + # rather than from what the blueprint intended — which is why it runs last + # and why its verify is the same probe 06-console ends on. + - name: 08-docs + title: The deployment, recorded + expectedMinutes: 1 + narrate: + start: 'Recording the live deployment in the repository.' + done: 'ai/context/deployment.md records the live deployment, from probed facts.' + failed: 'The deployment record did not land; everything built is still there, only the write-up is missing.' + modules: [] + requires: + phases: [06-console] + hooks: + pre: + - id: task + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: "{{ .phase.name }}" + name: "docs(deployment): record live deployment state" + 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/<task>-<phase>` 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 + 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: "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 six URLs 06-console just probed. Their addresses + # are already on the build page; a second set of the same facts is + # noise, and the line below still speaks. + - id: verify + uses: orun.http/probe@v1 + quiet: true + narrate: 'Every live URL answered on the final probe.' + with: + urls: + - "https://{{ .inputs.reponame }}-api-edge-stage.{{ .inputs.subdomain }}.workers.dev/health" + - "https://{{ .inputs.reponame }}-cms-stage.{{ .inputs.subdomain }}.workers.dev/health" + - "https://{{ .inputs.reponame }}-api-edge-prod.{{ .inputs.subdomain }}.workers.dev/health" + - "https://{{ .inputs.reponame }}-cms-prod.{{ .inputs.subdomain }}.workers.dev/health" + - id: verify-console + uses: orun.http/probe@v1 + quiet: true + narrate: 'The console URL still redirects into the CMS admin.' + with: + expectStatus: 308 + urls: + - "https://{{ .inputs.reponame }}-web-console-next-stage.{{ .inputs.subdomain }}.workers.dev" + - "https://{{ .inputs.reponame }}-web-console-next-prod.{{ .inputs.subdomain }}.workers.dev" diff --git a/specs/epics/lumen-payload-baseline/IMPLEMENTATION-STATUS.md b/specs/epics/lumen-payload-baseline/IMPLEMENTATION-STATUS.md new file mode 100644 index 0000000..4bac1f8 --- /dev/null +++ b/specs/epics/lumen-payload-baseline/IMPLEMENTATION-STATUS.md @@ -0,0 +1,18 @@ +# Implementation status — lumen-payload-baseline + +## PB-1 — the template layer — in review + +Verified locally with orun v2.89.0 (built from its tag): + +| gate | result | +|---|---| +| manifest, phases, coverage, rebrand, retouch, bootstrap-defer, fleet-stubs, pen-reset | pass | +| leak | pass — no factory path, the context pack exactly two files | +| placement | pass — 01 → 08 through the rebrand, `--resume` keeps the branding | +| branded-fork | pass — 243 files rewritten and 41 paths renamed; a frozen install, every package typechecked, every Worker config rendered, every suite (30 test tasks) green | + +Found by Tier 2 and fixed in this change: a test variable named `lumen`, the +migration checksum the rebrand broke, the CMS's undeclared `contracts` edge, +and the unrecorded chain depth since the CMS's sign-in binding. + +## PB-2 — tagged and registered — not started diff --git a/specs/epics/lumen-payload-baseline/README.md b/specs/epics/lumen-payload-baseline/README.md new file mode 100644 index 0000000..b4fe80f --- /dev/null +++ b/specs/epics/lumen-payload-baseline/README.md @@ -0,0 +1,42 @@ +# Epic: lumen-payload-baseline (PB) + +**lumen-payload is a live product: a multi-tenant SaaS whose console is +Payload CMS. This epic makes it a baseline too — "a Blueprint of itself", at +the quality of the Lumen baseline it was born from — so a new product with the +same shape (the twelve-Worker fleet and API edge, Payload on Workers as the +console, its own Hyperdrive path and media on R2, sign-in with the product's +own accounts) is one build away, and registered on Orunbase as the public +platform "Multi-tenant Payload CMS".** + +The idea that makes it more than a copy of Lumen's template layer: the CMS's +code names the platform `lumen` in every case-form — `lib/lumen/`, +`/auth/lumen/*`, `LumenLogin`, `lumenUserId`, the `lumen_user_id` column, +`LUMEN_API`, a migration called `206_cms_lumen_identity` — so the rebrand has +to rename code, paths included, and keep the pieces that must agree agreeing. +So the baseline's own CI places a product, brands it, and runs that product's +typecheck and every suite. + +## Status + +| Field | Value | +|-------|-------| +| Status | In progress (2026-10-30) | +| Cluster | **PB** (PB-1, PB-2) | +| Owner(s) | the factory layer (`repo-blueprint.yaml`, `blueprint.yaml`, `tooling/rebrand/`, `testing/`, `docs/phases/`, `.baseline/product/`); `apps/cms` (one dependency edge); `tests/cms`, `tests/platform-limits` (one rename, one recorded depth) | +| Builds on | the Lumen baseline at `baseline-v32` (this repository's parent), `lumen-payload-cms` (PC), `lumen-payload-console` (PX) | +| Decisions locked | (1) **Lumen's phase names, not new ones**: the CMS's data plane lands in 03 and 03-db beside the fleet's, and the CMS lands in `06-console`, because it IS the console. (2) **One rebrand engine for every baseline built this way**: its left-hand side is this repository's own `.rebrand/values.json`. (3) **The platform word is renamed everywhere, paths included**, to the product's own name. (4) **A product's code must still build**: the baseline's CI installs, typechecks and tests a placed, branded product. (5) **The build time is derived, not measured**, and says so (no test build was run, by the owner's choice). | +| Gate | PB-1 merged with Baseline CI green; `baseline-v1` cut by `tag.yml`; the registry row public, free, kind platform. | + +## Read order + +1. `design.md` — the shape of the baseline, the rebrand, the gates +2. `implementation-plan.md` — the milestones and what "done" means +3. `risks-and-open-questions.md` — what could go wrong and what was decided +4. `IMPLEMENTATION-STATUS.md` — what actually shipped + +## Milestones at a glance + +| Milestone | What it lands | Done when | +|---|---|---| +| PB-1 — the template layer | the card, the build, the rebrand engine, the gates (Tier 0–2), the product templates, the docs, this spec | Baseline CI green on the PR; merged | +| PB-2 — tagged and registered | `baseline-v1`; the orun-cloud registry row and the Orunbase platform page | the tag exists; the row is public at `baseline-v1` | diff --git a/specs/epics/lumen-payload-baseline/design.md b/specs/epics/lumen-payload-baseline/design.md new file mode 100644 index 0000000..cd36a8c --- /dev/null +++ b/specs/epics/lumen-payload-baseline/design.md @@ -0,0 +1,105 @@ +# Design — lumen-payload-baseline + +## 1. What a product gets + +Everything lumen-payload runs, under the product's own name: the twelve +bounded-context Workers behind `api-edge`, Supabase Postgres through +Hyperdrive, the edge's idempotency KV, `db-migrate` — and the CMS: + +- `apps/cms` — Payload 3 on Next.js (OpenNext) on Workers: the admin, REST and + GraphQL over schema `cms`, through its own cache-disabled Hyperdrive config, + with media in R2. It signs people in with the product's own accounts over a + service binding to `api-edge`, and holds the account, organization, + notifications, security-activity and billing pages. +- `apps/web-console-next` — the console URL, a 308 into the CMS admin. +- `infra/terraform/cloudflare-hyperdrive-cms`, `infra/terraform/cloudflare-r2-cms` + — the CMS's database path (and its generated `PAYLOAD_SECRET`) and bucket. + +And none of the factory (`testing/leak.test.sh`, `placement.test.sh`), none of +this repository's planning state, and none of its live record: a product's +`ai/context/deployment.md` starts as the "not rendered yet" stub, because this +repository's own would claim the product's URLs answer before they exist. + +## 2. Where the CMS lands — Lumen's phases, not new ones + +The barrier law decides it: a module may not depend on one in a later phase, +and a phase's PR lanes may not read what only a later apply publishes. + +| module | phase | why there | +|---|---|---| +| `cloudflare-r2-cms` | `03-infrastructure` | reads nothing anyone publishes | +| `cloudflare-hyperdrive-cms` | `03-infrastructure-database` | plans against supabase's outputs, exactly as `cloudflare-hyperdrive` does | +| `cms`, `cms-tests` | `06-console` | binds what 03/03-db publish and `api-edge` (05); it is the console | +| `web-console-next` (redirect) | `06-console` | `dependsOn` the CMS, so one convergence deploys the CMS first | + +`CLOUDFLARE_R2_TOKEN` (`r2-data`) is minted with its siblings in 03's one +Cloudflare reconcile. 06's verify probes the edge's and the CMS's `/health` +(200 — the CMS's is a round trip to schema `cms`) and the console URL (308, +not followed). The first CMS admin is the owner's step, documented, not the +build's: it would mean a build holding an admin's credential. + +Lumen's prebuilt-console machinery (`console-artifact.mjs`, its pin, its +publish job in `tag.yml`, its test) is not carried: this baseline's console is +the CMS, which every product builds. + +## 3. The rebrand + +`tooling/rebrand/rebrand.mjs` keeps Lumen's engine — the protected org-owned +literals, the held (opaque) substituted values, the guard that keeps a later +phase's pass from re-rewriting what an earlier one wrote, the leftover sweep — +and changes two things. + +**The left-hand side is this repository's own identity**, read from its +committed `.rebrand/values.json` (reponame, productname, subdomain, +workspace) and derived into every case-form, so the same file serves every +baseline built this way. + +**The platform word**, `lumen`, in every case-form, is renamed into the +product's: + +| form | example | becomes | +|---|---|---| +| env / binding | `LUMEN_API` | `<ENV>_API` (from cliBin) | +| PascalCase, glued | `LumenLogin` | `<Pascal>Login` | +| camelCase | `lumenUserId` | `<camel>UserId` | +| snake_case | `lumen_user_id`, `206_cms_lumen_identity` | `<snake>_user_id` — snake derived from the camel form **as Payload's adapter derives a column from a field** (to-snake-case: every capital starts a word), so the field and its column stay one name | +| slug | `lib/lumen/`, `/auth/lumen/`, `'lumen'` | `<brandSlug>` | +| display | "your Lumen account" | the product name | + +Paths are renamed by the same rules (`git mv`), so a directory and the imports, +routes and migration names pointing into it stay one string. A migration the +rebrand rewrote is re-sealed in `packages/db/src/manifest.ts` — the runner +refuses a file that does not hash to its checksum, on plan and on apply — and +only those: a stale checksum on an untouched migration is a hand edit the +runner should keep refusing. + +The sweep counts as residue `lumen` in any case and position, the baseline's +own name in every form, and its subdomain and workspace when the product's +differ — over contents and paths. + +## 4. The gates + +Lumen's Tier 0 and 1, adapted, plus a Tier 2 Lumen does not have: + +- Tier 0 (`baseline-contract`): manifest, phases, coverage, rebrand, retouch, + bootstrap-defer, fleet-stubs, pen-reset. fleet-stubs learns a second way a + binding holder's targets exist first — every Worker it binds is an enforced + dependency (the CMS binds only api-edge, two phases earlier). +- Tier 1 (`blueprint-parses`): the document read by the pinned CLI, the leak + gate, the placement through a rebrand. +- Tier 2 (`branded-fork`): the product placed and branded, then asked about + itself — the lockfile refreshed, a frozen install, every package + typechecked, every Worker config rendered from its fixture, every suite. + +Tier 2 found three things before any product did: a test's `const lumen` +(becoming `const acme-cloud`), the migration checksum, and two failures this +repository already had and its own CI never ran — `platform-limits`' chain +depth after the CMS's binding, and the CMS's undeclared `contracts` edge — +both on `quick-check` lanes that run no tests (docs/components/REVIEW.md). + +## 5. The card and the registry + +`blueprint.yaml`: "Multi-tenant Payload CMS", tags saas/cms/cloudflare/ +supabase/payload/nextjs, six secrets, seven milestones, 23 minutes. The +registry row (orun-cloud) is `lumen-payload`, public, free, kind platform on +Orunbase, at `baseline-v1`. diff --git a/specs/epics/lumen-payload-baseline/implementation-plan.md b/specs/epics/lumen-payload-baseline/implementation-plan.md new file mode 100644 index 0000000..9af4b3c --- /dev/null +++ b/specs/epics/lumen-payload-baseline/implementation-plan.md @@ -0,0 +1,35 @@ +# Implementation plan — lumen-payload-baseline + +## PB-1 — the template layer + +One pull request, because the pieces are one system: the build names the +rebrand, the gates read the build, the card is held to the build. + +- `repo-blueprint.yaml` and `blueprint.yaml` from Lumen `baseline-v32`, with + the CMS's four modules, the R2 token, the CMS probes, the deployment stub as + a template, and no console-artifact hooks. +- `tooling/rebrand/` — the engine of design §3; `tooling/bootstrap/`, + `hooks/render-deployment-docs.sh` (CMS rows). +- `testing/` — Lumen's gates adapted, `rebrand.test.sh` rewritten for the + engine, `branded-fork.test.sh` new; `.github/workflows/baseline.yml` (three + jobs) and `tag.yml` (the cut only). +- `.baseline/product/` — the product's README, AGENTS.md and deployment stub, + from this repository's own pages. +- Docs: `BOOTSTRAP.md`, `docs/phases/` (06-console rewritten for the CMS, + TIMINGS with the derived 23), `docs/components/REVIEW.md` regenerated for 49 + components, README and AGENTS.md sections on the baseline. +- Product fixes Tier 2 found: `apps/cms` declares `contracts`; + `tests/platform-limits` records the CMS's chain depth; one test variable + renamed. + +**Done when** every gate passes locally (orun v2.89.0) and in Baseline CI, and +the PR is merged with the product's own CI green. + +## PB-2 — tagged and registered + +- `tag.yml` cuts `baseline-v1` from `main`. +- orun-cloud: the registry row (`lumen-payload`, public, free, the card at + `blueprint.yaml`), the vendored card fixture and its tests, the docs overview + and the generated facts; then the Orunbase platform page. + +**Done when** the tag exists and the row is public at `baseline-v1`. diff --git a/specs/epics/lumen-payload-baseline/risks-and-open-questions.md b/specs/epics/lumen-payload-baseline/risks-and-open-questions.md new file mode 100644 index 0000000..6474189 --- /dev/null +++ b/specs/epics/lumen-payload-baseline/risks-and-open-questions.md @@ -0,0 +1,11 @@ +# Risks and open questions — lumen-payload-baseline + +| id | risk | status | +|---|---|---| +| PB-A | **The build time is not measured.** No test build was run (the owner's choice). 23 is Lumen's measured phases plus this repository's measured CMS deploys. | Open — the first real bootstrap replaces TIMINGS' derived section with its run. | +| PB-B | **A bare `lumen` in an identifier position** becomes a slug, which is not an identifier (`const lumen` → `const acme-cloud`). | Mitigated — the one case is renamed; Tier 2 typechecks every package of a branded product; AGENTS.md says so. | +| PB-C | **A rewritten migration's checksum.** The runner refuses a file whose hash is not its manifest's. | Resolved — the rebrand re-seals what it rewrote, and only that; tested. | +| PB-D | **26 components verify on `quick-check`, which runs no tests**, so a product's own CI does not run most suites (inherited from Lumen; it hid two failures here). | Open, deliberately — flipping them is its own change. Tier 2 runs every suite of a placed product, so a product is not born red. | +| PB-E | **The first admin needs the owner.** A product's CMS opens to nobody until its owner sets `CMS_SETUP_TOKEN`. | By design — documented in BOOTSTRAP §4, the product README and the CMS runbook. | +| PB-F | **R2 must be enabled on the Cloudflare account** before the first bucket, and the connection's token must carry R2 Storage Write for `r2-data`. | Documented — BOOTSTRAP §0, docs/phases/03, troubleshooting. | +| PB-G | **A product named so its PascalCase form is not an identifier** (`2 Acme`). | Resolved — the rebrand refuses it before writing. | diff --git a/tasks/01-scaffold.TaskContract.yaml b/tasks/01-scaffold.TaskContract.yaml new file mode 100644 index 0000000..08d690f --- /dev/null +++ b/tasks/01-scaffold.TaskContract.yaml @@ -0,0 +1,18 @@ +# Task contract template for the 01-scaffold 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 product repo is born — intent, CI, tooling and identity — and linked to its workspace + affects: + - intent.yaml + - .github/workflows + - tooling + - .rebrand + doneWhen: + - repo pushed and main pinned as default + - workspace linked (orun cloud link) + gates: [] diff --git a/tasks/02-foundation.TaskContract.yaml b/tasks/02-foundation.TaskContract.yaml new file mode 100644 index 0000000..e1bb232 --- /dev/null +++ b/tasks/02-foundation.TaskContract.yaml @@ -0,0 +1,22 @@ +# Task contract template for the 02-foundation 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 13 shared packages everything later builds on land and verify green + affects: + - cli + - contracts + - db + - notifications-client + - policy-engine + - sdk + - shared + - testing + - webhook-verifier + doneWhen: + - PR verify lanes green (turbo builds + tests) + gates: [] diff --git a/tasks/03-infrastructure-database.TaskContract.yaml b/tasks/03-infrastructure-database.TaskContract.yaml new file mode 100644 index 0000000..f4c1228 --- /dev/null +++ b/tasks/03-infrastructure-database.TaskContract.yaml @@ -0,0 +1,16 @@ +# Task contract template for the 03-infrastructure-database 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 database's consumers — the schema migrations (schema cms included) and both Hyperdrive configs — are applied on stage and prod and their wiring published + affects: + - db-migrate + - cloudflare-hyperdrive + - cloudflare-hyperdrive-cms + doneWhen: + - migrations applied, and WIRING_CLOUDFLARE_HYPERDRIVE, WIRING_CLOUDFLARE_HYPERDRIVE_CMS and CMS_PAYLOAD_SECRET published on stage and prod + gates: [] diff --git a/tasks/03-infrastructure.TaskContract.yaml b/tasks/03-infrastructure.TaskContract.yaml new file mode 100644 index 0000000..622ff72 --- /dev/null +++ b/tasks/03-infrastructure.TaskContract.yaml @@ -0,0 +1,16 @@ +# Task contract template for the 03-infrastructure 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 data plane's roots — Supabase, KV and the CMS media bucket — are provisioned on stage and prod and their outputs published + affects: + - cloudflare-kv + - cloudflare-r2-cms + - supabase + doneWhen: + - WIRING_CLOUDFLARE_KV, WIRING_CLOUDFLARE_R2_CMS, SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD and SUPABASE_DB_URL published on stage and prod + gates: [] diff --git a/tasks/04-workers.TaskContract.yaml b/tasks/04-workers.TaskContract.yaml new file mode 100644 index 0000000..76c707d --- /dev/null +++ b/tasks/04-workers.TaskContract.yaml @@ -0,0 +1,25 @@ +# 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 12-worker fleet lands and deploys once, each worker carrying its full service bindings + 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: + - convergence green with every service binding in place + gates: [] diff --git a/tasks/05-edge.TaskContract.yaml b/tasks/05-edge.TaskContract.yaml new file mode 100644 index 0000000..ba71640 --- /dev/null +++ b/tasks/05-edge.TaskContract.yaml @@ -0,0 +1,14 @@ +# Task contract template for the 05-edge 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 API edge — the single public entry point fronting the fleet — is live on stage and prod + affects: + - api-edge + doneWhen: + - api-edge /health 200 on stage and prod + gates: [] diff --git a/tasks/06-console.TaskContract.yaml b/tasks/06-console.TaskContract.yaml new file mode 100644 index 0000000..1224e10 --- /dev/null +++ b/tasks/06-console.TaskContract.yaml @@ -0,0 +1,19 @@ +# Task contract template for the 06-console 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 Payload CMS is live on stage and prod as the product's console, and the console URL opens its admin + affects: + - cms + - web-console-next + # Not cms-tests: its suite runs inside the cms lane (the cms buildCommand). + # Not cloudflare-domain, though 06-console lands it: it ships parked + # (subscribe.environments: []), and a parked component deploys nothing. + doneWhen: + - the CMS answers /health on stage and prod, through its own Hyperdrive config + - the console URL answers 308 into the CMS admin on stage and prod + gates: [] diff --git a/tasks/08-docs.TaskContract.yaml b/tasks/08-docs.TaskContract.yaml new file mode 100644 index 0000000..10d4749 --- /dev/null +++ b/tasks/08-docs.TaskContract.yaml @@ -0,0 +1,16 @@ +# Task contract template for the 08-docs 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 live deployment is recorded from verified facts as agent-readable state in the product repo + affects: + - ai/context/deployment.md + - ai/context/operations.md + - README.md + doneWhen: + - committed deployment manifest matches probed reality + gates: [] diff --git a/tasks/PB-1.TaskContract.yaml b/tasks/PB-1.TaskContract.yaml new file mode 100644 index 0000000..da06265 --- /dev/null +++ b/tasks/PB-1.TaskContract.yaml @@ -0,0 +1,33 @@ +apiVersion: orun.io/v1 +kind: TaskContract +metadata: + name: PB-1 + title: "lumen-payload as a Lumen-grade baseline: the template layer" +spec: + goal: "lumen-payload is a Blueprint of itself: repo-blueprint.yaml places a branded product with the Payload CMS as its console, blueprint.yaml is its card, and the baseline's own CI proves a placed, branded product installs, typechecks and passes every suite." + affects: + - "repo-blueprint.yaml" + - "blueprint.yaml" + - "tooling/rebrand/**" + - "tooling/bootstrap/**" + - "hooks/**" + - "testing/**" + - ".baseline/product/**" + - ".github/workflows/baseline.yml" + - ".github/workflows/tag.yml" + - "BOOTSTRAP.md" + - "docs/phases/**" + - "docs/components/REVIEW.md" + - "tasks/0*.TaskContract.yaml" + - "tests/fixtures/acme.json" + - "apps/cms/component.yaml" + - "tests/cms/src/lumen-accounts.test.ts" + - "tests/platform-limits/src/service-chain.test.ts" + - "README.md" + - "AGENTS.md" + - "specs/epics/lumen-payload-baseline/**" + - "tasks/PB-1.TaskContract.yaml" + doneWhen: + - "Baseline CI (baseline-contract, blueprint-parses, branded-fork) is green on the pull request" + - "the product's own CI is green on the pull request and on main after the merge" + 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/branded-fork.test.sh b/testing/branded-fork.test.sh new file mode 100755 index 0000000..787c221 --- /dev/null +++ b/testing/branded-fork.test.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash +# TIER 2 — THE PLACED, BRANDED PRODUCT COMPILES AND PASSES ITS OWN TESTS. +# +# placement.test.sh proves a product comes out of the blueprint branded, with +# nothing of the factory in it, and that `orun validate` and `orun plan` accept +# it. It does not prove the product's CODE survived the rebrand — and here the +# rebrand does more than rename words: the CMS names the platform `lumen` in +# every case-form, so the rebrand renames a Payload field and the column +# derived from it, the route and module directories and every import into +# them, a service binding, a cookie and a migration. A rename that leaves any +# two of those disagreeing is a product that is branded, clean by every other +# check here, and broken. +# +# So this places the whole blueprint from tests/fixtures/acme.json, brands it +# exactly as the phases do, refreshes the lockfile exactly as they do, and then +# asks the product itself: install, typecheck every package, run every suite. +# That is what the product's own CI runs on its first pull request, minus the +# deploys. +# +# It found the one place a slug was not a slug (a test's `const lumen = …`, +# which became `const acme-cloud = …`) before any product did. +# +# Needs: orun (the pinned version) + node + pnpm + python3 + git, and the +# npm registry (it installs). No credential, nothing deployed. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +for tool in orun node pnpm python3 git; do + command -v "$tool" >/dev/null || { echo "branded-fork.test.sh needs $tool on PATH" >&2; exit 1; } +done + +# BRANDED_FORK_KEEP=<dir> keeps the placed product there, to look at a failure. +if [ -n "${BRANDED_FORK_KEEP:-}" ]; then + scratch="$BRANDED_FORK_KEEP"; rm -rf "$scratch"; mkdir -p "$scratch" +else + scratch="$(mktemp -d)" + trap 'rm -rf "$scratch"' EXIT +fi + +sets=() +while IFS=$'\t' read -r k v; do sets+=( --set "$k=$v" ); done < <( + python3 - "$root/tests/fixtures/acme.json" <<'PY' +import json, sys +for k, v in json.load(open(sys.argv[1])).items(): + if not k.startswith("_"): + print(f"{k}\t{'true' if v is True else 'false' if v is False else v}") +PY +) + +tree="$scratch/product" +mkdir -p "$tree"/{apps,infra,packages,tests} +for d in apps infra packages tests; do touch "$tree/$d/.gitkeep"; done + +echo "── placing and branding the whole blueprint" +orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" "${sets[@]}" > "$scratch/place.log" 2>&1 || { + echo "FAIL: the placement did not run" >&2; tail -20 "$scratch/place.log" >&2; exit 1; } +( + cd "$tree" + git init -q -b main + git config user.email t@example.invalid + git config user.name "tier two" + printf 'baseline/\n.orun/\n' >> .gitignore + git add -A + node "$root/tooling/rebrand/rebrand.mjs" --values .rebrand/values.json --allow-dirty + git add -A + node "$root/tooling/rebrand/rebrand.mjs" --values .rebrand/values.json --verify +) > "$scratch/brand.log" 2>&1 || { echo "FAIL: the rebrand did not complete" >&2; tail -20 "$scratch/brand.log" >&2; exit 1; } +grep -E 'file\(s\) affected' "$scratch/brand.log" | sed 's/^/ /' + +run() { # LABEL COMMAND... + local label="$1" start log + shift + log="$scratch/$(echo "$label" | tr -c 'a-z0-9' '-').log" + start=$(date +%s) + if (cd "$tree" && "$@") > "$log" 2>&1; then + echo " ok $label ($(( $(date +%s) - start ))s)" + else + echo "FAIL: $label" >&2 + grep -E 'error TS|FAIL |✕|Error:|ERR_' "$log" | head -40 >&2 || tail -40 "$log" >&2 + exit 1 + fi +} + +echo "── the product, asked about itself" +# The phases refresh the lockfile after every rebrand (`pnpm install +# --lockfile-only`); a product's first CI install is then frozen against it. +run "lockfile refreshed as the phases refresh it" pnpm install --lockfile-only +run "installed, frozen" pnpm install --frozen-lockfile +run "every package typechecks" pnpm exec turbo run typecheck --concurrency=4 +# The suites read each Worker's RENDERED wrangler.jsonc, which is never +# committed: a lane renders it from wrangler.template.jsonc and the committed +# wiring.fixture.json before it verifies (tooling/wire/render.mjs, the same +# renderer the deploy runs against published wiring). So does this. +render_all() { + local t d n=0 + for t in apps/*/wrangler.template.jsonc; do + d="$(dirname "$t")" + [ -f "$d/wiring.fixture.json" ] || { echo "$d has a template and no wiring.fixture.json" >&2; return 1; } + node tooling/wire/render.mjs --template "$t" --out "$d/wrangler.jsonc" --map "$d/wiring.fixture.json" || return 1 + n=$((n + 1)) + done + [ "$n" -gt 0 ] || { echo "no wrangler.template.jsonc rendered — gone blind" >&2; return 1; } +} +run "every Worker config rendered from its fixture" render_all +run "every suite passes" pnpm exec turbo run test --concurrency=4 --continue + +echo "branded-fork.test.sh: ok" diff --git a/testing/coverage.test.sh b/testing/coverage.test.sh new file mode 100755 index 0000000..2c76722 --- /dev/null +++ b/testing/coverage.test.sh @@ -0,0 +1,154 @@ +#!/usr/bin/env bash +# EVERY COMPONENT THIS REPO SHIPS IS PLACED BY EXACTLY ONE PHASE +# (saas-bootstrap-engine BE5, Tier 0; ported from cirrus). +# +# `repo-blueprint.yaml` decides what a product is made of. A component that no +# module names is not a component a product gets — and nothing would say so. +# The failure is quiet and late: the fork builds, its CI goes green, and the +# missing piece surfaces when somebody looks for a worker that was never +# copied. +# +# orun already enforces the other half — every MODULE belongs to exactly one +# phase, and a module naming an unknown module is a parse error. What it cannot +# know is what this repository contains, because a blueprint declares what to +# place and not what exists. That is this file's job. +# +# bash + python3 + PyYAML. No network, no orun, no credential. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +echo "── every component against the blueprint that places it" +python3 - "$root" <<'PY' +import pathlib, sys + +try: + import yaml +except ImportError: + sys.exit("PyYAML is required for the coverage gate (pip install pyyaml)") + +root = pathlib.Path(sys.argv[1]) +problems = [] +def bad(m): problems.append(m) + +# A component directory this repository deliberately keeps to itself. Declared +# with its reason rather than skipped by a pattern: "tests/*" would also hide +# the thirteen component test suites a product genuinely needs, and the next +# baseline-only directory should have to be argued for in a diff. +# EMPTY, and that is the milestone's own result rather than an oversight. The +# one candidate was `tests/flows`, the bootstrap's contract suite, exempt +# because it tested `flows/` — which no product carried. `flows/` is gone, its +# suite is gone with it, and the gates that replace it live in `testing/` +# (which is not a component at all, and so is not a component this gate can +# miss). +# +# The map stays rather than the mechanism being deleted with no entry: the +# check below refuses an exemption whose directory is absent, so a stale entry +# cannot linger — and the next baseline-only directory should still have to be +# argued for in a diff rather than discovered as a re-added feature. +BASELINE_ONLY: dict[str, str] = {} + +bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text()) + +# Where each module takes its content from, and which phase places it. +placed_by = {} +for m in bp.get("modules") or []: + src = (m.get("from") or "").rstrip("/") + if src: + placed_by.setdefault(src, []).append(m["name"]) +phase_of = {n: ph["name"] for ph in (bp.get("phases") or []) for n in ph["modules"]} + +components = sorted( + p.parent.relative_to(root).as_posix() + for p in root.rglob("component.yaml") + if "node_modules" not in p.parts and ".git" not in p.parts +) +if not components: + sys.exit("no component.yaml anywhere — this check has gone blind") + +for comp in components: + modules = placed_by.get(comp, []) + reason = BASELINE_ONLY.get(comp) + + if reason and modules: + bad(f"{comp} is declared baseline-only ({reason}) and yet {modules[0]} " + f"places it — one of the two is wrong") + continue + if reason: + continue + if not modules: + bad(f"{comp} is a component and no module places it. Either add one, or " + f"declare it baseline-only in this file with the reason.") + continue + if len(modules) > 1: + bad(f"{comp} is placed by {len(modules)} modules ({', '.join(modules)}) " + f"— a component comes from one place") + continue + if modules[0] not in phase_of: + bad(f"{comp} is placed by {modules[0]}, which is in no phase") + +# The other direction: a module naming a path this repo does not have places +# nothing, silently. orun resolves `from` against the source tree and an absent +# path is an empty module, not an error. +for src, modules in sorted(placed_by.items()): + if not (root / src).exists(): + bad(f"module {modules[0]} takes its content from {src}, which does not " + f"exist — it would place nothing, and say nothing") + +# A directory named baseline-only must actually BE one, or the exemption is +# protecting nothing and will outlive the thing it was written for. +for comp in BASELINE_ONLY: + if not (root / comp).exists(): + bad(f"{comp} is declared baseline-only and does not exist — drop the entry") + +# ── WHAT `ignore` ACTUALLY EXCLUDES (BE6) ────────────────────────────────── +# +# orun matches an ignore entry two ways, and WHICH ONE depends on the entry: +# a pattern containing no glob metacharacter is compared against each path +# SEGMENT, and only a pattern containing one is compared against the whole +# relative path. So `apps/admin-worker/wrangler.jsonc` matches nothing at all — +# no segment is ever equal to it — and the entry is INERT while reading exactly +# like a rule. +# +# That was not hypothetical. Twelve such entries were inert in cirrus's +# blueprint, copied from this one, and a canary written to `apps/admin-worker/wrangler.jsonc` was +# placed straight into a product — which is the leak their comment says they +# exist to prevent. An `ignore` list that silently does nothing is worse than +# no list, because the comment above it reads as a defence. +for entry in bp.get("ignore") or []: + if "/" in entry and not any(c in entry for c in "*?["): + bad(f'ignore entry "{entry}" names a path and has no glob character, so orun ' + f'matches it against path SEGMENTS and it excludes nothing. Write it as ' + f'"**/{entry}".') + +# A workflow that runs the FACTORY must not ship to the factory's products. +# `github-workflows` copies the whole `.github` directory, so a lane added for +# this repository travels to every product built from it — and one that reads a +# path under `testing/` cannot work there, because `testing/` is not placed. +# ci.yml did exactly this here: its `flows-contract` job ran the factory's +# contract suite, and every product got a job that is red on its first PR. +ignored = set(bp.get("ignore") or []) +workflows = sorted((root / ".github" / "workflows").glob("*.y*ml")) +for wf in workflows: + text = wf.read_text(encoding="utf-8") + if "testing/" not in text: + continue + rel = f".github/workflows/{wf.name}" + if f"**/{rel}" not in ignored and rel not in ignored: + bad(f"{rel} reads a path under testing/, which no product is placed with, " + f"and is not in the blueprint's ignore list — so it ships into every " + f'product and fails there. Add "**/{rel}" to ignore.') + +if problems: + print("FAIL: the blueprint and this repository disagree about what a product is:", + file=sys.stderr) + for p in problems: + print(f" - {p}", file=sys.stderr) + sys.exit(1) + +shipped = len(components) - len(BASELINE_ONLY) +print(f" {shipped} of {len(components)} components placed, " + f"{len(BASELINE_ONLY)} baseline-only by declaration") +PY + +echo "coverage.test.sh: ok" diff --git a/testing/fleet-stubs.test.sh b/testing/fleet-stubs.test.sh new file mode 100755 index 0000000..9ac25ce --- /dev/null +++ b/testing/fleet-stubs.test.sh @@ -0,0 +1,162 @@ +#!/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/<name>/settings answers 200 for names in +# $tmp/exists, 404 otherwise (500 for a name containing "boom"); PUT +# .../scripts/<name> 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]) { + // `$dir/full` makes every create answer as an account at its Workers + // limit does — the condition that took lumen's own fleet down. + if (fs.existsSync(`${dir}/full`)) { + res.writeHead(403); + return res.end(JSON.stringify({ + success: false, + errors: [{ code: 10037, message: "You have exceeded the limit of 500 Workers on your account." }], + })); + } + 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 "── a placeholder it cannot create is not this component's failure" +# THE REGRESSION THIS GUARDS. This step runs in policy-worker's pre-deploy and +# every binding holder waits on policy-worker with `mode: enforced`, so exiting +# non-zero here failed the WHOLE fleet on both environments. It did exactly +# that on lumen's own main convergence (2026-10-25): the account was at its +# 500-Worker limit, `lumen-billing-worker-stage` could not be created, and ten +# lanes went red on a step belonging to a component that was itself fine. +: > "$tmp/exists"; : > "$tmp/puts"; : > "$tmp/full" +if out="$(node "$tool" --root "$root" --env stage 2>&1)"; then + ok "a create it cannot do exits 0 — the real deploys decide" +else + bad "a create it cannot do still fails the step (exit $?) — the fleet-wide regression is back" +fi +grep -q "could not create placeholder" <<<"$out" \ + && ok "it names each placeholder it could not create" \ + || bad "it is silent about the placeholders it could not create" +grep -q "10143" <<<"$out" \ + && ok "it says a still-missing target will fail its own deploy, by error code" \ + || bad "it does not say what happens next" +grep -q "Workers limit" <<<"$out" \ + && ok "it recognises an account at its Workers limit" \ + || bad "it does not recognise the 10037 limit answer" +[ ! -s "$tmp/puts" ] && ok "nothing was recorded as created" || bad "something was recorded as created" +rm -f "$tmp/full" + +echo "── the plan's side: every binding holder's targets exist before it deploys" +# Two ways a target can exist first, and each holder must have one: +# - it waits on policy-worker, whose pre-deploy creates a placeholder for +# every binding target (the fleet, whose workers bind each other); or +# - every Worker it binds is a component it waits on, enforced, so the real +# target has deployed before it does (the CMS, which binds only api-edge +# and lands two phases after it). +# A holder with neither is exactly the 10143 this tool exists to prevent. +holders=0; stubbed=0; ordered=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)) + how="$(python3 - "$root/apps/$app/component.yaml" "$t" "$root" <<'PY' +import pathlib, re, sys, yaml +spec = yaml.safe_load(open(sys.argv[1]))["spec"] +deps = {d["component"]: d for d in spec.get("dependsOn", [])} +if deps.get("policy-worker", {}).get("mode") == "enforced": + print("stubbed"); sys.exit(0) +root = pathlib.Path(sys.argv[3]) +# Which component deploys each Worker name: apps/<dir>'s wrangler `name`. +owner = {} +for w in list(root.glob("apps/*/wrangler.template.jsonc")) + list(root.glob("apps/*/wrangler.jsonc")): + m = re.search(r'"name":\s*"([^"]+)"', w.read_text()) + comp = yaml.safe_load((w.parent / "component.yaml").read_text())["metadata"]["name"] + if m: + owner[m.group(1)] = comp +targets = set(re.findall(r'"service":\s*"([^"]+)"', pathlib.Path(sys.argv[2]).read_text())) +if not targets: + sys.exit(f"{sys.argv[2]} has a services block and no service names — gone blind") +for svc in sorted(targets): + comp = owner.get(re.sub(r"-(dev|stage|prod)$", "", svc)) + if comp is None: + sys.exit(f"{svc} is deployed by no component in this repository") + if deps.get(comp, {}).get("mode") != "enforced": + sys.exit(f"{svc} ({comp}) is not an enforced dependency") +print("ordered") +PY +)" || { missing="$missing $app"; continue; } + case "$how" in stubbed) stubbed=$((stubbed + 1)) ;; ordered) ordered=$((ordered + 1)) ;; esac +done +[ -z "$missing" ] && ok "all $holders binding holders have their targets first: $stubbed wait on policy-worker, $ordered on every Worker they bind" || bad "a binding target may not exist when its holder deploys:$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/leak.test.sh b/testing/leak.test.sh new file mode 100755 index 0000000..e564958 --- /dev/null +++ b/testing/leak.test.sh @@ -0,0 +1,133 @@ +#!/usr/bin/env bash +# THE LEAK GATE — what a product carries, and what stays in the factory +# (saas-bootstrap-engine BE5, Tier 1; ported from cirrus). +# +# `BOOTSTRAP.md` describes a product as the thing lumen makes, not a copy of +# lumen. Until now the `ai-context` module copied the whole of `ai/context/`, +# so every product shipped this repository's planning state — `current.md`, +# `decisions.md`, `open-risks.md` — which after rebrand read as statements +# about the CUSTOMER's product, in the file an agent is pointed at first. And +# the `flows`, `agents` and `tooling` modules shipped the factory itself. +# +# WHAT THIS ASKS, AND WHAT IT CANNOT YET. It asks orun to DERIVE the placement +# — every file every phase would write — and gates that set. Derivation runs no +# hooks, contacts nothing and writes nothing. +# +# It does NOT place the tree and brand it; `testing/placement.test.sh` does. +# +# Needs: orun (the pinned version) + python3. No network, no credential. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +command -v orun >/dev/null || { echo "leak.test.sh needs orun on PATH" >&2; exit 1; } + +scratch="$(mktemp -d)" +trap 'rm -rf "$scratch"' EXIT + +echo "── deriving what every phase would place" +# Inputs come from the fixture, so a new required input fails HERE rather than +# in front of an operator. +sets=() +while IFS=$'\t' read -r k v; do sets+=( --set "$k=$v" ); done < <( + python3 - "$root/tests/fixtures/acme.json" <<'PY' +import json, sys +vals = json.load(open(sys.argv[1])) +for k, v in vals.items(): + if k.startswith("_"): + continue + print(f"{k}\t{'true' if v is True else 'false' if v is False else v}") +PY +) +orun new --blueprint "$root/repo-blueprint.yaml" --status --json \ + --out "$scratch/empty" "${sets[@]}" > "$scratch/status.json" + +python3 - "$scratch/status.json" "$root" <<'PY' +import json, pathlib, sys + +status = json.load(open(sys.argv[1])) +root = pathlib.Path(sys.argv[2]) +problems = [] +def bad(m): problems.append(m) + +# Against an empty output directory every file a phase places is "missing", so +# the union of those lists IS the product's file set. +placed = sorted({f for ph in status["phases"] for f in (ph.get("missing") or [])}) +if len(placed) < 500: + sys.exit(f"only {len(placed)} files derived — the tree is not a product") + +# ── the product's context pack, exactly ───────────────────────────────────── +# An exact set, not a prefix. That is the whole point of one module per file: +# a new file in ai/context/ cannot ship without somebody writing a module for +# it and saying so in a diff. +ALLOWED_AI = {"ai/context/deployment.md", "ai/context/operations.md"} +shipped_ai = {p for p in placed if p.startswith("ai/")} +for extra in sorted(shipped_ai - ALLOWED_AI): + bad(f"{extra} ships to the product and is this repository's own state") +for missing in sorted(ALLOWED_AI - shipped_ai): + bad(f"{missing} is declared a product file and would not ship") + +# ── the factory never ships ──────────────────────────────────────────────── +# `.vscode/tasks.json` is this repository's agent loop: it runs agents with +# their sandbox and approvals bypassed against `agents/orchestrator.md` and +# `ai/state.json`, which never ship (orun-cloud saas-build-panel BV4). +# `.baseline/` holds the templates of the product's README and AGENTS.md, +# which are placed under their own names, never from there. +NEVER = ("flows/", "agents/", "tasks/", "specs/", "testing/", "hooks/", + "docs/phases/", "tooling/rebrand/", "tooling/bootstrap/", + "tooling/fork/", "tooling/migrations/", ".baseline/", + ".vscode/tasks.json", + "FORKING.md", "BOOTSTRAP.md", "repo-blueprint.yaml", "blueprint.yaml") +for p in placed: + for never in NEVER: + if p == never or p.startswith(never): + bad(f"{p} would ship — it is the factory, not the product") + +# ── what an agent handed the product reads first ─────────────────────────── +# A product is ready for an agent to start in: its own front page, and an +# AGENTS.md at the root saying what to read and what not to touch. The build +# page's hand-off ends "Then clone <repo> and start building on it", and a +# product without one hands the agent a repository and nothing else. +for need in ("README.md", "AGENTS.md"): + if need not in placed: + bad(f"{need} would not ship — every product carries its own at the root") + +# ── and by content: PROVENANCE, which rebrand has no rule for ────────────── +# Deliberately NOT a search for "lumen". rebrand.mjs rewrites this +# repository's own name into the product's — that is its whole job — so +# flagging it here would mean failing on input rebrand is about to fix, and +# testing rebrand's work in the wrong place against the wrong tree. +# +# What rebrand cannot fix is a sentence about where the product CAME FROM. +# Cirrus shipped "Provenance — Cirrus from the Lumen baseline": rebrand turns +# the first name into the product's and leaves the rest standing, so the +# customer is told their product was forked from something they have never +# seen. This catches that prose appearing inside a file that ships. +import re +PROVENANCE = re.compile( + r"\bfork(ed)? (of|from)\b|\bbaseline (repo|repository|commit)\b", + re.I, +) +for rel in sorted(shipped_ai & ALLOWED_AI): + src = root / rel + if not src.exists(): + bad(f"{rel} is declared a product file and is not in this repository") + continue + for n, line in enumerate(src.read_text(errors="replace").splitlines(), 1): + if PROVENANCE.search(line): + bad(f"{rel}:{n} tells the product where the BASELINE came from, " + f"which rebrand cannot rewrite: {line.strip()[:70]}") + +if problems: + print("FAIL: the product would carry the baseline:", file=sys.stderr) + for p in problems: + print(f" - {p}", file=sys.stderr) + sys.exit(1) + +print(f" {len(placed)} files derived across every phase") +print(f" ai/context is exactly {len(ALLOWED_AI)} declared file(s)") +print(f" none of the {len(NEVER)} factory paths; " + f"no baseline provenance in the context pack") +PY + +echo "leak.test.sh: ok" diff --git a/testing/manifest.test.sh b/testing/manifest.test.sh new file mode 100755 index 0000000..3c51064 --- /dev/null +++ b/testing/manifest.test.sh @@ -0,0 +1,471 @@ +#!/usr/bin/env bash +# The manifest must state what THE BLUEPRINT does (saas-bootstrap-console +# BC2/BC3; repointed from the flows by saas-bootstrap-engine BE4, ported +# from cirrus). +# +# `blueprint.yaml` is the contract the platform's bootstrap door reads and the +# console renders screen for screen. A manifest that drifts is a console that +# lies — showing an operator secrets that will not be created, or a programme +# that will not be laid out, with nothing failing until a customer's build is +# already running. +# +# Every check compares the manifest to THE THING THAT DOES THE WORK, never to +# another copy of the same claim. `spec.source.tag` sat at `baseline-v1` against +# a live `baseline-v4` for three releases (and `baseline-v17` against +# `baseline-v27` in lumen — ten) because nothing compared it to anything that +# moved. A drift test between two files catches nothing. +# +# ## What the thing that does the work IS, now +# +# It used to be shell: `flows/common/create-secrets.sh`'s `create` calls, and +# the umbrella's `ensure-milestone` lines, grepped out of scripts. BE4 deleted +# those, and the work moved into `repo-blueprint.yaml` — so this file now reads +# the blueprint's own hooks. +# +# That is a STRONGER comparison, not a weaker one. Grepping a shell script for +# `create FOO cloudflare … workers-deploy` matched a line's shape; reading +# `orun.integrations/reconcile@v1`'s `with:` reads the declaration orun actually +# executes. The action's own documentation says as much — "a script walks that +# table calling create for each … it is a reconcile written out longhand, and +# this is the verb it was reaching for". +# +# TWO SHAPES OF REPO, one test. A repo may carry more than one baseline: stratus +# serves both the `stratus` and `stratus-coolify` registry rows from one tree. +# So every `blueprint*.yaml` at the root is checked. +# +# And a baseline need not have every mechanism. Stratus mints no secrets and +# lays out no milestones, so it declares neither block. That is allowed — but +# only BOTH-OR-NEITHER, checked in both directions: if the mechanism exists the +# block must match it, and if the block exists the mechanism must be there to +# realize it. "Absent" is never permission to skip a check silently; it is a +# fact that must agree with the other side. +# +# bash + python3 + PyYAML. No network, no fakes, no credential. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +echo "── blueprint manifests against the blueprint that realizes them" +python3 - "$root" <<'PY' +import pathlib, re, sys + +try: + import yaml +except ImportError: + sys.exit("PyYAML is required for the manifest contract test (pip install pyyaml)") + +root = pathlib.Path(sys.argv[1]) +problems = [] +def bad(m): problems.append(m) + +manifests = sorted(root.glob("blueprint*.yaml")) +if not manifests: + sys.exit("no blueprint*.yaml at the repo root — this check has gone blind") + +# ── what the blueprint actually mints, and what it actually lays out ────── +# +# One read of `repo-blueprint.yaml`, shared across a repo's baselines. A repo +# with no blueprint at the root has no mechanism to compare against, and that +# is a fact the both-or-neither rule below handles rather than a reason to skip. +bp_path = root / "repo-blueprint.yaml" +bp = yaml.safe_load(bp_path.read_text()) if bp_path.exists() else None +bp_phases = (bp or {}).get("phases") or [] + +def hooks_of(phase): + """Every hook a phase declares, in the order orun runs them.""" + h = phase.get("hooks") or {} + if isinstance(h, list): + return list(h) + return [x for slot in ("pre", "post", "await") for x in (h.get(slot) or [])] + +def uses(phase, action): + for hook in hooks_of(phase): + if (hook.get("uses") or "").startswith(action): + yield hook + +# 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 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") + +checked = [] +for path in manifests: + name = path.name + spec = (yaml.safe_load(path.read_text()) or {}).get("spec") or {} + def B(m): bad(f"{name}: {m}") + + # ── the field that cannot be true ───────────────────────────────────── + if "tag" in (spec.get("source") or {}): + B("spec.source.tag is back. The registry pins the tag; this file is fetched at it.") + + # ── blocks every baseline must carry ────────────────────────────────── + for key in ("source", "overview", "requires", "inputs", "bootstrap"): + if key not in spec: + B(f"spec.{key} is missing — the console renders it") + + # ── inputs v3: every input is collected by the console (BE3) ────────── + # + # `askedBy` is gone with the agent. It split inputs into ones a form + # collects and ones asked for in a session, and the second half no longer + # exists — so the field could only ever hold one value. + # + # The exemption it carried is what these checks replace: an `askedBy: + # agent` input needed no `pattern`, because prose asked for it and prose + # does not validate. + input_keys = {f.get("key") for f in (spec.get("inputs") or [])} + ACTION_ID = re.compile(r"^[a-z][a-z0-9.]*/[a-z][a-z0-9-]*@v[0-9]+$") + REBRAND = "tooling/rebrand/rebrand.mjs" + # THE KEY CHARSET THE PLATFORM'S PARSER ENFORCES, mirrored here. + # + # `INPUT_KEY_RE = /^[a-z][a-z0-9_]{0,38}$/` in orun-cloud's + # `blueprint-manifest.ts`. Nothing in this repository ran that parser: the + # `blueprint-parses` job reads `repo-blueprint.yaml` with ORUN, which + # accepts camelCase happily, and this file is a hand-rolled reader of the + # card. So a card key orun likes and the platform refuses passed every + # check here and failed at the pin: + # + # line 98: input key "githubOrg" must be lowercase letters, digits + # and underscores + # + # It cost a baseline tag — v6 was already cut and a baseline tag is never + # moved — which is the whole argument for mirroring the rule rather than + # trusting that the two readers agree. + # + # It also constrains `repo-blueprint.yaml`: a card key must be an input the + # blueprint accepts (checked below), so any input the CARD declares must be + # named in this charset on BOTH sides. The blueprint's own camelCase + # inputs — `epicSlug`, `orunWorkspace`, `pascalName` — are untouched, + # because the card does not declare them. + INPUT_KEY = re.compile(r"^[a-z][a-z0-9_]{0,38}$") + for i, field in enumerate(spec.get("inputs") or []): + key = field.get("key", f"#{i}") + if not INPUT_KEY.match(str(key)): + B(f"inputs[{key}] is not a key the platform's parser accepts — it " + f"must match ^[a-z][a-z0-9_]{{0,38}}$ (lowercase letters, digits " + f"and underscores). The console would refuse the whole manifest.") + if "askedBy" in field: + B(f"inputs[{key}] declares askedBy — there is no agent to ask, so " + f"every input is collected by the console") + if not field.get("pattern"): + B(f"inputs[{key}] declares no pattern — it is collected in a form " + f"and validated before Continue, so it must say what a valid " + f"value looks like") + + # from / derive / probe each answer "where does this value come from + # when nobody types it". Two of them is two answers. + sources = [k for k in ("from", "derive", "probe") if k in field] + if len(sources) > 1: + B(f"inputs[{key}] declares {' and '.join(sources)} — an input has " + f"one source") + + # A derivation must name inputs this manifest actually declares. + derive = field.get("derive") + if derive is not None: + refs = re.findall(r"\{([a-z][a-z0-9_]*)\}", derive) + if not refs: + B(f"inputs[{key}].derive has no {{key}} reference — a constant " + f"is a default, not a derivation") + for ref in refs: + if ref == key: + B(f"inputs[{key}].derive references itself") + elif ref not in input_keys: + B(f"inputs[{key}].derive references {{{ref}}}, which is not " + f"a declared input") + + # A DERIVATION HAS A SECOND IMPLEMENTATION, and they must agree. + # + # `rebrand.mjs` has computed this value since long before the manifest + # could say so: + # + # const apibaseurl = values.apibaseurl ?? `https://api.${productdomain}`; + # + # Both paths are live. The console resolves `derive` and the flow hands + # it down, so on a console bootstrap the manifest's rule wins; a phase + # run by hand passes nothing and rebrand's fallback wins. One rule, two + # implementations — which is the thing this file's header warns about, + # unless something holds them equal. This does. + # + # Since the console stopped asking for the domain, the card derives + # nothing: `apibaseurl` left it with `productdomain` (a card can only + # derive from inputs it declares), and rebrand's fallback alone picks + # the value — `https://api.<domain>`, or with no domain the product's + # prod edge on workers.dev, which placement.test.sh checks in a placed + # product. This stays for the next input that derives. + if derive is not None and (root / REBRAND).exists(): + js = (root / REBRAND).read_text(errors="replace") + for m in re.finditer(r"const (\w+) = values\.\w+ \?\? `([^`]+)`", js): + # `${productdomain}` there is `{productdomain}` here. + want = re.sub(r"\$\{([A-Za-z]+)\}", lambda g: "{" + g.group(1).lower() + "}", m.group(2)) + if m.group(1).lower() == key and want != derive: + B(f"inputs[{key}].derive is {derive!r} and {REBRAND} falls back " + f"to {want!r} — one value, two rules, and which one a " + f"product gets depends on whether the console resolved it") + + # A probe names an orun action. Shape only — this repository does not + # own the registry and cannot know which ids a runner has. The id being + # WELL-FORMED is what it can check; whether it is REGISTERED is the + # runner's answer, at parse time, where the real list lives. + probe = field.get("probe") + if probe is not None: + uses = (probe or {}).get("uses") + if not uses or not ACTION_ID.match(uses): + B(f"inputs[{key}].probe.uses is {uses!r} — not an action id " + f"(<namespace>/<verb>@v<major>)") + + # `from` says the CONSOLE already holds this value, so it renders no + # field for it (saas-bootstrap-console BC-K5). Two ways to get it + # wrong, and the platform refuses both — check them here too, so the + # mistake is caught in this repo rather than at a live bootstrap. + # + # A `connection.<provider>.<fact>` source is read from the connection + # the build is bound to, so the provider must be one the manifest + # requires — the platform's parser refuses it otherwise. + sources_known = ("repo.name", "repo.owner", "repo.fullName", + "connection.cloudflare.workersSubdomain") + src = field.get("from") + if src is not None and src not in sources_known: + B(f"inputs[{key}].from is {src!r} — must be one of {', '.join(sources_known)}") + if isinstance(src, str) and src.startswith("connection."): + provider = src.split(".")[1] + if provider not in ((spec.get("requires") or {}).get("integrations") or []): + B(f"inputs[{key}].from is {src!r} but spec.requires.integrations " + f"does not list {provider} — there is no connection to read it from") + + # ── secrets: BOTH or NEITHER, checked both ways ─────────────────────── + declared = {s.get("key"): (s.get("provider"), s.get("template")) for s in (spec.get("secrets") or [])} + if bp is None: + if declared: + B(f"declares {len(declared)} secret(s) but the repo has no " + f"repo-blueprint.yaml to mint them") + elif not blueprint_secrets: + if declared: + B(f"declares {len(declared)} secret(s) and repo-blueprint.yaml has no " + f"orun.integrations/reconcile@v1 hook to mint any") + else: + if "secrets" not in spec: + B("repo-blueprint.yaml mints keys and the manifest declares no secrets") + for k in sorted(set(blueprint_secrets) - set(declared)): + B(f"repo-blueprint.yaml mints {k} and the manifest does not declare it") + for k in sorted(set(declared) - set(blueprint_secrets)): + B(f"declares secret {k} and repo-blueprint.yaml never mints it") + for k in sorted(set(blueprint_secrets) & set(declared)): + if blueprint_secrets[k] != declared[k]: + B(f"{k}: manifest says provider/template {declared[k]}, " + f"repo-blueprint.yaml mints it as {blueprint_secrets[k]}") + + # ── bootstrap: what is left of it, and what BE4 removed ─────────────── + # + # `umbrella` and `agentBrief` named two files BE4 deleted. orun-cloud + # BE-K1c made both OPTIONAL in the manifest contract for exactly this, so + # this file no longer declares them — and must not, because a path that + # does not exist is the drift this whole test is about. + boot = spec.get("bootstrap") or {} + for field in ("umbrella", "agentBrief"): + rel = boot.get(field) + if rel is None: + continue + B(f"bootstrap.{field} is back, naming {rel}. The shell layer is gone " + f"(BE4): every phase is declared in repo-blueprint.yaml and orun runs " + f"it, so there is no umbrella to name and no session to brief.") + if not boot.get("expectedMinutes"): + B("bootstrap.expectedMinutes is missing — the console renders it") + # …and it is the budget the PHASES declare, not a second guess at it. + # The card said 75 while the phases summed to 84 (orun-cloud + # saas-build-panel BV4), so a build page that shows both — the whole + # build's budget, and each phase's — disagreed with itself. No build has + # been timed end to end under the blueprint (docs/phases/TIMINGS.md): + # both numbers are budgets, and they move together. + elif bp_phases: + want = sum(int(ph.get("expectedMinutes") or 0) for ph in bp_phases) + if int(boot["expectedMinutes"]) != want: + B(f"bootstrap.expectedMinutes is {boot['expectedMinutes']}, but " + f"repo-blueprint.yaml's phases budget {want} between them — " + f"one build, one budget") + + # ── …and what BE-K1e added in their place ───────────────────────────── + # + # With no umbrella and no brief, `blueprint` is the ONLY entry point: it + # names the document whose phases a runner places after fetching this repo + # at its pinned tag. The registry row's `manifestPath` names the console + # CARD — this file — so without this key a runner has nothing to run. + # + # Checked the way everything else here is checked: against the thing that + # does the work, not against another copy of the claim. The file must + # exist, and it must be the one that actually declares the phases — a path + # to some other YAML would satisfy a mere existence check and fail a real + # bootstrap at the only moment that matters. + build = boot.get("blueprint") + if not build: + B("bootstrap.blueprint is missing. This baseline has no umbrella and " + "no agentBrief (BE4), so nothing else names the document a runner " + "places — a fetch at the pinned tag would find no entry point.") + else: + target = root / build + if not target.is_file(): + B(f"bootstrap.blueprint names {build}, which does not exist") + else: + try: + doc = yaml.safe_load(target.read_text()) or {} + except yaml.YAMLError as exc: + doc = {} + B(f"bootstrap.blueprint names {build}, which does not parse: {exc}") + if doc and not (doc.get("phases") or (doc.get("spec") or {}).get("phases")): + B(f"bootstrap.blueprint names {build}, which declares no phases. " + f"A runner would fetch it and place nothing.") + if doc and doc.get("kind") != "Blueprint": + B(f"bootstrap.blueprint names {build}, whose kind is " + f"{doc.get('kind')!r} rather than Blueprint") + + # ── every declared input is one the BLUEPRINT accepts ───────────────── + # + # This used to check the manifest's keys against the UMBRELLA's inputs, + # because a flow was what consumed them and orun's flow engine fails closed + # on an undeclared `--set`. The blueprint is what consumes them now, and it + # fails closed the same way: + # + # ✕ unknown input "reponame" (not declared in blueprint inputs) + # + # That equivalence is why open question 10 had to be settled in the same + # commit that deleted the flows: the umbrella's lowercase input names were + # the ONLY thing translating this file's keys into the blueprint's + # camelCase ones, so deleting it without renaming would have left every key + # refused. + # + # ONE DIRECTION ONLY. The blueprint declares more than this file does — + # `githuborg`, `epicSlug`, `orunWorkspace` and the identity + # defaults are how a BUILD is driven, not what a product is configured + # with. What must hold is that nothing this file declares arrives at an + # engine that cannot take it. + if bp is not None: + bp_inputs = set((bp.get("inputs") or {}).keys()) + if not bp_inputs: + B("repo-blueprint.yaml declares no inputs — this check has gone blind") + for key in [f.get("key") for f in (spec.get("inputs") or [])]: + if key and key not in bp_inputs: + B(f"inputs[{key}] is not an input of repo-blueprint.yaml — the " + f"console would resolve it and the engine would refuse it " + f"(orun fails closed on an undeclared --set)") + + # ── …AND THE OTHER DIRECTION, for REQUIRED inputs only ─────────────── + # + # The check above is one-directional on purpose: the blueprint declares + # more than this card does, because `epicSlug` and the identity + # defaults are how a BUILD is driven rather than what a product is + # configured with. That tolerance had no floor, and `githuborg` fell + # through it — `required: true` in the blueprint, absent from this card, + # so a platform build resolved the card's inputs, handed them to the + # runner and died on its first step: + # + # ✕ input "githuborg" is required + # + # An input the blueprint REQUIRES and gives no default to is one somebody + # must supply, and the only things that supply inputs to a hosted build + # are this card's fields and its `from`/`derive` sources. So "more" may + # not include one of those. + # + # Defaulted inputs stay out of it: a default IS the supply. + if bp is not None: + for key, spec_in in (bp.get("inputs") or {}).items(): + if not isinstance(spec_in, dict): + continue + if not spec_in.get("required"): + continue + if "default" in spec_in: + continue + if key not in input_keys: + B(f"repo-blueprint.yaml requires input {key!r} and gives it no " + f"default, and this card does not declare it — a hosted build " + f"would collect every field it shows and still die with " + f'\'input "{key}" is required\'') + + # ── programme: BOTH or NEITHER, against the blueprint's own hooks ───── + # + # A milestone is what a phase CLUBS ITS TASK UNDER, which the phase states + # as `orun.task/ensure@v1`'s `milestone:`. Reading that is why nine phases + # correctly produce seven milestones: `03-infrastructure-database` and + # `04-workers-restore` name `03-infrastructure` and `04-workers`, because + # each is the second landing of one unit of work. + # + # Distinct, in phase order. The old check grepped the umbrella's + # `ensure-milestone` lines for the same list. + ensured, seen = [], set() + for phase in bp_phases: + for hook in uses(phase, "orun.task/ensure@v1"): + # Not `name`: that is the manifest's file name, which the summary + # line below prints (it printed the last milestone instead). + ms_name = ((hook.get("with") or {}).get("milestone") or "") + ms_name = ms_name.replace("{{ .phase.name }}", phase.get("name", "")).strip() + if ms_name and ms_name not in seen: + seen.add(ms_name) + ensured.append(ms_name) + + # A phase's `when:` is what made a milestone conditional; the umbrella + # carried the same fact as a shell `[ != "true" ] ||` guard. + conditional = { + p_["name"] for p_ in bp_phases + if p_.get("when") and p_.get("name") in seen + } + + prog = spec.get("programme") + if not ensured: + if prog: + B("declares a programme but repo-blueprint.yaml opens no milestones") + else: + if not prog: + B(f"repo-blueprint.yaml opens {len(ensured)} milestone(s) and the " + f"manifest declares no programme") + else: + ms = prog.get("milestones") or [] + if any(not isinstance(m, dict) or "name" not in m for m in ms): + B("every programme.milestones entry must be a mapping with a `name` " + "(so a conditional one can carry its `when`)") + else: + names = [m["name"] for m in ms] + dcond = {m["name"] for m in ms if m.get("when")} + if names != ensured: + B(f"programme.milestones {names} != repo-blueprint.yaml's {ensured}") + if dcond != conditional: + B(f"conditional milestones disagree: manifest says {sorted(dcond) or '[]'}, " + f"the blueprint guards {sorted(conditional) or '[]'}") + slug = ((bp.get("inputs") or {}).get("epicSlug") or {}).get("default") + if slug and prog.get("epicSlug") != slug: + B(f"programme.epicSlug {prog.get('epicSlug')!r} != the blueprint's " + f"default {slug!r}") + + # ── verify is optional, but must not name an input that is not there ── + input_keys = {f.get("key") for f in (spec.get("inputs") or [])} | {"env"} + for url in ((spec.get("verify") or {}).get("urls") or []): + for ph in re.findall(r"\{([a-zA-Z0-9_]+)\}", url): + if ph not in input_keys: + B(f"verify url interpolates {{{ph}}}, which is not an input") + + checked.append((name, len(declared), len((prog or {}).get("milestones") or []))) + +if problems: + print("FAIL: a manifest and the blueprint disagree:", file=sys.stderr) + for p in problems: + print(f" - {p}", file=sys.stderr) + sys.exit(1) + +for name, ns, nm in checked: + print(f" {name}: {ns} secret(s), {nm} milestone(s) agree with repo-blueprint.yaml") +PY + +echo "manifest.test.sh: ok" 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/<TASK-KEY>-<phase>`, 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/<task>-<slug>" + 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 new file mode 100755 index 0000000..0be1ff8 --- /dev/null +++ b/testing/phases.test.sh @@ -0,0 +1,388 @@ +#!/usr/bin/env bash +# The phases in `repo-blueprint.yaml` must be the phases the bootstrap runs +# (saas-bootstrap-engine BE1, ported from cirrus). +# +# Before BE1 this could not be checked, because the two were different +# documents: `tooling/blueprint/split-phases.py` derived eight +# `flows/phases/*/blueprint.yaml` slices from this file and re-mapped their +# names to folders through a table inside the script. A mapping table in a +# generator is a fact nothing compares to anything, and it was wrong — this +# file declared `workspace` last while the folder it became, `01-scaffold`, +# runs first. +# +# THE PARTITION BELOW IS THE PRE-MIGRATION TRUTH. It is what the eight slices +# actually placed, read off them at the commit that deleted them. Its job is to +# fail if a later edit quietly moves a module between phases: the bootstrap's +# order is load-bearing (a worker cannot deploy before its Hyperdrive exists) +# and a module that drifts one phase earlier fails at deploy time, live, with +# nothing in this repo having looked wrong. +# +# bash + python3 + PyYAML. No network, no fakes, no credential. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +echo "── repo-blueprint.yaml phases against what the bootstrap runs" +python3 - "$root" <<'PY' +import pathlib, re, sys + +try: + import yaml +except ImportError: + sys.exit("PyYAML is required for the phase contract test (pip install pyyaml)") + +root = pathlib.Path(sys.argv[1]) +problems = [] +def bad(m): problems.append(m) + +bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text()) +phases = bp.get("phases") or [] +if not phases: + sys.exit("repo-blueprint.yaml declares no phases — this check has gone blind") + +# What the eight slices placed, before they were deleted. +WAS = { + # `ai-context` became `ai-deployment` + `ai-operations`: the module copied + # the whole of ai/context/, which carried this repository's own planning + # state (current.md, decisions.md, open-risks.md) into every product. The + # partition below is the pre-migration truth for everything else; this + # line and the 03 split below are deliberate, argued changes and are + # recorded as such. + # + # `vscode` is gone the same way: it shipped `.vscode/tasks.json`, this + # repository's agent loop, which runs agents with their sandbox bypassed + # 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-package-json", + "root-pnpm-lock", "root-pnpm-workspace", "root-readme", "root-turbo", + "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"], + # The slice placed all four data-plane modules and landed without waiting, + # because two of them could never pass on the PR: hyperdrive and db-migrate + # plan against supabase's job outputs, which exist only after the apply on + # main. They moved to `03-infrastructure-database`, which runs after that + # apply, so every phase's PR can be verified before it merges. + "03-infrastructure": ["cloudflare-kv", "supabase"], + "03-infrastructure-database": ["cloudflare-hyperdrive", "db-migrate"], + "04-workers": ["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"], + "05-edge": ["api-edge", "api-edge-tests"], + # `cloudflare-domain` was 07-domain's one module. It folded into 06-console + # when the `domain` input went: the component ships parked (it subscribes + # to no environment until an owner wires a zone), so a landing of its own + # deployed nothing, and an on/off switch for a component that is already + # off was one more question for nothing. It moved whole, and nothing else + # moved with it. + "06-console": ["cloudflare-domain", "web-console-next", "web-console-next-tests"], +} +# Declared since BE1 and placing nothing: their work is hooks. `discovery-roots` +# is likewise new — the empty apps/infra/packages/tests roots orun's repo-scale +# gate requires, which the scaffold flow used to create with a mkdir. +# `platform-limits-tests` is likewise new here: a component the baseline grew +# after the slices were cut, which no slice placed (the coverage gate found it). +# `root-agents` is the product's AGENTS.md (saas-build-panel BV4): the page an +# agent handed the product reads first. +# +# THE CMS, this baseline's own addition to the Lumen partition above, and +# placed where its edges put it rather than in a phase of its own: +# `cloudflare-r2-cms` reads nothing anyone publishes, so it lands with the +# first half of the data plane; `cloudflare-hyperdrive-cms` plans against +# supabase's outputs exactly as `cloudflare-hyperdrive` does, so it lands +# with it; and Payload itself (`cms`, with the suite its lane runs) is the +# console — the console URL redirects into it — so it lands in 06-console. +ADDED = {"01-scaffold": ["discovery-roots", "root-agents"], "05-edge": ["platform-limits-tests"], + "03-infrastructure": ["cloudflare-r2-cms"], + "03-infrastructure-database": ["cloudflare-hyperdrive-cms"], + "06-console": ["cms", "cms-tests"]} +HOOK_ONLY = {"08-docs"} + +by_name = {p["name"]: p for p in phases} +names = [p["name"] for p in phases] + +# ── the order IS the execution order ────────────────────────────────────── +if names != sorted(names): + bad(f"phases are not in execution order: {names}. The numbered name IS the " + f"order; a phase out of sequence is a barrier in the wrong place.") + +# ── the partition has not drifted ───────────────────────────────────────── +for name, was in WAS.items(): + if name not in by_name: + bad(f"phase {name} is gone — the bootstrap ran it before BE1") + continue + now = sorted(by_name[name].get("modules") or []) + want = sorted(was + ADDED.get(name, [])) + if now != want: + moved_in = sorted(set(now) - set(want)) + moved_out = sorted(set(want) - set(now)) + bad(f"phase {name} no longer places what it placed: " + f"gained {moved_in or '[]'}, lost {moved_out or '[]'}") + +for name in HOOK_ONLY: + if name not in by_name: + bad(f"phase {name} is missing") + elif by_name[name].get("modules"): + bad(f"phase {name} places modules — it is declared as hooks only") + +# ── nothing may GATE on a phase the tree cannot answer for ──────────────── +# +# A hook-only phase places no files, so orun derives it as `unknown` rather +# than `done` (orun BE-O10) — deliberately, because its work is a landing in +# the task plane and a live deployment, neither of which the product repo can +# be asked about. `requires.phases` fails closed on `unknown`. So a requirement +# naming one can NEVER be satisfied, and the phase declaring it refuses for the +# whole of a real bootstrap. +# +# BE1 shipped exactly that: `05-edge` required `04-workers-restore`, and the +# epic's own open question 7 said "nothing declares one on them" — true of the +# intent, false of the file, with nothing comparing the two. It surfaced only +# once orun BE-O12 made the phases before it pass: +# +# ✕ phase "05-edge" requires 04-workers-restore (unknown) +# +# Naming the hook-only phase's own predecessor instead loses no ordering: phase +# order in this document is what sequences a run, and `requires` is the gate +# that catches a phase run against a tree where its predecessor never happened. +for p in phases: + for need in ((p.get("requires") or {}).get("phases") or []): + if need in HOOK_ONLY: + bad(f"phase {p['name']} requires {need}, which places no files — orun " + f"derives a hook-only phase as `unknown` and requires.phases " + f"fails closed on it, so this gate can never pass. Require its " + f"predecessor instead.") + +# ── every phase says what it is and what to budget ──────────────────────── +for p in phases: + for field in ("title", "expectedMinutes"): + if not p.get(field): + bad(f"phase {p['name']} declares no {field} — an operator reads both") + if not (p.get("hooks") or {}): + bad(f"phase {p['name']} declares no hooks — a phase that only places " + f"files still has to land them") + +# ── every contract a hook names exists ──────────────────────────────────── +def hooks_of(p): + h = p.get("hooks") or {} + if isinstance(h, list): + return list(h) + return [x for slot in ("pre", "post", "await") for x in (h.get(slot) or [])] + +for p in phases: + for h in hooks_of(p) + [x for x in ((p.get("requires") or {}).get("probe") or [])]: + rel = (h.get("with") or {}).get("contract") + if rel and not (root / rel).exists(): + bad(f"phase {p['name']} hook {h.get('id')} names contract {rel}, " + f"which does not exist") + +# ── every phase has a documentation page, and every page a phase ────────── +# 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. `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 = {"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: + want = DOC_SHARED.get(p["name"], p["name"]) + if want not in pages: + bad(f"phase {p['name']} has no page at docs/phases/{want}.md") +for page in sorted(pages): + if page not in by_name and page not in DOC_SHARED.values(): + bad(f"docs/phases/{page}.md documents a phase repo-blueprint.yaml " + f"does not declare") + +# ── narration: authored here, printed from state (BE2) ──────────────────── +# +# The plan put these checks in manifest.test.sh. They are here instead, and +# the reason is the same one that makes the checks worth having: that test is +# about `blueprint.yaml`, the CONSOLE manifest, and what it promises an +# operator. Narration is a property of `repo-blueprint.yaml`, so putting the +# checks there would have meant reading a second file in a test named after +# the first. +# +# What orun's event stream actually carries, which is what a line may name. +META_AT = { + # start/await/failed render against the phase's opening meta … + "start": {"files", "expectedMinutes"}, + "await": {"files", "expectedMinutes"}, + "failed": {"files", "expectedMinutes"}, + # … and only `done` has run to a close, so only `done` knows how long it + # took or what comes next. A `start` line naming `elapsed` would render + # empty at the one moment it was written for. + "done": {"files", "expectedMinutes", "elapsed", "next"}, +} +STATE_WORDS = {"done", "failed", "complete", "completed", "succeeded", "skipped"} +PHASE_KEYS = {"name", "title"} +input_keys = set((bp.get("inputs") or {}).keys()) + +# THE WORKSPACE COMES FROM THE BUILD. A console build cannot send +# `orunWorkspace` (the manifest's input keys are lowercase, and the console +# holds only repository facts), so without `from: workspace` it is empty +# there, and phase 01 writes `workspace: ws_SET_ME` into the product, points +# every secret ref at the repository's name, and links with `--org ""`. +# orun >= v2.58.11 fills it from the workspace the build runs in. +ws_input = (bp.get("inputs") or {}).get("orunWorkspace") or {} +if ws_input.get("from") != "workspace": + bad("inputs.orunWorkspace must declare `from: workspace` — a console build has no other way to say it") + +def strip_expressions(line): + out, rest = [], line + while True: + i = rest.find("{{") + if i < 0: + out.append(rest) + return "".join(out) + out.append(rest[:i]) + j = rest.find("}}", i) + if j < 0: + return "".join(out) + rest = rest[j + 2:] + +def refs(line): + """Every `.a.b` path inside an expression.""" + found = [] + for expr in re.findall(r"\{\{(.*?)\}\}", line, re.S): + found += re.findall(r"\.([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)", expr) + return found + +def check_line(where, line, slot, hook_ids): + # Rule 2: prose may describe the world, never assert the run's state. + prose = strip_expressions(line).lower() + for w in STATE_WORDS: + if re.search(rf"\b{w}\b", prose): + bad(f"{where} asserts {w!r} — `state` is the truth and narration is " + f"the caption. Describe the world, not the run.") + # Rule 3: every reference resolves against what the engine actually emits. + for ref in refs(line): + parts = ref.split(".") + root = parts[0] + if root == "phase": + if len(parts) != 2 or parts[1] not in PHASE_KEYS: + bad(f"{where} names .{ref}; a phase carries {sorted(PHASE_KEYS)}") + elif root == "inputs": + if len(parts) != 2 or parts[1] not in input_keys: + bad(f"{where} names .{ref}, which is not a declared input") + elif root == "meta": + allowed = META_AT.get(slot, META_AT["start"]) + if len(parts) != 2 or parts[1] not in allowed: + bad(f"{where} names .{ref}; the {slot} event carries " + f"{sorted(allowed)}") + elif root == "hooks": + if len(parts) < 2 or parts[1] not in hook_ids: + bad(f"{where} names .{ref}; this phase has no hook {parts[1] if len(parts)>1 else '?'!r}") + else: + bad(f"{where} names .{ref}; narration may reference phase, inputs, " + f"meta and hooks") + +for p in phases: + n = p.get("narrate") or {} + ids = {h.get("id") for h in hooks_of(p)} + for slot in ("start", "await", "done", "failed"): + line = n.get(slot) + # `await` is deliberately NOT authored (saas-build-panel BV4; rule + # below): orun generates "<title>: <what it waits on>" from its own + # reason, which an authored line cannot match. + if not line and slot == "await": + continue + if not line: + bad(f"phase {p['name']} declares no narrate.{slot} — an operator sees " + f"a generated line instead of the one this baseline meant") + continue + check_line(f"phase {p['name']} narrate.{slot}", line, slot, ids) + + # An `await` is the one place an operator is left waiting with nothing + # happening on screen, so it is the one place a line is not optional. + for h in ((p.get("hooks") or {}).get("await") or []): + line = h.get("narrate") + if not line: + bad(f"phase {p['name']} await hook {h.get('id')} declares no narrate " + f"— a wait with no words reads as a stalled build") + continue + check_line(f"phase {p['name']} hook {h.get('id')} narrate", line, "done", ids) + + for slot in ("pre", "post"): + for h in ((p.get("hooks") or {}).get(slot) or []): + if h.get("narrate"): + check_line(f"phase {p['name']} hook {h.get('id')} narrate", + h["narrate"], "start", ids) + +# ── the lines a build page shows (orun-cloud saas-build-panel BV4) ──────── +# +# The console's build panel prints these verbatim, so three rules hold them +# true at the moment they are shown. +# +# A phase's `await` line is ALSO the line of a `waiting` event raised by its +# `requires.probe` — before any of its hooks has run. "Terraform is applying" +# was printed while 03 waited for a provider connection. Authored, it guesses; +# left out, orun writes "<title>: <what it waits on>" from its own reason (an +# older engine, "<phase> is waiting."), which is true whatever it waits on. A +# generic authored line does not fix it: the reasons are whole clauses, so +# "Waiting on {{ .meta.waitingOn }}" renders "Waiting on waiting for github +# to be connected…". +for p in phases: + if (p.get("narrate") or {}).get("await"): + bad(f"phase {p['name']} authors narrate.await — it is also the line while " + f"a requires.probe waits, and only the engine knows what it waits on. " + f"Leave it out; orun generates it from the reason.") + +# A landing names the pull request it merged, or says there was nothing to +# land (a re-run over a main that has the phase already), and labels its PR's +# row on the page. +for p in phases: + for h in hooks_of(p): + if (h.get("uses") or "") != "orun.pr/land@v1": + continue + where = f"phase {p['name']} hook {h.get('id')}" + if not str(h.get("label") or "").strip(): + bad(f"{where} declares no label — its pull request's row on the build page has no name") + line = h.get("narrate") or "" + hid = h.get("id") + for out in ("landed", "number"): + if f".hooks.{hid}.outputs.{out}" not in line: + bad(f"{where} narrate does not read .hooks.{hid}.outputs.{out} — a landing " + f"line names its PR and says when there was nothing to land") + +# The keys a build page reads (orun BV3) have exact shapes. Older orun ignores +# them, which is what makes them safe to add — and also why a wrong shape +# would go unnoticed until a reader looked for it. +SHAPES = {"label": str, "pin": bool, "quiet": bool} +for p in phases: + for h in hooks_of(p) + list((p.get("requires") or {}).get("probe") or []): + for key, typ in SHAPES.items(): + if key in h and not isinstance(h[key], typ): + bad(f"phase {p['name']} hook {h.get('id')} {key}: must be a " + f"{typ.__name__}, got {h[key]!r}") + +# ── what BE1 and BE4 deleted stays deleted ──────────────────────────────── +if (root / "flows").exists(): + bad("flows/ is back — the bootstrap is the blueprint, and every mechanism " + "that layer carried is a typed action in the orun binary (BE4)") +if (root / "tooling" / "blueprint" / "split-phases.py").exists(): + bad("split-phases.py is back — orun's phase overlay refuses the cross-phase " + "edge the splitter used to prune") + +if problems: + print("FAIL: the blueprint's phases and the bootstrap disagree:", file=sys.stderr) + for p in problems: + print(f" - {p}", file=sys.stderr) + sys.exit(1) + +placed = sum(len(p.get("modules") or []) for p in phases) +narrated = sum(len(p.get("narrate") or {}) for p in phases) +narrated += sum(1 for p in phases for h in hooks_of(p) if h.get("narrate")) +print(f" {len(phases)} phases, {placed} modules, " + f"{len(HOOK_ONLY)} hook-only — in execution order") +print(f" {narrated} authored narration lines, every reference resolving") +PY + +echo "phases.test.sh: ok" diff --git a/testing/placement.test.sh b/testing/placement.test.sh new file mode 100755 index 0000000..7c9c9c3 --- /dev/null +++ b/testing/placement.test.sh @@ -0,0 +1,360 @@ +#!/usr/bin/env bash +# TIER 1, THE OTHER HALF — the tree is placed, branded, and made to answer +# (saas-bootstrap-engine BE5b; ported from cirrus). +# +# BE5a could only gate the DERIVED placement: a whole-blueprint `orun new` +# refused before writing a byte, because every phase's `requires` was checked +# up front and `02-foundation` asked whether `01-scaffold` was on disk during +# the run about to write it. orun BE-O11 fixed that, and BE-O12 fixed what it +# then exposed — that a BRANDED predecessor reads `drifted`, which the gate was +# refusing, and which `--resume` was silently overwriting back to the baseline. +# +# So this file does what the design's Tier 1 asks and BE5a could not: +# +# 1. place the whole blueprint from tests/fixtures/acme.json, offline; +# 2. assert the gates orun runs INSIDE that placement actually ran — the +# two-parser check on every generated component.yaml, and `orun validate` +# + `orun plan --dry-run` in the produced tree. They come free with a +# placement, which is exactly why they need asserting: a future orun that +# stopped running them would weaken this tier in silence, and BE1a exists +# because that already happened once with a version pin; +# 3. brand it as `01-scaffold`'s hook chain does, then `rebrand.mjs --verify`; +# 4. run the leak rules over the REAL FILES rather than the derivation; +# 5. check the API base and the domain the product ends up with: built with +# no domain, as a console build is, its CLI defaults to its own prod edge +# on workers.dev and the domain's places carry `<reponame>.example.com`; +# 6. THE PHASED SEQUENCE THROUGH A REBRAND: place 01, brand, then place the +# phases that follow. This is the step no test in this repository has ever +# taken, and it is where BE-O12's two defects lived. +# +# Needs: orun (the pinned version) + node + python3 + git. No network, no +# credential. Nothing here contacts a provider: placement writes files, and +# since BE-O12 a run with hooks off does not probe. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +command -v orun >/dev/null || { echo "placement.test.sh needs orun on PATH" >&2; exit 1; } +command -v node >/dev/null || { echo "placement.test.sh needs node for rebrand" >&2; exit 1; } + +scratch="$(mktemp -d)" +trap 'rm -rf "$scratch"' EXIT +fails=0 +fail() { echo " ✕ $*" >&2; fails=$((fails + 1)); } + +# The fixture is the source of inputs, so a new required input fails HERE rather +# than in front of an operator. +sets=() +while IFS=$'\t' read -r k v; do sets+=( --set "$k=$v" ); done < <( + python3 - "$root/tests/fixtures/acme.json" <<'PY' +import json, sys +vals = json.load(open(sys.argv[1])) +for k, v in vals.items(): + if k.startswith("_"): + continue + print(f"{k}\t{'true' if v is True else 'false' if v is False else v}") +PY +) + +# orun's repo-scale gate discovers apps/infra/packages/tests, and a missing root +# is a hard failure. `discovery-roots` places the .gitkeep files but the gate +# runs against the directory, so they exist before the run — the same order +# 01-scaffold's workflow used. +tree="$scratch/product" +mkdir -p "$tree"/{apps,infra,packages,tests} +for d in apps infra packages tests; do touch "$tree/$d/.gitkeep"; done + +echo "── placing the whole blueprint (offline, no credential)" +if ! orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" "${sets[@]}" \ + > "$scratch/place.log" 2>&1; then + echo "FAIL: the placement did not run" >&2 + tail -20 "$scratch/place.log" >&2 + exit 1 +fi + +# ── the gates that ride inside the placement ─────────────────────────────── +# `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" +placed_count="$(find "$tree" -type f -not -path "*/.orun/*" | wc -l | tr -d ' ')" +[ "$placed_count" -ge 500 ] || fail "only $placed_count files placed — that is not a product" + +echo " $placed_count files placed; the repo-scale gate ran" + +# ── brand it, exactly as 01-scaffold's hooks do ──────────────────────────── +echo "── branding, then rebrand --verify" +( + cd "$tree" + git init -q -b main + git config user.email t@example.invalid + git config user.name "tier one" + printf 'baseline/\n.orun/\n' >> .gitignore + git add -A +) >/dev/null 2>&1 +if ! (cd "$tree" && node "$root/tooling/rebrand/rebrand.mjs" \ + --values .rebrand/values.json --allow-dirty) > "$scratch/brand.log" 2>&1; then + echo "FAIL: rebrand did not complete" >&2 + tail -20 "$scratch/brand.log" >&2 + exit 1 +fi +if ! (cd "$tree" && node "$root/tooling/rebrand/rebrand.mjs" \ + --values .rebrand/values.json --verify) > "$scratch/verify.log" 2>&1; then + echo "FAIL: rebrand --verify found baseline identity left in the product" >&2 + tail -20 "$scratch/verify.log" >&2 + exit 1 +fi +echo " branded; no baseline-identity residue" + +# ── the leak rules, over the files rather than the derivation ────────────── +echo "── what the product actually carries" +python3 - "$tree" "$root" <<'PY' +import pathlib, re, sys +tree, root = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]) +problems = [] +def bad(m): problems.append(m) + +placed = sorted( + str(p.relative_to(tree)) + for p in tree.rglob("*") + if p.is_file() and ".git" not in p.parts and ".orun" not in p.parts +) + +# An exact set, not a prefix — the point of one module per file is that a new +# file in ai/context/ cannot ship without a module and a diff. +ALLOWED_AI = {"ai/context/deployment.md", "ai/context/operations.md"} +shipped_ai = {p for p in placed if p.startswith("ai/")} +for extra in sorted(shipped_ai - ALLOWED_AI): + bad(f"{extra} shipped and is this repository's own state") +for missing in sorted(ALLOWED_AI - shipped_ai): + bad(f"{missing} is declared a product file and did not ship") + +NEVER = ("flows/", "agents/", "tasks/", "specs/", "testing/", "hooks/", + "docs/phases/", "tooling/rebrand/", "tooling/bootstrap/", + "tooling/fork/", "tooling/migrations/", ".baseline/", + ".vscode/tasks.json", + "FORKING.md", "BOOTSTRAP.md", "repo-blueprint.yaml", "blueprint.yaml") +for p in placed: + for never in NEVER: + if p == never or p.startswith(never): + bad(f"{p} shipped — it is the factory, not the product") + +# PROVENANCE, over the BRANDED tree. Deliberately not a search for "lumen": +# rebrand rewrites this repository's name into the product's, so flagging it +# would fail on input rebrand has already fixed. What rebrand has no rule for +# is a sentence about where the baseline came from — and unlike the leak gate, +# which can only read this repository's copy of the two files, this reads what +# the product ended up with, after every rewrite. After branding, "lumen" is +# ALSO a leftover here — rebrand --verify above owns that verdict. +PROVENANCE = re.compile( + r"\bfork(ed)? (of|from)\b|\bbaseline (repo|repository|commit)\b", re.I) +for rel in sorted(shipped_ai & ALLOWED_AI): + for n, line in enumerate((tree / rel).read_text(errors="replace").splitlines(), 1): + if PROVENANCE.search(line): + bad(f"{rel}:{n} tells the product where the BASELINE came from: " + f"{line.strip()[:70]}") + +if problems: + print("FAIL: the product carries the baseline:", file=sys.stderr) + for p in problems: + print(f" - {p}", file=sys.stderr) + sys.exit(1) +print(f" {len(placed)} product files; ai/context is exactly " + f"{len(ALLOWED_AI)}; no factory, no provenance prose") +PY + +# ── the pages an agent starts from, in the product ───────────────────────── +# README.md and AGENTS.md are rendered from `.baseline/product/` and then +# branded like everything else, so they are checked here, after both: they +# name the product's own repository, leave no template behind, and every +# relative link in them — and in the operating contract they point at — +# resolves inside the product. The README this replaced linked +# `docs/phases/`, `BOOTSTRAP.md` and `specs/`, none of which ship, and the +# operating contract shipped `https://github.com/OPSFLOWS` as a clone URL. +echo "── the pages an agent starts from" +python3 - "$tree" "$root" <<'PY' +import json, pathlib, re, sys +tree, root = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]) +vals = json.loads((root / "tests/fixtures/acme.json").read_text()) +repo = f"{vals['githuborg']}/{vals['reponame']}" +problems = [] +def bad(m): problems.append(m) + +pages = ["README.md", "AGENTS.md", "ai/context/operations.md"] +missing = [rel for rel in pages if not (tree / rel).is_file()] +if missing: + sys.exit(f"FAIL: {', '.join(missing)} did not ship") +text = {rel: (tree / rel).read_text() for rel in pages} + +for rel in ("README.md", "AGENTS.md"): + if "{{" in text[rel]: + bad(f"{rel} still carries a template expression") + if repo not in text[rel]: + bad(f"{rel} does not name the product's repository, {repo}") + if "opencode.ai" in text[rel]: + bad(f"{rel} links Orun to opencode.ai") +for need in ("ai/context/operations.md", "ai/context/deployment.md"): + if need not in text["AGENTS.md"]: + bad(f"AGENTS.md does not point at {need}") +if "OPSFLOWS" in text["ai/context/operations.md"]: + bad("ai/context/operations.md still carries the OPSFLOWS placeholder") + +# Relative links only: a URL or an in-page anchor is not a file to find. +LINK = re.compile(r"\[[^\]]*\]\(([^)\s]+)\)") +links = 0 +for rel, body in text.items(): + for target in LINK.findall(body): + if re.match(r"[a-z]+:", target) or target.startswith("#"): + continue + links += 1 + if not ((tree / rel).parent / target.split("#", 1)[0]).exists(): + bad(f"{rel} links {target}, which is not in the product") +if links == 0: + bad("no relative links found in the product's pages — this check has gone blind") + +if problems: + print("FAIL: the pages an agent starts from:", file=sys.stderr) + for p in problems: + print(f" - {p}", file=sys.stderr) + sys.exit(1) +print(f" README.md and AGENTS.md name {repo}; {links} relative links resolve") +PY + +# ── the API base and the domain, in the product ──────────────────────────── +# The console asks for no domain, so the fixture carries none, and BE3's +# `derive: "https://api.{productdomain}"` left the card with it (a card can +# only derive from inputs it declares). What a product built that way must +# end up with, checked in the product rather than as a rule: +# +# - its CLI's DEFAULT_API_URL is its own prod edge on workers.dev. The name +# is read from the PLACED, BRANDED api-edge — its wrangler `name` plus the +# `--env prod` its component.yaml deploys — so the CLI and the worker it +# points at are held to one rule. `https://api.<placeholder>` could never +# answer; +# - every place the domain goes carries the reserved placeholder +# `<reponame>.example.com`, for an owner to replace later. +# +# Neither half can pass on nothing: a fixture that gains a domain, a brand.ts +# without DEFAULT_API_URL, an api-edge that stops deploying `--env prod`, or an +# intent without BASE_DOMAIN fails here instead of going blind. +echo "── the API base and the domain the product ends up with" +python3 - "$tree" "$root" <<'PY' +import json, pathlib, re, sys +tree, root = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]) +vals = json.loads((root / "tests/fixtures/acme.json").read_text()) +if (vals.get("productdomain") or "").strip(): + sys.exit("tests/fixtures/acme.json carries a productdomain — a console build " + "supplies none, so this would no longer check what one produces") +if (vals.get("apibaseurl") or "").strip(): + sys.exit("tests/fixtures/acme.json carries an apibaseurl — the CLI default " + "would be that, and the no-domain rule would go unchecked") + +wr = (tree / "apps/api-edge/wrangler.template.jsonc").read_text() +name = re.search(r'"name":\s*"([a-z0-9-]+)"', wr) +if not name: + sys.exit("apps/api-edge/wrangler.template.jsonc has no worker name — gone blind") +if not name.group(1).startswith(vals["reponame"] + "-"): + sys.exit(f"FAIL: the placed api-edge is named {name.group(1)!r}, not branded " + f"with {vals['reponame']!r}") +comp = (tree / "apps/api-edge/component.yaml").read_text() +if not re.search(r"^\s*deployCommand:.*--env prod\s*$", comp, re.M): + sys.exit("apps/api-edge/component.yaml no longer deploys `--env prod` — gone blind") +want = f"https://{name.group(1)}-prod.{vals['subdomain']}.workers.dev" +brand = (tree / "packages/cli/src/brand.ts").read_text() +m = re.search(r'DEFAULT_API_URL = "([^"]+)"', brand) +if not m: + sys.exit("packages/cli/src/brand.ts no longer declares DEFAULT_API_URL — gone blind") +if m.group(1) != want: + sys.exit(f"FAIL: the product's DEFAULT_API_URL is {m.group(1)!r}; built with no " + f"domain it must be its own prod edge, {want!r}") +print(f" DEFAULT_API_URL is {want} — api-edge's prod worker") + +placeholder = f"{vals['reponame']}.example.com" +intent = (tree / "intent.yaml").read_text() +bases = re.findall(r"^[ \t]*BASE_DOMAIN:[ \t]*(.*?)[ \t]*$", intent, re.M) +consoles = [c for c in re.findall(r"^[ \t]*CONSOLE_CUSTOM_DOMAIN:[ \t]*(.*?)[ \t]*$", intent, re.M) + if c not in ('""', "''")] +if not bases or not consoles: + sys.exit("intent.yaml carries no BASE_DOMAIN or CONSOLE_CUSTOM_DOMAIN — gone blind") +for b in bases: + if b != placeholder: + sys.exit(f"FAIL: intent.yaml's BASE_DOMAIN is {b!r}, not the placeholder {placeholder!r}") +for c in consoles: + if not c.endswith("." + placeholder): + sys.exit(f"FAIL: intent.yaml's CONSOLE_CUSTOM_DOMAIN is {c!r}, not under {placeholder!r}") +carrying = sorted( + str(p.relative_to(tree)) for p in tree.rglob("*") + if p.is_file() and ".git" not in p.parts and ".orun" not in p.parts + and placeholder in p.read_text(errors="replace")) +print(f" the domain is the placeholder {placeholder}: BASE_DOMAIN x{len(bases)}, " + f"CONSOLE_CUSTOM_DOMAIN x{len(consoles)}; {len(carrying)} files carry it") +PY + +# ── THE PHASED SEQUENCE THROUGH A REBRAND ────────────────────────────────── +# A fresh tree, phase by phase, with the branding in the middle where the real +# bootstrap puts it. Before orun BE-O12 this died at the second phase: +# +# ✕ phase "02-foundation" requires 01-scaffold (drifted) +# +echo "── the phased sequence, with the rebrand where 01-scaffold puts it" +seq="$scratch/seq" +mkdir -p "$seq"/{apps,infra,packages,tests} +for d in apps infra packages tests; do touch "$seq/$d/.gitkeep"; done +orun new --blueprint "$root/repo-blueprint.yaml" --out "$seq" --phase 01-scaffold \ + "${sets[@]}" > "$scratch/p01.log" 2>&1 || { + echo "FAIL: 01-scaffold did not place" >&2; tail -10 "$scratch/p01.log" >&2; exit 1; } +( + cd "$seq" + git init -q -b main + git config user.email t@example.invalid + git config user.name "tier one" + printf 'baseline/\n.orun/\n' >> .gitignore + git add -A + node "$root/tooling/rebrand/rebrand.mjs" --values .rebrand/values.json --allow-dirty +) > "$scratch/seqbrand.log" 2>&1 || { + echo "FAIL: the sequence's rebrand did not complete" >&2 + tail -10 "$scratch/seqbrand.log" >&2; exit 1; } + +name_after_brand="$(python3 -c "import json;print(json.load(open('$seq/package.json'))['name'])")" +[ "$name_after_brand" = "acme-cloud" ] \ + || fail "after branding, package.json name is $name_after_brand, not the product's" + +# 08-docs requires 06-console, which the rebrand has drifted: the case BE-O12 +# used to refuse. (The custom-domain component used to land after 06-console as +# 07-domain; it lands in 06-console now, parked.) +for ph in 02-foundation 03-infrastructure 03-infrastructure-database 04-workers 05-edge 06-console 08-docs; do + if ! orun new --blueprint "$root/repo-blueprint.yaml" --out "$seq" --phase "$ph" \ + "${sets[@]}" > "$scratch/p-$ph.log" 2>&1; then + fail "phase $ph refused after the rebrand: $(tail -1 "$scratch/p-$ph.log")" + fi +done + +# ── and a resume must not undo the branding ──────────────────────────────── +# This is the destructive half of BE-O12. A resume over a branded product used +# to re-place every drifted phase, which is all of them, reverting the product's +# identity to the baseline's. +orun new --blueprint "$root/repo-blueprint.yaml" --out "$seq" --resume "${sets[@]}" \ + > "$scratch/resume.log" 2>&1 || { + echo "FAIL: --resume did not run" >&2; tail -10 "$scratch/resume.log" >&2; exit 1; } +name_after_resume="$(python3 -c "import json;print(json.load(open('$seq/package.json'))['name'])")" +[ "$name_after_resume" = "acme-cloud" ] \ + || fail "--resume reverted the product's identity: package.json name is now + $name_after_resume. A resume between phases must not un-brand a product." + +[ "$fails" -eq 0 ] && \ + echo " 01 → 08 place through the rebrand; --resume leaves the branding alone" + +[ "$fails" -eq 0 ] || { echo "placement.test.sh: $fails failure(s)" >&2; exit 1; } +echo "placement.test.sh: ok" diff --git a/testing/rebrand.test.sh b/testing/rebrand.test.sh new file mode 100755 index 0000000..8d32765 --- /dev/null +++ b/testing/rebrand.test.sh @@ -0,0 +1,299 @@ +#!/usr/bin/env bash +# THE REBRAND WRITES EACH VALUE ONCE, WHAT IT WROTE STAYS WRITTEN, AND THE +# PIECES THAT MUST AGREE STILL AGREE. +# +# This drives the real rebrand.mjs over tiny trees and compares the files. Its +# left-hand side is this repository's own identity — `.rebrand/values.json`, +# which the script reads from next to itself — so every fixture below is +# written in THIS baseline's names, read from that file, and the same test +# holds in every baseline the engine serves. +# +# What it holds, from the cirrus and Lumen engines this one descends from: +# +# 1. A `secret://<workspace>/<project>/<env>/<KEY>` ref is verified by the +# platform against the run's own workspace, so both segments are renamed, +# each to its own value. +# 2. The rules run in sequence over one buffer, and a value containing a +# baseline word must not be rewritten by a later rule — nor by the next +# phase's pass, since a bootstrap re-runs the rebrand in every phase. +# +# And what this engine adds: +# +# 3. THE PLATFORM WORD. The CMS names the platform `lumen` in every case-form +# — a route directory, a module path, a Payload field and the column Payload +# derives from it, a binding, a cookie, a migration. Each must come out +# renamed AND still agree with the others, and the paths that carry the +# word must be renamed with it. +# +# Needs: node, git, python3. No network. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" +rebrand="$root/tooling/rebrand/rebrand.mjs" + +# ── this baseline's own names ────────────────────────────────────────────── +eval "$(python3 - "$root/.rebrand/values.json" <<'PY' +import json, re, shlex, sys +v = json.load(open(sys.argv[1])) +repo, name = v["reponame"], v["productname"] +pascal = re.sub(r"[^A-Za-z0-9]", "", name) +out = { + "REPO": repo, "NAME": name, "PASCAL": pascal, + "CAMEL": pascal[:1].lower() + pascal[1:], + "ENV": repo.upper().replace("-", "_"), + "SUB": v.get("subdomain") or "your-workers-subdomain", + "WS": v.get("orunWorkspace") or repo, +} +for k, val in out.items(): + print(f"{k}={shlex.quote(val)}") +PY +)" +[ -n "$REPO" ] && [ -n "$SUB" ] && [ -n "$WS" ] || { echo "rebrand.test.sh: .rebrand/values.json is incomplete" >&2; exit 1; } +echo " the baseline is $REPO (\"$NAME\"), subdomain $SUB, workspace $WS" + +fail=0 +# brand VALUES PASSES FILE=CONTENT... — a tree of the given files, branded +# PASSES times (a bootstrap runs it once per phase, over everything placed). +# Leaves the tree in $tree; returns non-zero if a pass failed. +brand() { + local values="$1" passes="$2" i spec + shift 2 + tree="$(mktemp -d)" + git -C "$tree" init -q + mkdir -p "$tree/.rebrand" + printf '%s\n' "$values" > "$tree/.rebrand/values.json" + for spec in "$@"; do + mkdir -p "$tree/$(dirname "${spec%%=*}")" + printf '%s\n' "${spec#*=}" > "$tree/${spec%%=*}" + done + for ((i = 1; i <= passes; i++)); do + git -C "$tree" add -A + if ! out="$(cd "$tree" && node "$rebrand" --values .rebrand/values.json --allow-dirty 2>&1)"; then + printf '%s\n' "$out" | sed 's/^/ /' >&2 + return 1 + fi + done +} +# check NAME VALUES FILE CONTENT WANT [PASSES] +check() { + local name="$1" values="$2" file="$3" content="$4" want="$5" passes="${6:-1}" got + if ! brand "$values" "$passes" "$file=$content"; then + echo " ✕ $name: the rebrand failed" >&2; fail=1; rm -rf "$tree"; return + fi + got="$(cat "$tree/$file" 2>/dev/null || echo "<$file is gone>")" + rm -rf "$tree" + if [ "$got" = "$want" ]; then echo " ok $name"; else + echo " ✕ $name:" >&2; echo " got: $got" >&2; echo " want: $want" >&2; fail=1 + fi +} +# moved NAME VALUES FROM TO [PASSES] — FROM is renamed to TO, nothing left behind +moved() { + local name="$1" values="$2" from="$3" to="$4" passes="${5:-1}" + if ! brand "$values" "$passes" "$from=export const x = 1"; then + echo " ✕ $name: the rebrand failed" >&2; fail=1; rm -rf "$tree"; return + fi + if [ -f "$tree/$to" ] && [ ! -e "$tree/$from" ] && git -C "$tree" ls-files --error-unmatch "$to" >/dev/null 2>&1 \ + && [ -z "$(find "$tree" -path "$tree/.git" -prune -o -type d -empty -print)" ]; then + echo " ok $name" + else + echo " ✕ $name: want $to (indexed, nothing empty left), have:" >&2 + (cd "$tree" && git ls-files | sed 's/^/ /') >&2 + fail=1 + fi + rm -rf "$tree" +} + +acme='{"reponame":"acme-cloud","productname":"Acme Cloud","subdomain":"acme","orunWorkspace":"ws_0000000000000000000000000000000f"}' +nodomain='{"reponame":"acme-cloud","productname":"Acme Cloud","githuborg":"acme-inc","subdomain":"acme"}' +ref="TOKEN: secret://$WS/$REPO/stage/CLOUDFLARE_API_TOKEN" + +echo "── rebrand: the secret ref's two segments" +check "a workspace id is the workspace segment" \ + '{"reponame":"altocumulus","productname":"Altocumulus","orunWorkspace":"ws_79BDXAZQ"}' apps/w/component.yaml "$ref" \ + "TOKEN: secret://ws_79BDXAZQ/altocumulus/stage/CLOUDFLARE_API_TOKEN" +check "an explicit workspace slug wins over the id" \ + '{"reponame":"altocumulus","productname":"Altocumulus","orunWorkspace":"ws_79BDXAZQ","orunWorkspaceSlug":"acme-space"}' apps/w/component.yaml "$ref" \ + "TOKEN: secret://acme-space/altocumulus/stage/CLOUDFLARE_API_TOKEN" +check "a workspace named with the platform word is written once…" \ + '{"reponame":"altocumulus","productname":"Altocumulus","orunWorkspaceSlug":"lumen-test"}' apps/w/component.yaml "$ref" \ + "TOKEN: secret://lumen-test/altocumulus/stage/CLOUDFLARE_API_TOKEN" +check "…and survives every later phase's pass" \ + '{"reponame":"altocumulus","productname":"Altocumulus","orunWorkspaceSlug":"lumen-test"}' apps/w/component.yaml "$ref" \ + "TOKEN: secret://lumen-test/altocumulus/stage/CLOUDFLARE_API_TOKEN" 3 + +echo "── rebrand: workers, subdomain, domain and the CLI's default" +check "a worker and its workers.dev host" \ + "$acme" apps/w/wrangler.template.jsonc "\"LUMEN_API_PUBLIC_URL\": \"https://$REPO-api-edge-prod.$SUB.workers.dev\"" \ + '"ACME_CLOUD_API_PUBLIC_URL": "https://acme-cloud-api-edge-prod.acme.workers.dev"' +# The worker rule's bases are this tree's own apps/<base>/ directories, so the +# fixture lives in the one it names. +check "a worker prefix of its own" \ + '{"reponame":"acme-cloud","productname":"Acme Cloud","brandSlug":"acme","subdomain":"acme"}' apps/api-edge/wrangler.template.jsonc \ + "\"services\": [{ \"binding\": \"LUMEN_API\", \"service\": \"$REPO-api-edge-stage\" }]" \ + '"services": [{ "binding": "ACME_CLOUD_API", "service": "acme-api-edge-stage" }]' +check "no domain: the domain's places get the placeholder" \ + "$nodomain" intent.yaml " BASE_DOMAIN: $REPO.example.com" \ + ' BASE_DOMAIN: acme-cloud.example.com' +check "a domain given: the domain where the domain goes" \ + '{"reponame":"acme-cloud","productname":"Acme Cloud","productdomain":"acme.dev","subdomain":"acme"}' \ + intent.yaml " BASE_DOMAIN: $REPO.example.com" ' BASE_DOMAIN: acme.dev' +check "no domain: the CLI defaults to the product's own prod edge" \ + "$nodomain" packages/cli/src/brand.ts "export const DEFAULT_API_URL = \"https://$REPO-api-edge-prod.$SUB.workers.dev\";" \ + 'export const DEFAULT_API_URL = "https://acme-cloud-api-edge-prod.acme.workers.dev";' +check "…and survives every later phase's pass" \ + "$nodomain" packages/cli/src/brand.ts "export const DEFAULT_API_URL = \"https://$REPO-api-edge-prod.$SUB.workers.dev\";" \ + 'export const DEFAULT_API_URL = "https://acme-cloud-api-edge-prod.acme.workers.dev";' 3 +check "a domain given: the CLI defaults to api.<domain>" \ + '{"reponame":"acme-cloud","productname":"Acme Cloud","productdomain":"acme.dev","subdomain":"acme"}' \ + packages/cli/src/brand.ts "export const DEFAULT_API_URL = \"https://$REPO-api-edge-prod.$SUB.workers.dev\";" \ + 'export const DEFAULT_API_URL = "https://api.acme.dev";' +check "an explicit apibaseurl wins either way" \ + '{"reponame":"acme-cloud","productname":"Acme Cloud","apibaseurl":"https://edge.acme.dev"}' \ + packages/cli/src/brand.ts "export const DEFAULT_API_URL = \"https://$REPO-api-edge-prod.$SUB.workers.dev\";" \ + 'export const DEFAULT_API_URL = "https://edge.acme.dev";' +check "the CLI's bin and env prefix" \ + '{"reponame":"acme-cloud","productname":"Acme Cloud","cliBin":"acme"}' packages/cli/src/config-paths.ts \ + "const dir = process.env.${ENV}_CONFIG_DIR ?? join(home, '.config', '$REPO')" \ + "const dir = process.env.ACME_CONFIG_DIR ?? join(home, '.config', 'acme')" +check "the user agent, written once though its value holds the platform word" \ + '{"reponame":"lumen-next","productname":"Lumen Next"}' apps/w/src/ua.ts "const UA = \"$PASCAL-Webhooks/1.0\";" \ + 'const UA = "LumenNext-Webhooks/1.0";' 3 + +echo "── rebrand: the platform word, every form, still agreeing" +check "a Payload field (camelCase)" \ + "$acme" apps/cms/src/collections/Users.ts " name: 'lumenUserId'," " name: 'acmeCloudUserId'," +check "…and the column Payload derives from it (snake_case)" \ + "$acme" packages/db/src/migrations/206/up.sql \ + 'ALTER TABLE "cms"."users" ADD COLUMN IF NOT EXISTS "lumen_user_id" varchar;' \ + 'ALTER TABLE "cms"."users" ADD COLUMN IF NOT EXISTS "acme_cloud_user_id" varchar;' +# to-snake-case, which Payload's adapter uses, starts a word at EVERY capital: +# `aCMECloudUserId` is a_c_m_e_cloud_user_id. A slug-derived snake name +# (acme_cloud) would leave the CMS querying a column its migration never made. +check "a name with a run of capitals: the field…" \ + '{"reponame":"acme-cloud","productname":"ACME Cloud"}' apps/cms/src/collections/Users.ts \ + " name: 'lumenUserId'," " name: 'aCMECloudUserId'," +check "…and the column, as Payload derives it from that field" \ + '{"reponame":"acme-cloud","productname":"ACME Cloud"}' packages/db/src/migrations/206/up.sql \ + 'CREATE UNIQUE INDEX "users_lumen_user_id_idx" ON "cms"."users" ("lumen_user_id");' \ + 'CREATE UNIQUE INDEX "users_a_c_m_e_cloud_user_id_idx" ON "cms"."users" ("a_c_m_e_cloud_user_id");' +check "a module path and a component, in an import" \ + "$acme" apps/cms/src/app/page.tsx "import { LumenLogin } from '@/components/admin/LumenLogin'; import { read } from '@cms/lib/lumen/cookies'" \ + "import { AcmeCloudLogin } from '@/components/admin/AcmeCloudLogin'; import { read } from '@cms/lib/acme-cloud/cookies'" +check "a route, a cookie and a binding" \ + "$acme" apps/cms/src/lib/x.ts "fetch('/auth/lumen/session', { headers: { cookie: 'lumen_session=' + env.LUMEN_API_URL } })" \ + "fetch('/auth/acme-cloud/session', { headers: { cookie: 'acme_cloud_session=' + env.ACME_CLOUD_API_URL } })" +check "the slug follows brandSlug" \ + '{"reponame":"acme-cloud","productname":"Acme Cloud","brandSlug":"acme"}' apps/cms/src/lib/strategy.ts \ + "export const strategy = { name: 'lumen' }" "export const strategy = { name: 'acme' }" +check "prose in code is the display name" \ + "$acme" apps/cms/src/components/SignIn.tsx "<p>Use your Lumen account. Lumen could not be reached.</p>" \ + "<p>Use your Acme Cloud account. Acme Cloud could not be reached.</p>" +check "markdown: prose the display name, code the identifier" \ + "$acme" apps/cms/docs/overview.md 'Sign in with Lumen through `LumenLogin`, the `Lumen` strategy.' \ + 'Sign in with Acme Cloud through `AcmeCloudLogin`, the `AcmeCloud` strategy.' +check "the baseline's own name, every form" \ + "$acme" apps/w/README.md "$NAME is $PASCAL; const $CAMEL = new $PASCAL(); $REPO; ${ENV}_TOKEN" \ + 'Acme Cloud is AcmeCloud; const acmeCloud = new AcmeCloud(); acme-cloud; ACME_CLOUD_TOKEN' +check "a product named with the platform word, three passes" \ + '{"reponame":"lumen-e2e","productname":"Lumen E2E"}' apps/cms/src/lib/x.ts \ + "fetch('/auth/lumen/session'); const id = user.lumenUserId; // Lumen" \ + "fetch('/auth/lumen-e2e/session'); const id = user.lumenE2EUserId; // Lumen E2E" 3 + +echo "── rebrand: the paths that carry the word are renamed with it" +moved "a module directory" "$acme" apps/cms/src/lib/lumen/client.ts apps/cms/src/lib/acme-cloud/client.ts +moved "a route directory" "$acme" "apps/cms/src/app/(site)/auth/lumen/callback/page.tsx" "apps/cms/src/app/(site)/auth/acme-cloud/callback/page.tsx" +moved "a component file" "$acme" apps/cms/src/components/admin/LumenLogin.tsx apps/cms/src/components/admin/AcmeCloudLogin.tsx +moved "a migration directory" "$acme" packages/db/src/migrations/206_cms_lumen_identity/up.sql packages/db/src/migrations/206_cms_acme_cloud_identity/up.sql +moved "a test file" "$acme" tests/cms/src/lumen-session.test.ts tests/cms/src/acme-cloud-session.test.ts +moved "a product named with the word, three passes" '{"reponame":"lumen-e2e","productname":"Lumen E2E"}' \ + apps/cms/src/lib/lumen/client.ts apps/cms/src/lib/lumen-e2e/client.ts 3 + +echo "── rebrand: a rewritten migration is re-sealed, an untouched one is not" +# The runner refuses a migration whose file does not hash to its manifest's +# checksum. The rebrand rewrites 206 (the column it adds), so it must re-seal +# that one — and only what it rewrote: a stale checksum on a file it did not +# touch is somebody's hand edit, which the runner should go on refusing. +sum() { python3 -c "import hashlib,sys;print(hashlib.sha256(open(sys.argv[1],'rb').read()).hexdigest())" "$1"; } +mig206='ALTER TABLE "cms"."users" ADD COLUMN "lumen_user_id" varchar;' +stale="$(printf '%064d' 0)" +manifest="export const manifest = { migrations: [ + { id: \"100_x\", path: \"100_x/up.sql\", checksum: + \"$stale\" }, + { id: \"206_cms_lumen_identity\", path: \"206_cms_lumen_identity/up.sql\", checksum: + \"$(printf '%s\n' "$mig206" | python3 -c "import hashlib,sys;print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())")\" }, +] }" +if brand "$acme" 2 "packages/db/src/manifest.ts=$manifest" \ + "packages/db/src/migrations/100_x/up.sql=CREATE TABLE x (id int);" \ + "packages/db/src/migrations/206_cms_lumen_identity/up.sql=$mig206"; then + m="$tree/packages/db/src/manifest.ts" + new="$(sum "$tree/packages/db/src/migrations/206_cms_acme_cloud_identity/up.sql")" + grep -q "206_cms_acme_cloud_identity/up.sql\", checksum:" "$m" && grep -q "\"$new\"" "$m" \ + && echo " ok the rewritten migration's checksum is its new file's" \ + || { echo " ✕ 206 was not re-sealed:" >&2; sed 's/^/ /' "$m" >&2; fail=1; } + grep -q "\"$stale\"" "$m" \ + && echo " ok an untouched migration's stale checksum is left for the runner to refuse" \ + || { echo " ✕ the untouched migration was re-sealed" >&2; fail=1; } +else + echo " ✕ the rebrand failed" >&2; fail=1 +fi +rm -rf "$tree" + +echo "── rebrand: refusals" +refuse() { # NAME VALUES + local name="$1" values="$2" + if brand "$values" 1 "apps/w/a.ts=x" 2>/dev/null; then + echo " ✕ $name: it branded" >&2; fail=1 + else echo " ok $name"; fi + rm -rf "$tree" +} +refuse "a name that cannot be an identifier" '{"reponame":"acme","productname":"2 Acme"}' +refuse "a repo slug that is not a slug" '{"reponame":"Acme_Cloud","productname":"Acme Cloud"}' + +# --verify runs in every phase of a bootstrap. Without the product's values it +# cannot tell the product's own identity from a baseline leftover; with them it +# passes what the rebrand would write. A real leftover fails either way, and +# so does a path still named after the baseline. +verify() { # NAME VALUES FILE CONTENT WANT(pass|fail) [--values] + local name="$1" values="$2" file="$3" content="$4" want="$5" withvalues="${6:-}" got + tree="$(mktemp -d)" + git -C "$tree" init -q + mkdir -p "$tree/$(dirname "$file")" "$tree/.rebrand" + printf '%s\n' "$content" > "$tree/$file" + printf '%s\n' "$values" > "$tree/.rebrand/values.json" + git -C "$tree" add -A + if (cd "$tree" && node "$rebrand" --verify ${withvalues:+--values .rebrand/values.json} >/dev/null 2>&1); then got=pass; else got=fail; fi + rm -rf "$tree" + if [ "$got" = "$want" ]; then echo " ok $name"; else echo " ✕ $name: --verify ${got}ed, want $want" >&2; fail=1; fi +} +echo "── rebrand --verify: the product's own identity is not residue" +e2e='{"reponame":"lumen-e2e","productname":"Lumen E2E","subdomain":"acme"}' +verify "given the values, a name holding the platform word passes" \ + "$e2e" apps/w/wrangler.template.jsonc '"name": "lumen-e2e-api-edge"' pass --values +verify "without them it cannot know, and fails" \ + "$e2e" apps/w/wrangler.template.jsonc '"name": "lumen-e2e-api-edge"' fail +verify "given the values, a real leftover still fails" \ + "$e2e" apps/w/src/a.ts 'const x = user.lumenUserId' fail --values +verify "the baseline's own name is a leftover" \ + "$acme" apps/w/README.md "Welcome to $NAME." fail --values +verify "the baseline's subdomain is a leftover once the product's differs" \ + "$acme" apps/w/README.md "https://x.$SUB.workers.dev" fail --values +verify "…and the baseline's workspace" \ + "$acme" apps/w/component.yaml "K: secret://$WS/acme-cloud/stage/K" fail --values +verify "a path named after the baseline is a leftover" \ + "$acme" apps/cms/src/lib/lumen/client.ts 'export const x = 1' fail --values +verify "a clean product passes" \ + "$acme" apps/w/README.md "Welcome to Acme Cloud, at https://acme-cloud-cms-prod.acme.workers.dev." pass --values + +# THE OLD KEYS STILL WORK. Products born from the flows' phase slices committed +# values.json with `repoName`, `productName`, …; a later phase run against one +# brands with that file, so rebrand reads both, the manifest's key winning. +echo "── rebrand: the pre-blueprint camelCase keys" +check "the old keys brand like the new ones" \ + '{"repoName":"altocumulus","productName":"Altocumulus","productDomain":"altocumulus.dev","orunWorkspace":"ws_79BDXAZQ"}' \ + apps/w/component.yaml "$ref" "TOKEN: secret://ws_79BDXAZQ/altocumulus/stage/CLOUDFLARE_API_TOKEN" +check "the manifest's key wins over the old one" \ + '{"reponame":"altocumulus","repoName":"stale","productname":"Altocumulus","productdomain":"altocumulus.dev","orunWorkspace":"ws_79BDXAZQ"}' \ + apps/w/component.yaml "$ref" "TOKEN: secret://ws_79BDXAZQ/altocumulus/stage/CLOUDFLARE_API_TOKEN" + +[ "$fail" -eq 0 ] || exit 1 +echo "rebrand.test.sh: ok" 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 <phase> <stamp> +# +# 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/<worker> does with apps/<worker>) 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/tests/cms/src/lumen-accounts.test.ts b/tests/cms/src/lumen-accounts.test.ts index d1ded67..87f0724 100644 --- a/tests/cms/src/lumen-accounts.test.ts +++ b/tests/cms/src/lumen-accounts.test.ts @@ -26,18 +26,18 @@ function store(rows: Account[] = []) { return s } -const lumen = { id: 'usr_ed', email: 'Ed@Example.com', displayName: 'Ed' } +const person = { id: 'usr_ed', email: 'Ed@Example.com', displayName: 'Ed' } describe('accountFor', () => { it('returns the linked account', async () => { const s = store([{ id: 'u1', email: 'ed@example.com', role: 'editor', lumenUserId: 'usr_ed' }]) - await expect(accountFor(s, lumen, false)).resolves.toMatchObject({ id: 'u1', role: 'editor' }) + await expect(accountFor(s, person, false)).resolves.toMatchObject({ id: 'u1', role: 'editor' }) expect(s.rows).toHaveLength(1) }) it('links an unlinked account with the same email once, keeping its role (an invitation)', async () => { const s = store([{ id: 'u1', email: 'ed@example.com', role: 'editor', lumenUserId: null }]) - await expect(accountFor(s, lumen, false)).resolves.toMatchObject({ id: 'u1', role: 'editor', lumenUserId: 'usr_ed' }) + await expect(accountFor(s, person, false)).resolves.toMatchObject({ id: 'u1', role: 'editor', lumenUserId: 'usr_ed' }) }) it('never re-links an account linked to someone else', async () => { @@ -47,31 +47,31 @@ describe('accountFor', () => { created++ throw new Error('email taken') } - await expect(accountFor(s, lumen, true)).rejects.toThrow('email taken') + await expect(accountFor(s, person, true)).rejects.toThrow('email taken') expect(created).toBe(1) expect(s.rows[0]).toMatchObject({ lumenUserId: 'usr_other', role: 'admin' }) }) it('creates a pending account (no role) for anyone new', async () => { const s = store() - await expect(accountFor(s, lumen, false)).resolves.toMatchObject({ email: 'ed@example.com', name: 'Ed', role: null, lumenUserId: 'usr_ed' }) + await expect(accountFor(s, person, false)).resolves.toMatchObject({ email: 'ed@example.com', name: 'Ed', role: null, lumenUserId: 'usr_ed' }) }) it('makes the first admin only with the setup token and only while no admin exists', async () => { const s = store() - await expect(accountFor(s, lumen, true)).resolves.toMatchObject({ role: 'admin' }) + await expect(accountFor(s, person, true)).resolves.toMatchObject({ role: 'admin' }) await expect(accountFor(s, { id: 'usr_2', email: 'two@example.com', displayName: null }, true)).resolves.toMatchObject({ role: null }) }) it('promotes a pending account through setup while there is no admin, and only then', async () => { const s = store([{ id: 'u1', email: 'ed@example.com', role: null, lumenUserId: 'usr_ed' }]) - await expect(accountFor(s, lumen, false)).resolves.toMatchObject({ role: null }) - await expect(accountFor(s, lumen, true)).resolves.toMatchObject({ role: 'admin' }) + await expect(accountFor(s, person, false)).resolves.toMatchObject({ role: null }) + await expect(accountFor(s, person, true)).resolves.toMatchObject({ role: 'admin' }) const t = store([ { id: 'u1', email: 'boss@example.com', role: 'admin', lumenUserId: 'usr_boss' }, { id: 'u2', email: 'ed@example.com', role: null, lumenUserId: 'usr_ed' }, ]) - await expect(accountFor(t, lumen, true)).resolves.toMatchObject({ role: null }) + await expect(accountFor(t, person, true)).resolves.toMatchObject({ role: null }) }) it('reads the row back when two first requests race to create it', async () => { @@ -80,6 +80,6 @@ describe('accountFor', () => { s.rows.push({ id: 'u9', ...data, email: data.email.toLowerCase() }) throw new Error('unique violation') } - await expect(accountFor(s, lumen, false)).resolves.toMatchObject({ id: 'u9' }) + await expect(accountFor(s, person, false)).resolves.toMatchObject({ id: 'u9' }) }) }) diff --git a/tests/fixtures/acme.json b/tests/fixtures/acme.json new file mode 100644 index 0000000..38c21a3 --- /dev/null +++ b/tests/fixtures/acme.json @@ -0,0 +1,21 @@ +{ + "_comment": [ + "The inputs a Tier 1 dry instantiation renders with (saas-bootstrap-engine BE5).", + "Acme is not a real product and never becomes one: this tree is placed into a", + "temp directory, asserted against, and deleted. The values are chosen to be", + "AWKWARD rather than tidy — a two-word product name, a hyphenated repo slug,", + "and NO domain: a console build asks for none, so the placeholder", + "<reponame>.example.com is what a product is born with, and the CLI defaults", + "to the product's own prod edge on workers.dev — because a fixture that only", + "uses values the templates were written against proves the templates work on", + "the values they were written against.", + "Every key here is an input repo-blueprint.yaml declares. A key it does not", + "declare is a fixture that has drifted, and orun refuses it." + ], + "reponame": "acme-cloud", + "productname": "Acme Cloud", + "githuborg": "acme-inc", + "subdomain": "acme", + "orunWorkspace": "ws_0000000000000000000000000000000f", + "epicSlug": "infra-baselining" +} diff --git a/tests/platform-limits/src/service-chain.test.ts b/tests/platform-limits/src/service-chain.test.ts index 15b12db..ec57d34 100644 --- a/tests/platform-limits/src/service-chain.test.ts +++ b/tests/platform-limits/src/service-chain.test.ts @@ -34,8 +34,14 @@ const MAX_WORKER_INVOCATIONS = 32; */ const CHAIN_BUDGET = 12; -/** Measured today. Named so growth is a visible edit, not a silent drift. */ -const DEEPEST = { entry: "api-edge", depth: 8 }; +/** + * Measured today. Named so growth is a visible edit, not a silent drift. + * + * The CMS, since its sign-in (lumen-payload-console PX1): it checks a session + * with api-edge over one service binding, so its deepest chain is the edge's + * own (8, unchanged) plus that hop. + */ +const DEEPEST = { entry: "cms", depth: 9 }; /** * Cycles in the binding graph, reviewed and accepted. 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/<TASK-KEY>-<branchSlug>`, 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/<task>-<slug> 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 <phase> <stamp> +// +// 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 <name> the phase the marker names (required) +// --components a,b,c the components to touch, by `metadata.name` … +// --affects <contract> … 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 <name> (--components a,b,c | --affects <TaskContract.yaml>) [--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/rebrand/rebrand.mjs b/tooling/rebrand/rebrand.mjs new file mode 100644 index 0000000..b769dc0 --- /dev/null +++ b/tooling/rebrand/rebrand.mjs @@ -0,0 +1,677 @@ +#!/usr/bin/env node +// Fork/rebrand renamer for this baseline (zero-dependency). +// +// This repository is a baseline: a product placed from it is rebranded with +// this script, phase by phase. It rewrites every *instance identity* literal — +// repo slug, product domain, product/display name, SDK class name, CLI bin, +// Cloudflare worker resource names (so a fork is account-safe even when it +// shares an account with this repository), wire-visible user agents, +// workers.dev subdomain, the Orun workspace — to the values supplied in a +// values file, leaving *org-owned* identity untouched (the orun state backend, +// `sourceplane.io` manifest apiVersion, company email addresses). +// +// WHERE THE BASELINE'S OWN IDENTITY COMES FROM. The rename map's left-hand +// side is this repository's own `.rebrand/values.json` — the file its own +// bootstrap wrote and AGENTS.md says not to touch — read from next to this +// script, never typed in here. So the engine is the same file in every +// baseline built this way, and a baseline renamed later stays a baseline. +// +// AND THE PLATFORM WORD. This repository was itself born from the Lumen +// baseline, and code it added afterwards names the platform `lumen`: the CMS's +// sign-in (`lib/lumen/`, `/auth/lumen/*`, `LumenLogin`, `lumenUserId`, the +// `lumen_user_id` column, `LUMEN_API`, "your Lumen account"). Lumen's own +// rebrand renamed `lumen` and so produced this repository's name; this one +// renames what is left, in every case-form, into the product's, and RENAMES +// THE PATHS that carry it, so a product carries no `lumen` at all. Every form +// is derived so the pieces that must agree do: a Payload field and the column +// Payload derives from it, a route directory and the URLs that reach it, a +// module path and its imports. +// +// Usage (from the product root, on a clean tree): +// node tooling/rebrand/rebrand.mjs --values my-brand.json [--dry-run] +// node tooling/rebrand/rebrand.mjs --verify [--values my-brand.json] +// +// Values file (see tooling/rebrand/values.example.json): +// { +// "reponame": "acme-cloud", // required — repo slug +// "productname": "Acme Cloud", // required — display name +// "productdomain": "acme.dev", // optional — default <reponame>.example.com (set later) +// "pascalName": "AcmeCloud", // default: productname, non-alnum stripped +// "brandSlug": "acme", // default: reponame +// "cliBin": "acme", // default: reponame +// "apibaseurl": "https://api.acme.dev",// default: https://api.<productdomain>, or with no +// // domain https://<brandSlug>-api-edge-prod.<subdomain>.workers.dev +// "subdomain": "my-subdomain", // default: "your-workers-subdomain" +// "salesEmail": "sales@acme.dev", // optional: keeps the baseline mailbox if absent +// "orunWorkspace": "ws_…" // the product's Orun workspace +// } +// +// Modes: +// (default) apply the rename map in place (content, then paths), then sweep +// --dry-run report per-rule match counts and paths to rename; change nothing +// --verify only run the leftover sweep (non-zero exit on residue) +// --source <file> the baseline's own values (default: ../../.rebrand/values.json +// from this script) — for tests only + +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import * as fs from "node:fs"; +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; + +// ── Inputs ───────────────────────────────────────────────────── + +function flag(name) { + return process.argv.includes(`--${name}`); +} +function arg(name) { + const i = process.argv.indexOf(`--${name}`); + return i >= 0 ? process.argv[i + 1] : undefined; +} + +const dryRun = flag("dry-run"); +const verifyOnly = flag("verify"); + +// THE MANIFEST'S KEYS, and the old camelCase ones for products that committed +// them before the blueprint was the bootstrap. The manifest's key wins. +const LEGACY = { + reponame: "repoName", + productname: "productName", + productdomain: "productDomain", + apibaseurl: "apiBaseUrl", + subdomain: "workersDevSubdomain", +}; +function readValues(file, what) { + let values; + try { + values = JSON.parse(fs.readFileSync(file, "utf8")); + } catch (error) { + console.error(`rebrand: cannot read ${what} ${file}: ${error.message}`); + process.exit(2); + } + for (const [key, old] of Object.entries(LEGACY)) { + if (values[key] === undefined && values[old] !== undefined) values[key] = values[old]; + } + for (const required of ["reponame", "productname"]) { + if (typeof values[required] !== "string" || values[required].length === 0) { + console.error(`rebrand: ${what} is missing required field "${required}"`); + process.exit(2); + } + } + return values; +} + +// The column name Payload's database adapter derives from a field name +// (to-snake-case: every uppercase letter starts a word). `lumenUserId` is a +// field and `lumen_user_id` its column; renamed apart, the CMS would query a +// column its migration never created. Deriving both from one camel form keeps +// them one name. +function payloadSnake(s) { + const camel = /([a-z][A-Z]|[A-Z][a-z])/.test(s) + ? s.replace(/(.)([A-Z]+)/g, (_, prev, uppers) => `${prev} ${uppers.toLowerCase().split("").join(" ")}`) + : s; + return camel + .toLowerCase() + .replace(/[\W_]+(.|$)/g, (_, next) => (next ? ` ${next}` : "")) + .trim() + .replace(/\s/g, "_"); +} + +// Every form of one identity, derived the same way for the baseline and the +// product so that each rule's two sides are the same KIND of thing. +function derive(values) { + const reponame = values.reponame ?? ""; + const productname = values.productname ?? ""; + // The domain is NOT ASKED at bootstrap: a product goes live on workers.dev + // and an owner sets a domain later. Until then the reserved placeholder + // `<reponame>.example.com` (RFC 2606 — it can never be someone else's) + // stands wherever the domain goes, so setting it is replacing one string. + const productdomain = (values.productdomain ?? "").trim() || (reponame ? `${reponame}.example.com` : ""); + const pascalName = (values.pascalName ?? "").trim() || productname.replace(/[^A-Za-z0-9]/g, ""); + const camelName = pascalName.charAt(0).toLowerCase() + pascalName.slice(1); + const brandSlug = (values.brandSlug ?? "").trim() || reponame; + const cliBin = (values.cliBin ?? "").trim() || reponame; + const subdomain = (values.subdomain ?? "").trim() || "your-workers-subdomain"; + // The CLI's default API. With a domain it is `https://api.<domain>`. With + // none, `api.<placeholder>` could never answer, so it is the product's own + // prod edge on workers.dev, live from the first deploy: api-edge deploys + // `--env prod` as `<brandSlug>-api-edge` + `-prod`. + const apibaseurl = + (values.apibaseurl ?? "").trim() || + ((values.productdomain ?? "").trim() + ? `https://api.${productdomain}` + : `https://${brandSlug}-api-edge-prod.${subdomain}.workers.dev`); + // A `secret://<workspace>/<project>/<env>/<KEY>` ref names the WORKSPACE + // first and the project (repo) second. A ws_… or org_… id IS a valid + // workspace segment (orun-cloud state-worker secrets-resolve.ts); the repo + // name is the last resort only when no workspace was given. + const workspace = + (values.orunWorkspaceSlug ?? "").trim() || (values.orunWorkspace ?? "").trim() || reponame; + return { + reponame, + productname, + productdomain, + pascalName, + camelName, + snakeName: payloadSnake(camelName), + repoSnake: reponame.replace(/-/g, "_"), + brandSlug, + cliBin, + envPrefix: cliBin.toUpperCase().replace(/-/g, "_"), + subdomain, + apibaseurl, + workspace, + salesEmail: values.salesEmail, + }; +} + +const here = path.dirname(fileURLToPath(import.meta.url)); +const sourcePath = arg("source") ?? path.resolve(here, "../../.rebrand/values.json"); +const S = derive(readValues(sourcePath, "the baseline's own values")); + +const valuesPath = arg("values"); +if (!verifyOnly && !valuesPath) { + console.error("usage: rebrand.mjs --values <file> [--dry-run] | --verify [--values <file>]"); + process.exit(2); +} +// --verify takes --values too, optionally: without them it cannot tell the +// product's own identity from a leftover of the baseline's (below). +const T = valuesPath ? derive(readValues(valuesPath, "values file")) : null; + +if (T && !verifyOnly) { + if (/[^a-z0-9-]/.test(`${T.reponame}${T.brandSlug}${T.cliBin}`)) { + console.error("rebrand: reponame/brandSlug/cliBin must be lowercase slugs ([a-z0-9-])"); + process.exit(2); + } + // The pascal form becomes class and component names (`AcmeCloudLogin`), so + // it has to be an identifier. + if (!/^[A-Za-z][A-Za-z0-9]*$/.test(T.pascalName)) { + console.error( + `rebrand: "${T.pascalName}" (pascalName, or productname without its punctuation) ` + + "must start with a letter and hold only letters and digits — it names classes and components", + ); + process.exit(2); + } +} + +// In-place rewrite of the whole tree: insist on a clean checkout so the +// result is reviewable as one diff (and trivially revertible). +if (!verifyOnly && !dryRun && !flag("allow-dirty")) { + const status = execFileSync("git", ["status", "--porcelain"], { encoding: "utf8" }); + if (status.trim().length > 0) { + console.error("rebrand: working tree is not clean — commit/stash first (or pass --allow-dirty)"); + process.exit(2); + } +} + +// ── File set ─────────────────────────────────────────────────── + +// Tracked text files only. Exclusions are generated/locked artifacts or this +// tool itself. +const EXCLUDE_RE = new RegExp( + [ + "^tooling/rebrand/", + "^\\.rebrand/", + "^pnpm-lock\\.yaml$", + "^kiox\\.lock$", + "\\.(png|jpg|jpeg|ico|gif|webp|woff2?|ttf|eot)$", + ].join("|"), +); + +function trackedFiles() { + return execFileSync("git", ["ls-files"], { encoding: "utf8" }) + .split("\n") + .filter((f) => f.length > 0 && !EXCLUDE_RE.test(f)) + .filter((f) => { + // `git ls-files` also lists gitlinks (nested repos) and paths deleted + // from disk. Only regular files are sweepable. + try { + return fs.statSync(f).isFile(); + } catch { + return false; + } + }); +} + +// ── Protected literals (org-owned identity, never rewritten) ─── +const PROTECTED = [ + /https:\/\/orun-api\.sourceplane\.ai/g, // orun state backend + /sourceplane\.io/g, // manifest apiVersion, owned by the orun tooling + /[A-Za-z0-9._%+-]+@sourceplane\.ai/g, // company mailboxes +]; +const MASK = (i, j) => `\u0000REBRAND_PROTECTED_${i}_${j}\u0000`; + +// ── Substituted values are opaque ────────────────────────────── +// +// The rules run in sequence over one buffer. A rule writes a TOKEN standing +// for its value, and every token is expanded once, after the last rule — so a +// value that contains a baseline word (`lumen-e2e`, `Lumen Next`) is never +// rewritten a second time. A token is NUL, `H<n>`, NUL; its outer characters +// take the word/non-word class of the value's own first and last characters, +// so a `\b` (or a lookaround on [A-Za-z0-9]) in a later rule sees the same +// boundary beside the token that it would have seen beside the value. +const heldValues = []; +const heldIndex = new Map(); +function hold(value) { + if (value === "") return ""; + let i = heldIndex.get(value); + if (i === undefined) { + i = heldValues.push(value) - 1; + heldIndex.set(value, i); + } + const edge = (c) => (/[A-Za-z0-9]/.test(c) ? "0" : c === "_" ? "_" : "\u0001"); + return `${edge(value[0])}\u0000H${i}\u0000${edge(value[value.length - 1])}`; +} +const HELD_RE = /[0_\u0001]\u0000H(\d+)\u0000[0_\u0001]/g; +function release(text) { + return text.replace(HELD_RE, (_, i) => heldValues[Number(i)]); +} + +const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +// ── Worker resource names ────────────────────────────────────── +// +// Every Cloudflare worker ships brand-prefixed as `<brandSlug>-<base>`, the +// base being its `apps/<base>/` directory. Re-prefixed so a fork's workers +// never collide with this repository's, even in a shared account. The console +// is an explicit literal pair (`<brandSlug>-web-console`), which also covers +// its `-next` name. +function workerBases(files) { + const bases = new Set(); + for (const file of files) { + const m = /^apps\/([^/]+)\//.exec(file); + if (m && m[1] !== "web-console-next") bases.add(m[1]); + } + return [...bases]; +} + +// ── The rules ────────────────────────────────────────────────── + +const PLATFORM = "lumen"; // the word the CMS code names the platform with +const NOT_ALNUM_BEFORE = "(?<![A-Za-z0-9])"; +const NOT_ALNUM_AFTER = "(?![A-Za-z0-9])"; + +// Literal pairs, most specific first. +function literalPairs() { + const list = []; + if (T.salesEmail) list.push(["sales@sourceplane.ai", T.salesEmail, "sales mailbox (console seam)"]); + list.push( + // The secret ref's workspace AND project, as one: MUST precede the + // workspace and repo-slug rules, which would each take half of it. + [`secret://${S.workspace}/${S.reponame}/`, `secret://${T.workspace}/${T.reponame}/`, "secret ref workspace/project"], + [`${S.brandSlug}-web-console`, `${T.brandSlug}-web-console`, "console worker prefix"], + [`${S.pascalName}-Webhooks`, `${T.pascalName}-Webhooks`, "webhooks UA"], + // The CLI default API seam. Elsewhere the same URL is "the prod edge on + // workers.dev", which the worker and subdomain rules below rebrand. + [`DEFAULT_API_URL = "${S.apibaseurl}"`, `DEFAULT_API_URL = "${T.apibaseurl}"`, "CLI default API base"], + [S.productdomain, T.productdomain, "product domain"], + [`STORAGE_PREFIX = "${S.brandSlug}.next"`, `STORAGE_PREFIX = "${T.brandSlug}.next"`, "storage prefix"], + [S.subdomain, T.subdomain, "workers.dev subdomain"], + [S.workspace, T.workspace, "Orun workspace"], + // Docs: the CLI's config dir and command examples, the check-run name. + [`.config/${S.cliBin}/`, `.config/${T.cliBin}/`, "CLI config dir (docs)"], + [`\`${S.cliBin} `, `\`${T.cliBin} `, "CLI bin (doc examples, open)"], + [`\`${S.cliBin}\``, `\`${T.cliBin}\``, "CLI bin (doc examples, closed)"], + [`"${S.brandSlug}/verify"`, `"${T.brandSlug}/verify"`, "check-run name example"], + // The product's own name, every case-form. The display name has a space, + // so it is never an identifier and is the display name everywhere. + [S.productname, T.productname, "product name"], + [S.pascalName, T.pascalName, "PascalCase name"], + [S.camelName, T.camelName, "camelCase name"], + ); + return list.filter(([from, to]) => from && from !== to); +} + +// Regex rules, in order, after the literal pairs. +function regexRules(files) { + const list = [ + { + re: new RegExp(`\\b${esc(S.envPrefix)}(?![A-Za-z0-9])`, "g"), + to: () => T.envPrefix, + label: "env-var prefix", + }, + { + re: new RegExp(`${NOT_ALNUM_BEFORE}${esc(S.repoSnake)}${NOT_ALNUM_AFTER}`, "g"), + to: () => T.repoSnake, + label: "snake_case repo slug", + }, + // The same name derived from the PascalCase form, which differs from the + // repo slug's when a word carries a digit (`saas2` against `saas_2`). + { + re: new RegExp(`${NOT_ALNUM_BEFORE}${esc(S.snakeName)}${NOT_ALNUM_AFTER}`, "g"), + to: () => T.snakeName, + label: "snake_case name", + }, + ]; + const bases = workerBases(files); + if (bases.length > 0) { + const wb = bases.slice().sort((a, b) => b.length - a.length).map(esc).join("|"); + list.push({ + re: new RegExp(`\\b${esc(S.brandSlug)}-(${wb})\\b`, "g"), + to: (_file, _m, base) => `${T.brandSlug}-${base}`, + label: "worker CF name", + }); + } + // CLI bin: usage strings, keychain/config-dir derivations, package bin. + list.push( + { + re: new RegExp(`\\b${esc(S.cliBin)}\\b`, "g"), + to: () => T.cliBin, + label: "CLI bin (packages/cli)", + fileFilter: (file) => file.startsWith("packages/cli/"), + }, + // Repo slug: intent metadata.name, component repo: fields, Supabase and + // Hyperdrive project names (`<repo>-stage`), the root package, docs. + { + re: new RegExp(`\\b${esc(S.reponame)}\\b`, "g"), + to: () => T.reponame, + label: "repo slug", + fileFilter: (file) => !file.startsWith("packages/cli/"), + }, + ); + + // ── The platform word, in every case-form the code uses ── + // + // Env vars and bindings: LUMEN_API, LUMEN_SESSION_COOKIE → <ENV>_API, … + list.push({ re: /LUMEN_(?=[A-Z])/g, to: () => `${T.envPrefix}_`, label: "platform env prefix" }); + // Glued into an identifier: LumenLogin, LumenTransport, findByLumenId. + list.push({ + re: /(?<=[A-Za-z0-9_])Lumen|Lumen(?=[A-Za-z0-9_])/g, + to: () => T.pascalName, + label: "platform PascalCase", + }); + // camelCase: lumenUserId, lumenCall — and so the Payload field the column + // below is derived from. + list.push({ + re: new RegExp(`${NOT_ALNUM_BEFORE}${PLATFORM}(?=[A-Z])`, "g"), + to: () => T.camelName, + label: "platform camelCase", + }); + // snake_case: lumen_user_id, lumen_session, 206_cms_lumen_identity. + list.push({ + re: new RegExp(`(?<=_)${PLATFORM}${NOT_ALNUM_AFTER}|${NOT_ALNUM_BEFORE}${PLATFORM}(?=_)`, "g"), + to: () => T.snakeName, + label: "platform snake_case", + }); + // Everything else is a slug: lib/lumen/, /auth/lumen/*, 'lumen' (the + // Payload strategy), lumen-email. The CLI's meaning of a bare word is its + // bin, as for the repo slug above. + list.push({ + re: new RegExp(`${NOT_ALNUM_BEFORE}${PLATFORM}${NOT_ALNUM_AFTER}`, "g"), + to: (file) => (file.startsWith("packages/cli/") ? T.cliBin : T.brandSlug), + label: "platform slug", + }); + return list; +} + +// A standalone `Lumen` is the platform's display name: every one in code is +// prose (a UI string, a comment, a test title), so it is the product's display +// name there too. Only markdown code — fences and inline spans — keeps the +// identifier form. +function replaceBrandWord(file, text, count, asPath) { + const sub = (chunk, to) => + chunk.replace(/\bLumen\b/g, () => { + count(); + return hold(to); + }); + // A path is never prose: a display name would put a space in it. + if (asPath) return sub(text, T.pascalName); + if (!/\.(md|markdown)$/.test(file)) return sub(text, T.productname); + return text + .split(/(```[\s\S]*?(?:```|$))/) + .map((part) => { + if (part.startsWith("```")) return sub(part, T.pascalName); + return part + .split(/(`[^`\n]+`)/) + .map((span) => + span.startsWith("`") && span.endsWith("`") ? sub(span, T.pascalName) : sub(span, T.productname), + ) + .join(""); + }) + .join(""); +} + +// ── Leftover sweep ───────────────────────────────────────────── +// +// After a rebrand (or under --verify) every remaining baseline-identity +// literal is residue: org-owned (allowed, enumerated below) or a missed rename +// (reported, non-zero exit). Paths are swept as well as contents: a file still +// NAMED after the baseline is as much a leftover as a line. +// +// `lumen` in any case and any position is residue — the platform word is +// renamed wherever it stands, so nothing legitimately keeps it. So is the +// baseline's own name in every form (which may not contain the word at all), +// and its subdomain and workspace when the product's differ: a fork deploying +// into the same account or workspace legitimately keeps those. +function residueRe() { + const parts = [PLATFORM]; + for (const form of [S.reponame, S.productname, S.pascalName, S.camelName, S.repoSnake, S.snakeName, S.envPrefix]) { + if (form && !form.toLowerCase().includes(PLATFORM)) parts.push(esc(form)); + } + // Only with the product's values, and only when they differ: without them a + // kept subdomain or workspace cannot be told from a missed one. + for (const key of ["subdomain", "workspace"]) { + if (T && S[key] && S[key] !== T[key]) parts.push(esc(S[key])); + } + return new RegExp(parts.join("|"), "i"); +} + +const ALLOWED_RESIDUE = [ + /https:\/\/orun-api\.sourceplane\.ai/g, // orun state backend + /[A-Za-z0-9._%+-]+@sourceplane\.ai/g, // company mailboxes +]; + +function sweep(files, allowedLiterals) { + const RESIDUE = residueRe(); + const clean = (s) => { + let out = ALLOWED_RESIDUE.reduce((l, re) => l.replace(re, ""), s); + // The rename's own TARGET values: a fork legitimately named with the + // platform word inside it (repo "lumen-e2e") is not residue. + for (const lit of allowedLiterals) if (lit) out = out.split(lit).join(""); + return out; + }; + const residue = []; + for (const file of files) { + if (RESIDUE.test(clean(file))) residue.push(`${file}: (the path)`); + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch { + continue; + } + for (const line of text.split("\n")) { + if (RESIDUE.test(clean(line))) residue.push(`${file}: ${line.trim().slice(0, 120)}`); + } + } + return residue; +} + +// ── Main ─────────────────────────────────────────────────────── + +const files = trackedFiles(); + +if (verifyOnly && !T) { + // Without the product's values every form of the platform word and of the + // baseline's name is residue, which is what a product that kept none wants. + const residue = sweep(files, []); + report(residue, "rebrand --verify"); +} + +const LITERALS = literalPairs(); +const RULES = regexRules(files); + +// Every value a rule can write, for the sweep and for the guard below. +const produced = [ + ...LITERALS.map(([, to]) => to), + T.envPrefix, + `${T.envPrefix}_`, + T.repoSnake, + T.snakeName, + T.cliBin, + T.reponame, + T.brandSlug, + T.pascalName, + T.camelName, + T.productname, + ...workerBases(files).map((base) => `${T.brandSlug}-${base}`), +].filter((v, i, all) => v && all.indexOf(v) === i); +const RESIDUE_FOR_ALLOW = residueRe(); +const allowed = produced.filter((to) => RESIDUE_FOR_ALLOW.test(to)); + +if (verifyOnly) { + // A product whose own name or workspace contains a baseline word + // (`lumen-test`) carries it legitimately; given --values, what this rebrand + // would write is allowed exactly as the post-rename sweep allows it. + report(sweep(files, allowed), "rebrand --verify"); +} + +// What a previous run already wrote stays as written. Every phase of a +// bootstrap re-runs this over the whole tree, so the product a previous run +// branded is the input to the next one: a value some rule would match again +// is HELD wherever it already stands. +const rematchable = (v) => + LITERALS.some(([from]) => v.includes(from)) || + /\bLumen\b/.test(v) || + RULES.some(({ re }) => new RegExp(re.source).test(v)); +const guarded = produced.filter(rematchable).sort((a, b) => b.length - a.length); + +const counts = new Map(); +const bump = (label) => counts.set(label, (counts.get(label) ?? 0) + 1); + +function transform(file, input, asPath = false) { + let text = input; + const masks = []; + PROTECTED.forEach((re, i) => { + text = text.replace(re, (m) => { + const token = MASK(i, masks.length); + masks.push([token, m]); + return token; + }); + }); + for (const value of guarded) text = text.split(value).join(hold(value)); + for (const [from, to, label] of LITERALS) { + const n = text.split(from).length - 1; + if (n === 0) continue; + text = text.split(from).join(hold(to)); + for (let k = 0; k < n; k++) bump(label); + } + for (const { re, to, label, fileFilter } of RULES) { + if (fileFilter && !fileFilter(file)) continue; + text = text.replace(re, (...m) => { + bump(label); + return hold(to(file, ...m)); + }); + } + text = replaceBrandWord(file, text, () => bump("Lumen (display name; identifier in markdown code)"), asPath); + text = release(text); + for (const [token, value] of masks) text = text.split(token).join(value); + return text; +} + +const touched = new Set(); +for (const file of files) { + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch { + continue; + } + if (text.includes("\0")) continue; // binary safety net + const out = transform(file, text); + if (out !== text) { + touched.add(file); + if (!dryRun) fs.writeFileSync(file, out); + } +} + +// ── Paths ────────────────────────────────────────────────────── +// +// A path is renamed by the same rules as the text that names it, so a +// directory and the imports, routes and migration names that point into it +// stay one string. Under `git mv`, so the index (which the sweep and the +// landing both read) follows. +const renames = []; +for (const file of trackedFiles()) { + const next = transform(file, file, true); + if (next !== file) renames.push([file, next]); +} +for (const [from, to] of renames) { + bump("path renamed"); + if (dryRun) continue; + if (fs.existsSync(to)) { + console.error(`rebrand: cannot rename ${from} → ${to}: the target exists`); + process.exit(1); + } + fs.mkdirSync(path.dirname(to), { recursive: true }); + execFileSync("git", ["mv", from, to]); +} +// Directories the renames emptied. +if (!dryRun) { + const dirs = [...new Set(renames.map(([from]) => path.dirname(from)))].sort((a, b) => b.length - a.length); + for (const dir of dirs) { + for (let d = dir; d && d !== "."; d = path.dirname(d)) { + try { + if (fs.readdirSync(d).length > 0) break; + fs.rmdirSync(d); + } catch { + break; + } + } + } +} + +// ── Migration checksums ──────────────────────────────────────── +// +// The migration runner refuses a migration whose file does not hash to the +// checksum its manifest records — on plan and on apply. A migration this +// rebrand rewrote (206 renames the column it adds) is a different file, so a +// product's first db-migrate would refuse it and 03-infrastructure-database +// would never converge. A product applies every migration to an empty +// database, so its manifest records the product's own files: each migration +// THIS RUN rewrote is re-sealed. One it did not touch is left alone, so a +// hand edit to a migration still fails the runner, as it should. +const MANIFEST = "packages/db/src/manifest.ts"; +const MIGRATIONS = "packages/db/src/migrations/"; +let resealed = 0; +if (!dryRun && fs.existsSync(MANIFEST)) { + const moved = new Map(renames); + const rewritten = new Set( + [...touched].filter((f) => f.startsWith(MIGRATIONS)).map((f) => (moved.get(f) ?? f).slice(MIGRATIONS.length)), + ); + const before = fs.readFileSync(MANIFEST, "utf8"); + const after = before.replace( + /(path:\s*"([^"]+)",\s*checksum:\s*")([0-9a-f]{64})(")/g, + (whole, head, rel, sum, tail) => { + if (!rewritten.has(rel)) return whole; + const now = createHash("sha256").update(fs.readFileSync(MIGRATIONS + rel)).digest("hex"); + if (now === sum) return whole; + resealed += 1; + return head + now + tail; + }, + ); + if (after !== before) fs.writeFileSync(MANIFEST, after); + bump("migration checksum resealed"); + if (resealed === 0) counts.delete("migration checksum resealed"); + else counts.set("migration checksum resealed", resealed); +} + +console.log( + `rebrand${dryRun ? " (dry-run)" : ""}: ${touched.size} file(s) affected, ${renames.length} path(s) renamed`, +); +for (const [label, n] of counts) console.log(` ${String(n).padStart(5)} ${label}`); +if (dryRun) { + for (const [from, to] of renames) console.log(` ${from} → ${to}`); + process.exit(0); +} + +report(sweep(trackedFiles(), allowed), "rebrand", "after rename"); + +function report(residue, who, when = "") { + if (residue.length > 0) { + console.error(`${who}: ${residue.length} baseline-identity leftover(s)${when ? ` ${when}` : ""}:`); + for (const r of residue) console.error(` ${r}`); + process.exit(1); + } + console.log(`${who}: ${who === "rebrand" ? "leftover sweep clean." : "no baseline-identity leftovers."}`); + process.exit(0); +} diff --git a/tooling/rebrand/values.example.json b/tooling/rebrand/values.example.json new file mode 100644 index 0000000..e9fd967 --- /dev/null +++ b/tooling/rebrand/values.example.json @@ -0,0 +1,9 @@ +{ + "reponame": "acme-cloud", + "productname": "Acme Cloud", + "productdomain": "acme.dev", + "brandSlug": "acme", + "cliBin": "acme", + "subdomain": "your-workers-subdomain", + "salesEmail": "sales@acme.dev" +}