From 47534b308538fa321c5b686e9968a0619016c4e7 Mon Sep 17 00:00:00 2001 From: Rahul Varghese Date: Thu, 29 Oct 2026 01:30:49 +0000 Subject: [PATCH] SL4: supabase-slack-clone becomes an Orun baseline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In supabase-starter's current shape, with db-migrate between the project and the app. blueprint.yaml is the console card (github, cloudflare and supabase; the subdomain from the Cloudflare connection; no domain asked; four brokered secrets; fourteen minutes). repo-blueprint.yaml is the build: 01-product lands the whole product as one pull request and one convergence runs supabase → db-migrate → web per environment, each edge enforced on main and advisory on a pull request; it awaits only the watch and the probe, because every key the apply publishes is read fail-closed in the convergence. 02-docs records the deployment from probed facts. .baseline/ carries the identity, the product's README (Deploy by hand, Roles, Your first migration, Email, Custom domain) and its AGENTS.md, and the task contracts. The rebrand renames through the SITE_NAME seam and never rewrites a migration; the deployment record reads sign-up, the schema and the roles from /api/health; the context pack, BOOTSTRAP.md and the phase cards say how to run it. baseline.yml runs the tiers: the contract tests, the blueprint read by orun v2.88.0, the leak gate, the offline bootstrap and the product's own plans, and the e2e — the landing's checks, db-migrate's own lane steps against a Supabase stand-in that now runs the configured access-token hook, the web lane in its staged job tree with the stage wiring inlined, the deploy's own smoke refused before the migrations and passing after, and the chat driven as a member, a moderator and an admin. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_019PcpNVpFBcbeiX3EHdXfmn --- .baseline/identity.json | 9 + .baseline/product/AGENTS.md | 85 ++ .baseline/product/README.md | 206 +++++ .baseline/tasks/01-product.TaskContract.yaml | 30 + .baseline/tasks/02-docs.TaskContract.yaml | 14 + .github/workflows/baseline.yml | 156 ++++ BOOTSTRAP.md | 265 ++++++ README.md | 92 +- ai/context/current.md | 42 + ai/context/decisions.md | 21 + ai/context/deployment.md | 8 + ai/context/open-risks.md | 13 + ai/context/operations.md | 210 +++++ blueprint.yaml | 167 ++++ docs/phases/01-product.md | 143 +++ docs/phases/02-docs.md | 43 + docs/phases/README.md | 148 ++++ hooks/render-deployment-docs.sh | 191 ++++ repo-blueprint.yaml | 766 ++++++++++++++++ specs/epics/README.md | 2 +- .../IMPLEMENTATION-STATUS.md | 45 +- specs/epics/supabase-slack-clone/README.md | 3 +- testing/bootstrap-defer.test.sh | 67 ++ testing/coverage.test.sh | 264 ++++++ testing/e2e.test.sh | 516 +++++++++++ testing/fixtures/acme.json | 23 + ...aseline-identity.supabase-slack-clone.json | 9 + testing/leak.test.sh | 188 ++++ testing/lib/bootstrap.sh | 63 ++ testing/lib/chat-client.mjs | 88 ++ testing/lib/fake-supabase-api.py | 820 ++++++++++++++++++ testing/lib/local-postgres.sh | 76 ++ testing/lib/run-hooks.py | 72 ++ testing/lib/stage-job.py | 82 ++ testing/manifest.test.sh | 446 ++++++++++ testing/phases.test.sh | 568 ++++++++++++ testing/placement.test.sh | 482 ++++++++++ testing/rebrand.test.sh | 187 ++++ testing/retouch.test.sh | 199 +++++ tooling/bootstrap/dev-lanes.mjs | 114 +++ tooling/bootstrap/promotion.mjs | 123 +++ tooling/bootstrap/retouch.mjs | 254 ++++++ tooling/bootstrap/work-tree.mjs | 73 ++ tooling/catalog/gen-component-docs.py | 550 ++++++++++++ tooling/rebrand/rebrand.mjs | 491 +++++++++++ tooling/rebrand/values.example.json | 8 + 46 files changed, 8377 insertions(+), 45 deletions(-) create mode 100644 .baseline/identity.json create mode 100644 .baseline/product/AGENTS.md create mode 100644 .baseline/product/README.md create mode 100644 .baseline/tasks/01-product.TaskContract.yaml create mode 100644 .baseline/tasks/02-docs.TaskContract.yaml create mode 100644 .github/workflows/baseline.yml create mode 100644 BOOTSTRAP.md create mode 100644 ai/context/current.md create mode 100644 ai/context/decisions.md create mode 100644 ai/context/deployment.md create mode 100644 ai/context/open-risks.md create mode 100644 ai/context/operations.md create mode 100644 blueprint.yaml create mode 100644 docs/phases/01-product.md create mode 100644 docs/phases/02-docs.md create mode 100644 docs/phases/README.md create mode 100755 hooks/render-deployment-docs.sh create mode 100644 repo-blueprint.yaml create mode 100755 testing/bootstrap-defer.test.sh create mode 100755 testing/coverage.test.sh create mode 100644 testing/e2e.test.sh create mode 100644 testing/fixtures/acme.json create mode 100644 testing/fixtures/baseline-identity.supabase-slack-clone.json create mode 100755 testing/leak.test.sh create mode 100755 testing/lib/bootstrap.sh create mode 100644 testing/lib/chat-client.mjs create mode 100755 testing/lib/fake-supabase-api.py create mode 100755 testing/lib/local-postgres.sh create mode 100755 testing/lib/run-hooks.py create mode 100755 testing/lib/stage-job.py create mode 100755 testing/manifest.test.sh create mode 100755 testing/phases.test.sh create mode 100644 testing/placement.test.sh create mode 100755 testing/rebrand.test.sh create mode 100755 testing/retouch.test.sh create mode 100755 tooling/bootstrap/dev-lanes.mjs create mode 100644 tooling/bootstrap/promotion.mjs create mode 100644 tooling/bootstrap/retouch.mjs create mode 100644 tooling/bootstrap/work-tree.mjs create mode 100644 tooling/catalog/gen-component-docs.py create mode 100644 tooling/rebrand/rebrand.mjs create mode 100644 tooling/rebrand/values.example.json diff --git a/.baseline/identity.json b/.baseline/identity.json new file mode 100644 index 0000000..f926bf5 --- /dev/null +++ b/.baseline/identity.json @@ -0,0 +1,9 @@ +{ + "_comment": "THIS TREE'S OWN IDENTITY — the FROM side of every rebrand. tooling/rebrand/rebrand.mjs reads it to know what to rename AWAY from; a product's identity is the --values file, which is the TO side. Change a value here only together with the tree: these strings must be what the tree actually contains, or the rename silently misses and the product ships carrying this baseline's name. `productName` is the SITE_NAME seam in apps/web/lib/site.ts (every page's and the sign-in heading read it); `slug` also names the Supabase projects (terraform `repo`), the db-migrate parameters, the Worker and the secret project; `domain` and `subdomain` are placeholders, because this baseline has never deployed under a name of its own; `githubOwner` is the owner in this repository's source link.", + "slug": "supabase-slack-clone", + "pascal": "SupabaseSlackClone", + "productName": "Slack Clone", + "domain": "supabase-slack-clone.example.com", + "subdomain": "your-workers-subdomain", + "githubOwner": "sourceplane" +} diff --git a/.baseline/product/AGENTS.md b/.baseline/product/AGENTS.md new file mode 100644 index 0000000..c78e3e2 --- /dev/null +++ b/.baseline/product/AGENTS.md @@ -0,0 +1,85 @@ +# supabase-slack-clone — notes for coding agents + +You are in the repository of a live product. Read this before you change +anything; `README.md` is the same product told for the person who runs it. + +## What this is + +A team chat — channels, messages that arrive live, email and password +sign-up, and moderators and admins who can delete what members cannot — as a +Next.js app built by OpenNext into one Cloudflare Worker. The browser talks +to a Supabase project per environment (`stage`, `prod`) directly: Auth, the +Data API and Realtime, with the publishable key, and row-level security +decides what each user may read and write. Terraform creates the project; +db-migrate applies the chat schema to it and switches on the access-token +hook that puts each user's role in their session. Orun deploys it: a merge to +`main` converges what it changed — the Supabase project, then the schema, +then the app, stage before prod. `dev` only verifies. + +| component | path | what it is | +|---|---|---| +| `web` | `apps/web` | the app and its Worker build (`component.yaml`, `next.config.ts`, `wrangler.template.jsonc`) | +| `supabase` | `infra/terraform/supabase` | the Supabase project per environment and its Auth settings | +| `db` | `packages/db` | the migrations, their manifest and the runner db-migrate calls | +| `db-migrate` | `infra/db-migrate` | applies `packages/db` to each environment's project | +| `db-tests` | `tests/db` | the schema's tests, on a Supabase-shaped Postgres in process | +| `web-tests` | `tests/web` | the app's vitest suite | + +`intent.yaml` declares the environments, the workspace and how CI plans; each +`component.yaml` declares one component and what it depends on. + +## Read first + +1. `README.md` — what is where, running it locally, "Roles", "Your first + migration", "Custom domain". +2. `ai/context/operations.md` — how a deploy works, the secrets model, + row-level security and roles, the common operations. +3. `ai/context/deployment.md` — the live URLs, the workspace and the secrets, + by name, as last probed. +4. `apps/web/lib/Store.js` — the Supabase client, the data hooks and the + Realtime subscriptions every page uses. +5. `packages/db/src/migrations` and `packages/db/src/auth-config.ts` — the + schema, its policies and the Auth hook the runner enables after them. + +## How a change lands + +- Work is tracked as tasks on the Orun workspace (`orun task list`). One task, + one branch, one pull request against `main` — `orun pr open` names the + branch after the task and records it in the pull request. +- Before you push: `pnpm install`, `pnpm run wire:fixture`, `pnpm typecheck`, + `pnpm lint`, `pnpm test`, `pnpm build`. Nothing runs them for you: the pull + request's `ci.yml` lanes build and dry-deploy the app, plan the Supabase + root and the migrations, and type-check, lint and test nothing. `orun + validate` and `orun plan` show what `ci.yml` will plan. +- Merging is deploying. Watch the run on `main`, then probe the URLs in + `ai/context/deployment.md`: a run that planned nothing deployed nothing. +- A schema change is a NEW migration directory under + `packages/db/src/migrations` plus its entry in `packages/db/src/manifest.ts` + (`pnpm --filter @saas/db run manifest:fix` writes the checksum). A table in + `public` gets row-level security and its policies in the migration that + creates it — the publishable key is public by design. A table the chat + should stream joins the `supabase_realtime` publication in a migration too. +- A new component is a directory under `apps/`, `infra/` or `packages/` with a + `component.yaml`, declaring `dependsOn` on any infrastructure whose + published secrets it reads. + +## Do not touch + +- `execution.state.workspace` in `intent.yaml`: every remote operation and + every CI credential is scoped to it. +- An applied migration. db-migrate compares every file's sha256 with the + manifest and with the database's own ledger, and refuses a changed one. +- `apps/web/wrangler.jsonc` by hand: edit `wrangler.template.jsonc` and run + `pnpm run wire:fixture`. Never commit a real project's URL or key. +- `ai/context/deployment.md`, and the README between `<!-- 02-docs:begin -->` + and `<!-- 02-docs:end -->`: both are rendered from probes. +- The Auth URLs and the access-token hook in the Supabase dashboard: the + apply owns the Site URL, the redirect allow-list and `mailer_autoconfirm`, + db-migrate owns the hook, and each undoes a dashboard edit on its next run. +- Secret values, anywhere — the repository, `ai/context/`, a log, GitHub. + Provider credentials are brokered per run; secrets are inspected by name. +- `ci.yml` as the only workflow on a push to `main`: whatever watches a + merge reads the newest run for its commit, and a second workflow there + could be the run it reads. +- The last line of a `component.yaml` (`# orun: redeploy …`) is a deploy + trigger; change it only to redeploy that component. diff --git a/.baseline/product/README.md b/.baseline/product/README.md new file mode 100644 index 0000000..e3f7aef --- /dev/null +++ b/.baseline/product/README.md @@ -0,0 +1,206 @@ +# supabase-slack-clone + +Supabase's [Slack clone](https://github.com/supabase/supabase/tree/master/examples/slack-clone/nextjs-slack-clone) +— a team chat with channels, messages that arrive live over Supabase +Realtime, email and password sign-up, and moderator and admin roles carried +in every session by an Auth hook and enforced by row-level security — on +**Cloudflare Workers + Static Assets** through +[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with a +**Supabase** project per environment provisioned by Terraform and its schema +applied by migrations, on every merge to `main`. + +## Live deployment + +<!-- 02-docs:begin --> +Not recorded yet. The bootstrap's last phase writes the live URLs, the +workspace, how sign-up behaves on each environment and the secrets the +product uses 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). +<!-- 02-docs:end --> + +## What is here + +| Surface | Where | +|---|---| +| The product's name | `apps/web/lib/site.ts` | +| Sign-in and sign-up, the channel pages, `/api/health` | `apps/web/pages` | +| The Supabase client, the data hooks and the Realtime subscriptions | `apps/web/lib/Store.js` | +| The sidebar, a message, the message box | `apps/web/components` | +| Workers build and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc`, `component.yaml` | +| The Supabase project (stage, prod) and its Auth settings | `infra/terraform/supabase` | +| The schema — tables, roles, policies, the access-token hook, the Realtime publication, the two starter channels — and its runner | `packages/db` (applied by `infra/db-migrate`) | +| Tests | `tests/web` (the app), `tests/db` (the schema, on Postgres in process) | + +A coding agent starts at [AGENTS.md](AGENTS.md): what to read first, how a +change lands, and what not to touch. + +## Getting started + +```bash +pnpm install +pnpm run wire:fixture # re-render apps/web/wrangler.jsonc from its template (it is committed) +pnpm typecheck +pnpm lint +pnpm test +pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next +``` + +Run them before you push: a pull request's CI builds and dry-deploys the +app and plans the migrations, but type-checks, lints and tests nothing. + +The build needs no Supabase project: without one it inlines the committed +`wrangler.jsonc`'s placeholder values, and nothing calls them. + +## Running it locally + +Against one of the product's own projects (stage is the natural one — its +URL and publishable key are in the Supabase dashboard → Project Settings → +API), or any Supabase project with the schema applied: + +1. Copy `apps/web/.env.example` to `apps/web/.env.local` and fill in the two + values. `next dev` and `pnpm build` read it. +2. Run Next's dev server — + + ```bash + pnpm --filter @app/web dev # http://localhost:3000 + ``` + + — or the built Worker under `wrangler dev`, with the same two values in + `apps/web/.dev.vars` (copy `.dev.vars.example`): + + ```bash + pnpm build + pnpm --filter @app/web preview # http://localhost:8787 + ``` + +A project of your own gets the schema from the same runner the pipeline +uses — a Supabase access token and the project's ref in the environment, +then: + +```bash +pnpm --filter @saas/db build +SUPABASE_ACCESS_TOKEN=… SUPABASE_PROJECT_REF=… node packages/db/dist/runner/cli.js apply --env stage +``` + +It applies every migration the project has not had, then switches on the +access-token hook. + +## How it deploys + +Merges to `main` converge through [Orun](https://github.com/sourceplane/orun): +`.github/workflows/ci.yml` plans the changed components and runs each lane +against the workspace in `intent.yaml`. Per environment the order is +enforced — **the Supabase project, then the migrations, then the Worker** — +because each reads what the one before it left: the migrations read the +project's ref and credentials, and the app's build reads the project's URL +and publishable key (`WIRING_SUPABASE`), renders them into the Worker's vars +and inlines them into the browser bundle, and talks to the tables the +migrations made. `stage` deploys first and `prod` once stage has converged +on the same commit; `dev` only verifies. Every deploy is smoke-tested over +HTTP, `/api/health` included, which answers only when the project's Auth +answers the key the build inlined and its Data API knows the chat's tables. + +The pipeline holds one credential, GitHub's own `GITHUB_TOKEN`. The +Cloudflare token and account id and the Supabase access token and org id are +brokered per run from the workspace's connections; the project's URL and +publishable key and its database credentials are published by the Terraform +apply as orun secrets. Nothing provider-shaped is stored in the repository +or in GitHub, and no service-role key is read anywhere: the chat runs in the +browser with the publishable key, and row-level security is the boundary. + +**Deploy by hand.** Orunbase's **Deploy** button on a component, or **Run +workflow** on the CI workflow in GitHub's Actions tab (on `main`), runs +`ci.yml` for the environment and components you pick, and each one deploys +exactly as a merge would deploy it. Leave the component blank to redeploy +every component in that environment, with nothing changed: after rotating a +secret, say. A component with nothing to run in that environment (a test +suite in `prod`) is left out with a notice. + +## Roles + +Every new user is a **member**: they read every channel and message, post, +and delete their own messages and the channels they created. Roles beyond +that are rows in `public.user_roles`, and each session carries the user's +role as its `user_role` claim — put there by the access-token hook +(`public.custom_access_token_hook`), which db-migrate switches on in each +project's Auth after the migrations. Row-level security reads the claim +through `public.authorize()`: + +| role | may also | +|---|---| +| `moderator` | delete any message | +| `admin` | delete any message and any channel | + +As upstream ships it, an address with `+supamod@` in it signs up as a +moderator and one with `+supaadmin@` as an admin (`handle_new_user`, the +trigger on `auth.users`). That is a demo's convenience — anyone can choose +such an address. Before real users arrive, replace it with a migration that +drops those two branches, and grant roles by inserting into +`public.user_roles` (Supabase dashboard → SQL editor) instead. A role takes +effect at the user's next sign-in or token refresh. + +## Your first migration + +A schema change is a new directory under `packages/db/src/migrations` +(`040_<name>/up.sql`), its entry in `packages/db/src/manifest.ts`, and +`pnpm --filter @saas/db run manifest:fix` to write its checksum. Merge it and +db-migrate applies it, stage then prod, before the app deploys. An applied +migration is never edited: the runner compares every file with its checksum +and with the project's own ledger, and refuses a changed one. A table in +`public` gets row-level security and its policies in the migration that +creates it; a table the chat should stream joins the `supabase_realtime` +publication there too, with `replica identity full` if a delete must carry +the row. `tests/db` runs every migration on Postgres in process and holds the +policies to their roles. + +## Email + +A Supabase project without an SMTP server of its own emails only the members +of its organization, a few times an hour. So each project is created with +email confirmation **off**: a new user is signed in the moment they sign up, +and anyone can. + +To require confirmation, give each project SMTP of its own (Supabase +dashboard → Authentication → Emails → SMTP Settings), then set +`authEmailConfirmation: "true"` in `infra/terraform/supabase/component.yaml` +and merge. The sign-in page then tells a new user to look for the email, and +the link brings them back to the app, the project's Site URL. + +## Custom domain + +The app answers on workers.dev from its first deploy. To serve it on your +own domain: + +1. Attach the domain to the Worker in Cloudflare (Workers & Pages → + `supabase-slack-clone-web-prod` → Settings → Domains & Routes). +2. Set `SITE_URL: https://<your-domain>` under `environments.prod.env` in + `intent.yaml`. It is the one setting for the product's origin: the + supabase apply makes it the project's Auth Site URL and redirect + allow-list, where Supabase's emails send people. +3. Redeploy the project: change the last line of + `infra/terraform/supabase/component.yaml` (`# orun: redeploy …`) in the + same pull request — a change to `intent.yaml` alone plans nothing. + +The apply owns the project's Auth URLs: an edit in the Supabase dashboard is +undone by the next apply. + +The repository also names the domain in one place, `BASE_DOMAIN` under each +environment's `env:` in `intent.yaml`, which the product was born with as the +reserved placeholder `supabase-slack-clone.example.com`. Nothing builds a URL +from it — the origin is `SITE_URL` — so replacing it moves nothing by itself; +it records the domain. Replace it with yours in the same pull request as +`SITE_URL`. + +## CI + +| Workflow | What it runs | +|---|---| +| `ci.yml` | the Orun pipeline, and the only workflow: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes — the app built and dry-deployed for each environment, the Supabase root checked and planned, the migrations' checksums verified offline — with nothing applied or deployed (typecheck, lint and the tests are `pnpm` scripts you run before you push, above); a merge applies and deploys stage → prod | + +## Licence + +The app is Supabase's example, under the Apache License 2.0 of the +[supabase/supabase](https://github.com/supabase/supabase) repository it +lives in (`apps/web/LICENSE`); its own `package.json` says MIT. The rest of +this repository is the product's. diff --git a/.baseline/tasks/01-product.TaskContract.yaml b/.baseline/tasks/01-product.TaskContract.yaml new file mode 100644 index 0000000..2250efc --- /dev/null +++ b/.baseline/tasks/01-product.TaskContract.yaml @@ -0,0 +1,30 @@ +# Task contract template for the 01-product landing. +# Unbound to a key on purpose: `orun.task/ensure@v1` seals and attaches it to +# the key the allocator issues. It lives under `.baseline/`, not `tasks/`, +# because `tasks/` is this repository's own work tree (`intent.yaml` `work:`), +# where an unkeyed contract is an error. gates: [] is a DECLARATION — merge +# alone finishes this task; the main convergence is the gate the bootstrap +# watches, not one the plane observes as a PR check. +# +# The whole product in one landing. `affects` names COMPONENTS, by +# metadata.name — every one the bootstrap's convergence plans on stage and +# prod (db and the two test packages verify on dev, which the bootstrap keeps +# off main until 02-docs, so a marker on them would re-plan nothing): the +# phase's retouch hook reads this list to decide which component.yaml files +# get the redeploy marker, so a re-run after a failed convergence has a diff and +# re-plans exactly these — the deploy set and the task plane's statement of +# the work are one list. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The product's repository is born and linked, the whole product lands in one pull request, and one convergence provisions the Supabase project, migrates the schema and deploys the app on stage and prod + affects: + - supabase + - db-migrate + - web + doneWhen: + - repo pushed, main pinned as default, workspace linked + - SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD, SUPABASE_DB_URL and WIRING_SUPABASE published on stage and prod + - the chat schema applied and the access-token hook switched on, then the app deployed and smoke-tested, on stage and prod, in the order supabase → db-migrate → web + - the home page and /api/health answer on both workers.dev URLs + gates: [] diff --git a/.baseline/tasks/02-docs.TaskContract.yaml b/.baseline/tasks/02-docs.TaskContract.yaml new file mode 100644 index 0000000..bf6e30b --- /dev/null +++ b/.baseline/tasks/02-docs.TaskContract.yaml @@ -0,0 +1,14 @@ +# Task contract template for the 02-docs landing. See 01-product's header. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The live deployment is recorded from verified facts as agent-readable state in the product's repo, and the bootstrap's deferrals are put back + affects: + - ai/context/deployment.md + - ai/context/operations.md + - README.md + - intent.yaml + doneWhen: + - committed deployment manifest matches probed reality + - prod waits on stage again, and dev verifies every merge to main again + gates: [] diff --git a/.github/workflows/baseline.yml b/.github/workflows/baseline.yml new file mode 100644 index 0000000..95c45e9 --- /dev/null +++ b/.github/workflows/baseline.yml @@ -0,0 +1,156 @@ +name: Baseline CI + +# THE FACTORY'S OWN LANES — this repository tested as a BASELINE: that its +# build document parses with the orun a bootstrap actually runs, that its card +# agrees with it, that every component is placed by exactly one phase, that a +# placed tree comes up branded and carrying nothing of the factory, that the +# product's own push-to-main plan converges the Supabase project, then its +# schema, then the app, and that the product installs, builds, migrates, +# deploys (dry), serves, and chats — members, a moderator and an admin +# through Supabase Auth, the Data API and the access-token hook (a local +# stand-in). +# +# ─── WHY THIS IS NOT IN ci.yml ──────────────────────────────────────────── +# +# `repo-blueprint.yaml`'s `github-workflows` module copies the WHOLE `.github` +# directory into every product built from this repository. 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. This +# file is in the blueprint's `ignore` list, and `testing/coverage.test.sh` +# fails on any workflow that reads `testing/` and is not. + +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: + # Tier 0. bash, python3 and git; node for the tools. No workspace install, + # no network, no credential — the job that most certainly fails a PR. + baseline-contract: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-node@v5 + with: + node-version: 22 + # setup-node v5 turns on the pnpm cache by itself when package.json + # names a packageManager, and then fails on a runner with no pnpm. + # This job installs nothing. + package-manager-cache: false + - name: Contract tests (manifest, phases, coverage, rebrand, retouch, bootstrap-defer) + 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; do + echo "── $t" + bash "testing/$t.test.sh" + done + # Every component's docs/{overview,architecture,runbook}.md is generated + # from what the component declares (its manifest, Worker config, + # Terraform, migrations, package scripts). A pull request that changes + # one of those facts without regenerating the pages fails here. + - name: Component docs match their manifests + run: python3 tooling/catalog/gen-component-docs.py --check + + # Tier 1. THE BLUEPRINT, READ AND PLACED BY THE BINARY A BOOTSTRAP RUNS. + # + # Pinned at the bootstrap floor (BOOTSTRAP.md), not the product's lane pin: + # every test here reads YAML with PyYAML, which parses anything well-formed; + # only the pinned orun can say whether the document is one a bootstrap can + # run. `--status` parses it, validates every hook against the action + # registry, compiles every `when` and narration template, and writes + # nothing. Then the leak gate (what a product would carry) and the + # placement tier (the offline bootstrap: both phases placed and finished by + # the blueprint's own hooks, then the product's own `orun plan` for the + # 01-product merge — supabase, then db-migrate, then web, enforced — and a + # --resume that changes nothing). The floor is v2.88.0 (the task set-up in the + # background, the landings checked in the box, the deploy credentials + # minted in one `secrets` reconcile per provider), newer than the product's + # lane pin (v2.78.4, ci.yml), so the product's own plans here read the + # per-edge `modeRules` as its CI does. + blueprint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: sourceplane/orun-action@v1.2.0 + with: + version: v2.88.0 + - uses: pnpm/action-setup@v4 + with: + version: 10.12.1 + - uses: actions/setup-node@v5 + with: + node-version: 22 + # This job installs nothing either: with no lockfile hook the offline + # bootstrap never runs pnpm, so there is no store, and the pnpm cache + # setup-node v5 turns on by itself (package.json names a packageManager) + # fails the job saving a path that does not exist whenever no earlier + # cache exists for the lockfile. + package-manager-cache: false + - name: repo-blueprint.yaml, read by the pinned CLI + run: | + set -euo pipefail + orun --version + python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml + # Required inputs must be supplied for the document to resolve; the + # values are arbitrary and nothing is written. + orun new --blueprint repo-blueprint.yaml --status \ + --out "$(mktemp -d)" \ + --set reponame=acme-chat \ + --set "productname=Acme Chat" \ + --set githuborg=acme-inc + - name: the leak gate — what a product carries + run: bash testing/leak.test.sh + - name: placement — the offline bootstrap, and the product's own plan + run: | + git config --global user.email ci@example.invalid + git config --global user.name "baseline ci" + bash testing/placement.test.sh + + # Tier 2. THE PRODUCT IT PRODUCES WORKS: the 01-product landing installed, + # its fixture rendered, type-checked, linted, tested and built (its own pull + # request runs `plan` alone, and the landing is checked in the box with + # `orun validate` and `orun plan`); a Supabase project stood in for — a + # local Postgres with Supabase's roles and its auth schema, Auth with the + # access-token hook, the Data API and the Management API's query and Auth + # config endpoints (testing/lib/fake-supabase-api.py); the chat schema + # applied by db-migrate's own lane steps; the stage lane's own structure + # check, build — inlining the stage wiring it is handed — output check and + # dry deploy in the job tree orun stages; and the built Worker served over + # that project — its smoke refused before the migrations and passed after, + # every route, and the chat as the browser drives it: a member, a moderator + # and an admin signed up with their roles in their sessions, the starter + # channels, a message posted and read back with its author, deletes + # allowed and refused by role, and nothing for an anonymous caller. + # Pinned at the bootstrap floor (v2.88.0): the offline bootstrap reads the + # blueprint, and the floor is newer than the product's lane pin (v2.78.4), + # which is all the lane steps need. The runner image carries PostgreSQL 16 + # (not started); the test starts its own on a random port. + product: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: sourceplane/orun-action@v1.2.0 + with: + version: v2.88.0 + - uses: pnpm/action-setup@v4 + with: + version: 10.12.1 + - uses: actions/setup-node@v5 + with: + node-version: 22 + cache: pnpm + - name: e2e — the bootstrapped product builds, migrates, deploys (dry), serves and chats + run: | + python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml + git config --global user.email ci@example.invalid + git config --global user.name "baseline ci" + bash testing/e2e.test.sh diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md new file mode 100644 index 0000000..3d775c3 --- /dev/null +++ b/BOOTSTRAP.md @@ -0,0 +1,265 @@ +# BOOTSTRAP — a new product from this baseline, in one landing + +How to go from **nothing** to **a team chat live on stage and prod — its own +Supabase project per environment, migrated, Auth pointed at the app and its +roles hook on, sign-up open, two channels waiting — documented**, with two +provider consents. + +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. The console card the platform renders is +**`blueprint.yaml`**; it names the build document and states the inputs, the +brokered secrets and the programme, and `testing/manifest.test.sh` holds it +to what the build document does. + +Target wall-clock: **about fourteen minutes** — an estimate summed from the +phases (13 + 1) until a bootstrap measures it. The shape: the task set-up in +the background while ONE landing is placed, branded and checked in the box +(`orun validate` and `orun plan`, no runner waited for), then one convergence +per environment (stage and prod side by side until `02-docs` restores the +promotion gate) that creates the Supabase project (five to seven minutes), +sets its Auth, applies the chat schema and switches on its access-token +hook, and builds and deploys the app, in that order, then a short docs +landing. + +## 0. What you need + +- GitHub org access (repository creation) and a machine with `git`, `node` + (≥ 22), `pnpm` (10.12.1), `python3` with PyYAML, `curl`, and the `orun` + CLI **≥ v2.88.0** — the floor for RUNNING the bootstrap (the phase overlay, + `githubOwner` on the doctor probe, `environments` on the secrets probe, + `from: workspace`, a landing's `label`, the deploy credentials minted in + one `secrets` reconcile per provider, the task set-up run in the + background (`background: true`), and landings checked in the box before + they merge (`checks: local`)). The product's own `ci.yml` pins its + lanes separately (v2.78.4), and that pin — or anything newer, as the floor + is — is what reads the per-edge `mode` rules the convergence order relies + on. +- A **Cloudflare** account (the free plan is enough for one Worker with + static assets) and its Account API token with the permission groups the + console's Connect recipe lists — Workers Scripts among them. +- **A Supabase organization with room for two more projects** — + `<reponame>-stage` and `<reponame>-prod`. Supabase's free plan allows two + active projects per organization, so on the free plan that is the whole + allowance: pause or delete what else is there first, or use a paid + organization. It is connected to the workspace by OAuth consent (console → + Integrations → Supabase) — or by a pasted personal access token. The + connection is anchored on ONE organization, and that is where both + projects are created. +- 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 (secret writes below admin are + masked as `not_found`). +- **The repository allow-listed in the workspace** (console → Settings → Git + repos), unless the credential can write links. `01-product`'s `link` step + stops and names the fix if it is not. +- **Not an SMTP server.** Each project is created with email confirmation + off, so sign-up works on the first deploy without one; the owner adds SMTP + and turns confirmation on later (§3). +- **Not a service-role key.** The chat runs in the browser with the + publishable key; nothing reads a service-role key, and none is published. + +## 1. One command: `--resume` + +The whole bootstrap, unattended. `--resume` places every phase not already +derived as done, in order, honouring each phase's barrier: + +```bash +git clone --depth 1 --branch <baseline-tag> https://github.com/sourceplane/supabase-slack-clone +cd supabase-slack-clone + +orun new --blueprint repo-blueprint.yaml \ + --out ~/products/acme-chat --run-hooks --resume \ + --set reponame=acme-chat --set productname="Acme Chat" \ + --set githuborg=acme-inc \ + --set orunWorkspace=ws_XXXXXXXX \ + --set subdomain=<workers-dev-subdomain> +``` + +`subdomain` is the workers.dev subdomain of the Cloudflare account you deploy +into (Workers & Pages → your subdomain). 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. + +**`--run-hooks` is the difference between placing files and bootstrapping a +product.** Without it `orun new` writes the tree and stops: no repository, no +landing, no convergence watch, no probe. That is deliberate — it is what +makes the offline bootstrap in `testing/` possible with no workspace and no +provider. + +`--resume` is safe to re-run from anywhere, a fresh container with a fresh +`--out` included: **phase state is derived from the tree, never stored.** A +phase whose files are present but branded derives as `drifted`, and +`--resume` leaves it placed rather than reverting the product's identity. + +## 1b. Or phase by phase + +| phase | what it lands | verified by | +|---|---|---| +| `01-product` | the repository, created and linked; the four brokered credentials; then the whole product in one PR — intent, CI, tooling, identity, the Supabase Terraform root, the migrations, the app and their tests | its commit validated and planned in the box (as the PR and as the merge), then merged; the convergence green (supabase → db-migrate → web, per environment — the migrations resolving the database credentials and the app's deploy the `WIRING_SUPABASE` the apply before them published, each fail-closed); `/` and `/api/health` answering on both workers.dev URLs, which says the project answered the build's key and its Data API knows the chat's tables | +| `02-docs` | `ai/context/deployment.md` from probed facts (how sign-up behaves and whether the schema is in place included); prod's promotion gate and dev's push lanes restored | the render's own probes, recorded; the commit checked in the box and merged | + +```bash +orun new --blueprint repo-blueprint.yaml --out ~/products/acme-chat --run-hooks \ + --phase 01-product --values ~/acme-chat.values.yaml +# … then 02-docs +``` + +`02-docs` reads the identity back from `.rebrand/values.json` in the placed +tree, but the blueprint's **required** inputs — `reponame`, `productname`, +`githuborg` — are validated before anything runs, so pass them every time (a +`--values` file is easier). The domain is not one of them: the app goes live +on workers.dev, and `productdomain` defaults to empty, which brands the +reserved placeholder `<reponame>.example.com` into `BASE_DOMAIN` for an owner +to replace when they attach a domain (README, "Custom domain"). Pass +`--set productdomain=` only for a product that already has its domain. +The full guide, one page per phase: [docs/phases/README.md](docs/phases/README.md). + +| flag | what it does | +|---|---| +| `--status` | derives and prints every phase's state and writes nothing. It parses the document, validates each hook against the action registry and compiles every template; it needs no credential and no network | +| `--phase <name>` | places exactly that phase; its `requires.phases` still gates | +| `--until <name>` | places every phase through that one and stops | + +What lands in the product is PRODUCT-ONLY: the app, the Terraform root, the +migrations, the tests, its CI, its tooling, its README, its AGENTS.md and its +two context pages. None of +this repository's machinery (`.baseline/`, the blueprints, `tooling/rebrand`, +`tooling/bootstrap`, `hooks/`, `testing/`, `docs/phases/`, `specs/`, +`tasks/`, this file) ships, and no shipped file names any of it. That +promise is a test: `testing/leak.test.sh` derives what every phase would +place and gates the set and every file's text, and +`testing/placement.test.sh` gates the same rules over a placed, branded tree. + +## 2. Headless / container mode + +The blueprint's source is this repository (`sources: [{kind: dir, path: .}]`), +so the container contract is a shallow clone at a pinned tag plus two +tokens: + +```bash +export ORUN_TOKEN=… # orun auth, headless +export GITHUB_TOKEN=… # fine-grained PAT (below) + +git clone --depth 1 --branch <baseline-tag> https://github.com/sourceplane/supabase-slack-clone +cd supabase-slack-clone +orun new --blueprint repo-blueprint.yaml \ + --out /work/acme-chat --run-hooks --resume --progress json \ + --values /work/acme-chat.values.yaml +``` + +| requirement | detail | +|---|---| +| `GITHUB_TOKEN` | fine-grained PAT: **read** on this repository; on the PRODUCT's repository **contents write**, **pull-requests write**, **actions read+write** (`orun.run/watch@v1` resumes runs with `gh run rerun`), **checks read**; **repository create** on the owner if `01-product` creates it (or pre-create it — supported) | +| classic token caveat | a classic PAT or gh OAuth token also needs the `workflow` scope to push `.github/workflows/` | +| pinning | the clone's `--branch <tag>` pins everything: the blueprint, its modules and its hooks' scripts all come from that one commit | + +## 3. After the product is live + +- **Sign-up works** on both environments: confirmation is off, so a new user + is signed in the moment they sign up and lands in `#public`. +- **Roles**: every new user is a member. As upstream ships it, an address + with `+supamod@` signs up as a moderator and one with `+supaadmin@` as an + admin — a demo's convenience anyone can use. Replace that trigger in a + migration before real users arrive, and grant roles in + `public.user_roles` (the product's README, "Roles"). +- **Email confirmation** (per environment, optional): give the project SMTP + of its own (Supabase dashboard → Authentication → Emails → SMTP Settings), + set `authEmailConfirmation: "true"` in the product's + `infra/terraform/supabase/component.yaml` and merge. The product's README, + "Email", is the owner's copy of this. +- **Schema changes** are new migrations under `packages/db/src/migrations` + (the product's README, "Your first migration"); every table in `public` + needs RLS — the publishable key is public by design. +- **Custom domain**: attach it to the Worker in Cloudflare, then set + `SITE_URL` under the environment's `env:` in the product's `intent.yaml` — + the project's Auth Site URL follows it — and redeploy supabase (the + product's README, "Custom domain"). + There is no domain phase: attaching a domain needs zone permissions the + brokered `workers-deploy` token does not carry. +- **Refresh the record**: re-run `--phase 02-docs`; it is idempotent, and it + records whether sign-up asks for confirmation and whether the schema is in + place. + +## 4. Testing this baseline + +`.github/workflows/baseline.yml` runs three tiers on every pull request, and +each runs locally the same way: + +```bash +for t in manifest phases coverage rebrand retouch bootstrap-defer; do bash testing/$t.test.sh; done +bash testing/leak.test.sh # needs orun +bash testing/placement.test.sh # needs orun, node, pnpm: the offline bootstrap and the product's own plans +bash testing/e2e.test.sh # + network for pnpm, psql and a PostgreSQL server install +``` + +The offline bootstrap (`testing/lib/bootstrap.sh`) places both phases in +order and finishes each with the blueprint's OWN `run:` hooks — read out of +`repo-blueprint.yaml`, not transcribed — so the retouch marker, the rebrand, +the re-tenant, the deferrals and their restore and the deployment record +all run exactly as a real bootstrap runs them. Only the +platform's typed actions (task, repo, reconcile, land, watch, secrets, +probe) and the `link` step are stood in for, a landing becoming a commit. + +What no test here can do is the clouds' half: create a Supabase project, read +its API keys, set its Auth, mint a token, deploy for real. The Terraform root +is held to `fmt`, `init -backend=false` and `validate` (a real `plan` reads +Supabase's API and the platform's state backend); the convergence ORDER is +proven on the product's own `orun plan`; and the app's Supabase is a local +stand-in — a Postgres with Supabase's roles, `auth` schema and Realtime +publication, and the Auth (with the access-token hook), Data API and +Management API endpoints the app and the migration runner call +(`testing/lib/fake-supabase-api.py`). db-migrate's own lane steps apply the +schema to it and switch the hook on; the built Worker's smoke is refused +before that and passes after; and the chat is driven as the browser drives +it — a member, a moderator and an admin, their roles in their sessions, +messages posted, read and deleted by role, and nothing for the bare +publishable key. Realtime's websocket is not stood in for; the publication +it streams is checked instead. + +## 5. Cutting a baseline tag (maintainers) + +Every product built from this repository resolves a `baseline-vN` tag, so the +tag is cut by a workflow rather than by hand: + +```bash +gh workflow run tag.yml -f version=baseline-v1 # from main +gh workflow run tag.yml -f version=baseline-v1 -f ref=<sha> +``` + +It refuses a version that is not `baseline-v<N>` and a tag that already +exists: a baseline tag is never moved. Then add (or move) the registry row in +orun-cloud's `infra/baselines-registry/baselines.yaml` by pull request — +after the tag exists, because the registry's sync fetches `blueprint.yaml` +at the tag and refuses the whole catalogue if it 404s. + +## Troubleshooting + +| Symptom | Cause → fix | +|---|---| +| `01-product` parks: `waiting for github for <org>` | the workspace's GitHub connection is to another account. Connect the App installation on `<org>` (console → Integrations → GitHub), then `--resume` | +| `01-product` parks on the `providers` probe for cloudflare or supabase | that connection is missing. Connect it (console → Integrations); the probe is a wait, not a failure | +| `01-product` stops at `link` | the repository is not linked to the workspace and the credential cannot link it. Allow-list it (console → Settings → Git repos) and re-run the phase | +| Secret WRITE fails `not_found` while listings work | the API key's role is below admin; re-mint it with the admin role | +| supabase apply: project limit reached | the organization has no room for the two projects stage and prod need (the free plan allows two active projects per organization). Pause or delete one, or upgrade, then re-run `01-product` | +| supabase apply: `does not support oauth access` | a supabase provider ≥ 1.6 reads billing endpoints the brokered OAuth token cannot; the root pins `~> 1.5.1` — keep it | +| supabase apply: `Unable to read API keys` / `Unable to update auth settings` | the Supabase connection's grant does not cover the project's API keys or its Auth configuration (not yet exercised live with the platform's OAuth app). Reconnect Supabase with a personal access token and re-run `01-product`; the reconcile re-mints only what is missing | +| db-migrate: `PATCH config/auth answered HTTP 401/403` | the same grant, from the migration runner: the token reaches the query endpoint but not the project's Auth config. Reconnect as above; the migrations already applied are not applied again | +| db-migrate: `checksum mismatch` | an applied migration was edited. Put the file back as it was applied, and make the change a new migration | +| Signed in, but the delete buttons never appear for a `+supamod@` or `+supaadmin@` user | the session has no `user_role` claim: the hook is off in that project's Auth (Authentication → Hooks). db-migrate turns it on after every apply — redeploy db-migrate (its `component.yaml` redeploy line) and sign in again | +| web: `wire: missing wiring documents … WIRING_SUPABASE_<ENV>` | the supabase apply for that environment did not publish; its lane's log says why. web waits on it, enforced — and this is the check that the wiring is there: nothing awaits it separately | +| `land` stops: `the landing's own check failed — orun plan for …` | the product's tree does not plan — the line after it is orun's own error (an unknown component type, a composition that does not resolve). Nothing was pushed. Fix the tree (or the baseline) and re-run the phase | +| `land` waits on CI after all | the product's repository requires a status check on `main` (branch protection or a ruleset), so GitHub refused the early merge; the landing waits for the check as a `checks: ci` landing would, then merges | +| web smoke: `/api/health` 503 | `schema: not migrated` — db-migrate has not run against this project (web waits on it, enforced, on main; a hand deploy of web alone can outrun it); `auth: key refused` — the inlined key is not the project's; `auth: unreachable` — the project is paused or still coming up | +| `build-app` fails: `Symlink apps/web/node_modules/next is invalid, it points out of the filesystem root` | the product's intent pins stack-tectonic ≥ 0.20.0, whose lane-scoped install links each job's node_modules out of its tree, which Next 16's Turbopack refuses. Pin 0.19.0 (`intent.yaml` says why) | +| `verify-app-structure` fails: `test -f "wrangler.jsonc"` | the product's `apps/web/wrangler.jsonc` is not committed. It must be — the check runs before the build in a fresh checkout (`pnpm run wire:fixture` renders it) | +| Sign-up says the address cannot be mailed | confirmation was turned on without SMTP: Supabase's own email reaches only the organization's members. Add SMTP, or set `authEmailConfirmation` back to `"false"` | +| The app sends a signed-in user to `/channels/1` and shows nothing | `#public` (channel 1, from `030_seed`) was deleted. Re-create it in a migration | +| Convergence failed AFTER the PR merged; re-running lands nothing | expected on its own — the files are on main. Re-run the phase (`--phase 01-product`, `--redo 01-product`, or the console's Retry): its `retouch` hook gives the landing a diff and the components re-plan; the project is adopted, not recreated | +| The convergence reported green, then `verify` got 404 | a second workflow ran on the push to main and the watch took its run. Only `ci.yml` may run on a push to main | +| The product's `intent.yaml` says `workspace: ws_SET_ME` | `orunWorkspace` was empty and the build ran outside a workspace; set it and re-run `01-product` | +| A bootstrap stopped before `02-docs`; prod no longer waits on stage | the gate is deferred, not dropped: run `02-docs`, or `node tooling/bootstrap/promotion.mjs --restore --file <product>/intent.yaml` | +| `✕ input "productname" is required` | all three required inputs (`reponame`, `productname`, `githuborg`) must be set on every invocation, single-phase ones included | +| `unknown flag: --phase`, `has no parameter "checks"`, `has no parameter "secrets"` or another parse error in the blueprint | the CLI is below the v2.88.0 floor | diff --git a/README.md b/README.md index 7905cea..72afa64 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,9 @@ on **Cloudflare Workers + Static Assets** through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with the Supabase project itself provisioned by Terraform and its schema applied by migrations through [Orun](https://github.com/sourceplane/orun), and packaged -as an **Orun baseline** in SL4: one command will take a new product from -nothing to live on stage and prod, in its own repository, under its own -name, in ONE landing. +as an **Orun baseline**: one command takes a new product from nothing to +live on stage and prod, in its own repository, under its own name, in ONE +landing. The example's code is the code. What the port changes is what the Workers runtime and a fresh, unattended deployment force: `next` pinned (upstream @@ -23,14 +23,58 @@ the access-token hook `supabase/config.toml` switched on set by that runner through the Management API, each project created with its Auth pointed at the Worker and email confirmation off (so anyone can sign up on the first deploy, with no SMTP server), and a read-only `/api/health` only the Worker -can answer. What the baseline adds (SL4) is everything needed to make a copy -of it somebody else's — built the way +can answer. What the baseline adds is everything needed to make a copy of it +somebody else's — built the way [supabase-starter](https://github.com/sourceplane/supabase-starter) builds a -product, in one landing. See -[`specs/epics/supabase-slack-clone`](specs/epics/supabase-slack-clone/README.md) +product, in one landing. See [`specs/epics/supabase-slack-clone`](specs/epics/supabase-slack-clone/README.md) for the design, the milestones and the as-built status, including every departure. +## Instantiating a product + +```bash +git clone --depth 1 --branch <baseline-tag> https://github.com/sourceplane/supabase-slack-clone +cd supabase-slack-clone +orun new --blueprint repo-blueprint.yaml --out ~/products/acme-chat --run-hooks --resume \ + --set reponame=acme-chat --set productname="Acme Chat" \ + --set githuborg=acme-inc --set subdomain=<workers-dev-subdomain> +``` + +Or, once the platform's registry lists it, from the Orun console (Baselines → +`supabase-slack-clone` → Build). Two phases: **`01-product`** creates the +repository, mints the four brokered credentials (Cloudflare and Supabase) and +lands the whole product as one pull request, whose convergence on `main` +provisions, migrates and deploys it per environment in a fixed order — + +``` +supabase ──▶ db-migrate ──▶ web +``` + +— every edge `mode: enforced` on a push to main and advisory on a pull +request; then **`02-docs`** records the live deployment from probed facts. +**[BOOTSTRAP.md](BOOTSTRAP.md)** is the operator guide; +[docs/phases/](docs/phases/README.md) has a page per phase. The Supabase +organization needs room for **two** projects (stage and prod) — the free +plan's limit. + +The new repository receives the **product only** — the app, the Terraform +root, the migrations, the tests, its CI, its tooling, a README and an +AGENTS.md of its own and its operating contract — renamed throughout to the +product's name, repository, Worker and Supabase projects. None of this +repository's machinery ships. + +| What makes it a baseline | Where | +|---|---| +| The console card (inputs, secrets, programme) | `blueprint.yaml` | +| The build document (modules, phases, hooks) | `repo-blueprint.yaml` | +| This tree's identity, the product's README and AGENTS.md, and the bootstrap's task contracts | `.baseline/` | +| The rename engine (product-name seam: `apps/web/lib/site.ts`) | `tooling/rebrand/rebrand.mjs` | +| The bootstrap's helpers (deferrals, redeploy marker, work-tree strip) | `tooling/bootstrap/` | +| The deployment-record renderer | `hooks/render-deployment-docs.sh` | +| The product's context pack | `ai/context/` | +| The baseline's tests: contract, leak, offline bootstrap and plans, end to end | `testing/`, `.github/workflows/baseline.yml` | +| Cutting a `baseline-vN` tag | `.github/workflows/tag.yml` | + ## What is here (the product) | Surface | Where | @@ -54,35 +98,10 @@ pnpm test pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next ``` -The build needs no Supabase project: without one it inlines the committed -`wrangler.jsonc`'s placeholder values, and nothing calls them. - -## Running it locally - -Against any Supabase project with the schema applied (its URL and -publishable key are in the dashboard → Project Settings → API): - -1. Copy `apps/web/.env.example` to `apps/web/.env.local` and fill in the two - values; `next dev` and `pnpm build` read it. Then - `pnpm --filter @app/web dev` (http://localhost:3000). -2. Or the built Worker: the same two values in `apps/web/.dev.vars` (copy - `.dev.vars.example`), `pnpm build`, then `pnpm --filter @app/web preview` - (http://localhost:8787). - -The schema comes from the runner the pipeline uses: -`pnpm --filter @saas/db build`, then -`SUPABASE_ACCESS_TOKEN=… SUPABASE_PROJECT_REF=… node packages/db/dist/runner/cli.js apply --env stage` -— every migration the project has not had, then the access-token hook. - -## How it deploys - -Merges to `main` converge through Orun (`.github/workflows/ci.yml`), per -environment in a fixed order — the Supabase project, then the migrations, -then the Worker — every edge enforced on a push to main and advisory on a -pull request. `stage` deploys first and `prod` once stage has converged; -`dev` only verifies. Each deploy is smoke-tested over HTTP, `/api/health` -included. The pipeline plans nothing while `intent.yaml` names the -placeholder workspace `ws_CHANGE_ME`, as this repository does. +The build needs no Supabase project. Running it against one — `.env.local` +for `next dev` and the build, `.dev.vars` for `wrangler dev` — is in the +product's README (`.baseline/product/README.md`), which is what a product +built from here carries. ## How it maps to Vercel and Supabase @@ -105,6 +124,7 @@ service-role key is read anywhere. | Workflow | What it runs | Ships to a product | |---|---|---| | `ci.yml` | the Orun pipeline, and the only workflow a product carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the app built and dry-deployed per environment, the Supabase root planned, the migrations planned offline; no typecheck, lint or tests), except the bootstrap's own landings (`orun/BASE-*`), where `plan` alone runs and nothing waits for it — the landing was checked in the build box; a merge applies, migrates and deploys stage → prod. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does. A manual run (Orunbase's Deploy button, or Run workflow on `main`) plans the environment and components it names under the push-to-main trigger, so they deploy as a merge deploys them | yes | +| `baseline.yml` | the baseline's own tiers: contract tests; the blueprint read by the pinned orun, the leak gate, the offline bootstrap and the product's own plans; the 01-product landing installed, its fixture rendered, type-checked, linted, tested and built, then built in the job tree orun stages, dry-deployed, and served against a local Supabase stand-in — the smoke refused before the migrations, db-migrate's own steps applying them and the hook, then the smoke passing and the chat driven as a member, a moderator and an admin | no | | `tag.yml` | cuts a `baseline-vN` tag (manual) | no | ## Licence and credit diff --git a/ai/context/current.md b/ai/context/current.md new file mode 100644 index 0000000..106159f --- /dev/null +++ b/ai/context/current.md @@ -0,0 +1,42 @@ +# supabase-slack-clone — where this repository stands + +The entry page for anyone (or any agent) picking this repository up. It is +this repository's own state and does not ship to a product built from it; the +two pages that do are [operations.md](operations.md) and +[deployment.md](deployment.md). + +## What it is + +Supabase's Next.js Slack clone on Cloudflare Workers + Static Assets +(`@opennextjs/cloudflare`), its Supabase project per environment provisioned +by Terraform and its schema applied by db-migrate through Orun, packaged as +an Orun baseline: `orun new --blueprint repo-blueprint.yaml` builds a new +product in its own repository and takes it to live on stage and prod in one +landing (`01-product`: supabase → db-migrate → web per environment), then +records what went live (`02-docs`). + +## Release + +| | | +|---|---| +| Latest tag | `baseline-v1` (SL4) | +| Proven live | No. Nothing has been applied against a real Supabase organization: no Terraform apply, no migration, no live deploy, no live bootstrap (risk SL-A). Everything short of the platform is proven offline in Baseline CI, against a local Supabase stand-in | + +## Where to read + +| Question | Page | +|---|---| +| What shipped, and every departure from upstream | `specs/epics/supabase-slack-clone/IMPLEMENTATION-STATUS.md` | +| Why it is built this way | [decisions.md](decisions.md), then `specs/epics/supabase-slack-clone/design.md` | +| What could still go wrong | [open-risks.md](open-risks.md), then `specs/epics/supabase-slack-clone/risks-and-open-questions.md` | +| How to instantiate it | `BOOTSTRAP.md`, `docs/phases/` | +| What each component is | `apps/web/docs/`, `infra/terraform/supabase/docs/`, `infra/db-migrate/docs/`, `packages/db/docs/`, `tests/web/docs/`, `tests/db/docs/` (generated; `python3 tooling/catalog/gen-component-docs.py`) | + +## Next + +1. Bootstrap one product from `baseline-v1` against a workspace with a + Supabase connection, and record its timings — the apply, the brokered + token's reach to the API-keys and Auth-config endpoints, the migrations + and the hook, a sign-up on the first deploy (closes SL-A). +2. Decide whether the baseline should replace upstream's plus-address roles + (SL-C) instead of leaving it to each product's owner. diff --git a/ai/context/decisions.md b/ai/context/decisions.md new file mode 100644 index 0000000..1e95bd5 --- /dev/null +++ b/ai/context/decisions.md @@ -0,0 +1,21 @@ +# supabase-slack-clone — decisions + +The choices that shape this repository, one line each, with where the full +reasoning lives. + +| # | Decision | Why | Source | +|---|---|---|---| +| 1 | OpenNext on Workers + Static Assets (`cloudflare-workers-assets-turbo`), no Hyperdrive | The example's every Supabase call runs in the browser over HTTPS; the Worker serves pages and one health check, and never opens a Postgres connection | `specs/epics/supabase-slack-clone/design.md` §2 | +| 2 | The publishable key is a wrangler var; no service-role key is published or read | It ships to every browser by design and row-level security is the boundary; nothing in the product runs with the service role | risk SL-E | +| 3 | `wrangler.jsonc` committed as the fixture render; stage and prod re-render it from `WIRING_SUPABASE_<ENV>` (`optionalSecretEnv`), and `next build` reads the project from it | The composition checks the file exists before the build; the bundle and the Worker must name one project; stage must not wait on prod's document | risk SL-F, supabase-starter | +| 4 | Upstream's two migrations and its seed are db-migrate migrations, byte for byte | One runner and one checksummed ledger per project, a pull request that verifies offline, and the `#public` channel the app sends everyone to | design §2 | +| 5 | The access-token hook is switched on by the migration runner after the migrations, every apply, and read back | Terraform applies before the migrations, so it would point Auth at a function that does not exist yet; SQL cannot set Auth config | design §4, risk SL-B | +| 6 | supabase → db-migrate → web, each edge enforced on a push to `main`, advisory on a pull request | One convergence provisions, migrates, then deploys per environment | `repo-blueprint.yaml`, `testing/placement.test.sh` | +| 7 | `/api/health` asks Auth's settings and the Data API's `channels` with the publishable key, read-only | A page that renders proves only that the Worker deployed; this proves the project is bound and migrated, and only the Worker can answer it | design §5 | +| 8 | `next` pinned at 16.3.8; the two calls Next 16 and supabase-js 2 refuse fixed; the App component renamed `ChatApp` | `latest` is not reproducible; upstream's `<Link><a>` and `onAuthStateChange` shape no longer work; upstream's component name spells this repository's slug | IMPLEMENTATION-STATUS | +| 9 | Email confirmation off until the project has SMTP of its own | A fresh project's built-in email reaches only its organization's members | risk SL-H | +| 10 | Upstream's plus-address roles kept, and documented as a demo to replace | Changing the example's role model is not the port's to decide; the product's README says how | risk SL-C | +| 11 | `packages/db` is named `@saas/db` | The db-migrate composition builds the package by that name | `infra/db-migrate`, stack-tectonic 0.19.0 | +| 12 | supabase-starter's current shape (`SS10`): two phases, one landing; one `secrets` reconcile per provider; the task set-up in the background; landings checked in the box; no authored await line; `AGENTS.md` in every product; `ci.yml` as turso-starter's with the manual-deploy contract | The reference starter's current `main` is the standard | `repo-blueprint.yaml`, `testing/phases.test.sh` | +| 13 | stack-tectonic 0.19.0, not 0.20.0 | 0.20.0's lane-scoped install is refused by Turbopack | `intent.yaml` | +| 14 | Component docs are generated from the manifests and checked in CI | A hand-written copy of the dependency graph, bindings and published outputs drifts silently | `tooling/catalog/gen-component-docs.py` | diff --git a/ai/context/deployment.md b/ai/context/deployment.md new file mode 100644 index 0000000..f70e410 --- /dev/null +++ b/ai/context/deployment.md @@ -0,0 +1,8 @@ +# supabase-slack-clone — live deployment manifest + +> Not rendered yet. The bootstrap's `02-docs` phase probes every live URL and +> regenerates this file from what answered — the workspace, the URLs and +> their status, how sign-up behaves on each environment's Supabase project +> and whether its schema is in place, and the secrets the product uses, by +> name. Until then, nothing here claims the product is live. The operating +> contract is [operations.md](operations.md). diff --git a/ai/context/open-risks.md b/ai/context/open-risks.md new file mode 100644 index 0000000..64708ec --- /dev/null +++ b/ai/context/open-risks.md @@ -0,0 +1,13 @@ +# supabase-slack-clone — open risks + +What is not yet proven or not yet decided. The full write-up of every risk, +including the accepted and resolved ones, is +`specs/epics/supabase-slack-clone/risks-and-open-questions.md`; this page +lists only what is still live, so it should be short. + +| ID | Risk | State | What closes it | +|---|---|---|---| +| SL-A | Unproven against a real organization: no Terraform apply, migration, live deploy or live bootstrap yet — so whether the brokered Supabase token reaches the API-keys and Auth-config endpoints, whether upstream's `010_init` may re-create the `supabase_realtime` publication through the Management API, and the wall-clock are all unknown | OPEN | One bootstrap from a tag against a workspace with a Supabase connection | +| SL-C | Upstream's plus-address roles let anyone sign up as an admin | ACCEPTED (documented for the product's owner) | A product's own migration that replaces the trigger | +| SL-D | Upstream's `public.create_user` seed helper is callable through the Data API | ACCEPTED (documented) | The same migration revokes it | +| SL-G | The pages router on Next 16 and OpenNext 1.20 | WATCH | Holds while both serve it | diff --git a/ai/context/operations.md b/ai/context/operations.md new file mode 100644 index 0000000..4279f95 --- /dev/null +++ b/ai/context/operations.md @@ -0,0 +1,210 @@ +# supabase-slack-clone — operating contract (for humans and agents) + +This is the standing guide to how this product is deployed and operated. +Instance facts (live URLs, workspace, how sign-up behaves on each +environment, the secrets it uses) live in [deployment.md](deployment.md), +rendered from probed reality by the bootstrap's `02-docs` phase; this file is +the contract that stays true between deployments. It is written to give an +agent with repository read access enough context to reason about and operate +the product without any other source. + +## What this system is + +Supabase's Slack clone — a team chat with channels, messages that arrive +live, email and password sign-up, and moderator and admin roles — on +Cloudflare Workers, its Auth, its data and its Realtime a Supabase project +per environment, expressed as an Orun component-native desired-state repo. +Six components: + +- **`infra/terraform/supabase`** (`supabase`) — one Supabase project per + environment, its Auth's Site URL and redirect allow-list pointed at the + app's Worker, and sign-up confirming at once unless `authEmailConfirmation` + is on (below). Its apply publishes `WIRING_SUPABASE` (the project URL and + publishable key) and `SUPABASE_PROJECT_REF`, `SUPABASE_DB_PASSWORD`, + `SUPABASE_DB_URL` onto the environment's secret rung. +- **`infra/db-migrate`** (`db-migrate`) — applies `packages/db`'s migrations + to that project over the Management API's query endpoint, records each in + the project's own ledger (`_migrations.applied`), then switches on the + access-token hook the chat's roles need in the project's Auth config + (`packages/db/src/auth-config.ts`). A pull request plans it offline: every + file's checksum against the manifest, nothing touched. +- **`packages/db`** (`db`) — the migrations, their manifest and the runner. +- **`apps/web`** (`web`) — the app: Next.js (pages router) built by + `@opennextjs/cloudflare` into one Worker plus Static Assets. The chat runs + in the browser, which talks to Supabase directly with supabase-js — Auth, + the Data API and Realtime — never a Postgres connection. The Worker serves + the pages and `/api/health`. +- **`tests/web`**, **`tests/db`** — the vitest suites (`pnpm test`): the app, + and the schema on Postgres in process. Their `dev` lanes install them and + check their structure; they do not run the tests, so run them (and + `pnpm typecheck`, `pnpm lint`) before you push. + +Environments: **`stage`** and **`prod`** are deployed; **`dev` is +verify-only by design** — lanes build and verify, nothing deploys. + +## Identity and tenancy + +Every remote operation runs against ONE Orun workspace, declared in +`intent.yaml` under `execution.state.workspace` — committed, enforced, and +what CI uses. Do not remove it; headless credentials depend on it. If it +reads `ws_SET_ME`, the bootstrap had no workspace to write: set the real one +before anything else. + +## How deployment works + +1. Merge (or push) to `main`. +2. CI (`.github/workflows/ci.yml`) runs `orun plan --changed` — only + components whose files changed are planned — then runs each planned lane + with `orun run --remote-state`, authenticated by GitHub OIDC (the + exchange resolves this repository's linked workspace server-side). +3. Per environment, in this order — every edge `mode: enforced` on a push to + main, advisory on a pull request (which deploys nothing): + **`supabase` → `db-migrate` → `web`.** A job resolves its secrets when it + starts, so db-migrate reads the database credentials the apply before it + published, and the app's deploy reads `WIRING_SUPABASE`. It re-renders + `apps/web/wrangler.jsonc` from that document, builds — `next build` + inlines the same URL and key into the browser bundle (`next.config.ts`) + — deploys `supabase-slack-clone-web-<env>`, and smoke-tests it: the + sign-in page, and `/api/health`, which answers 200 only when the project's + Auth answers the key the build inlined and its Data API knows the + `channels` table the migrations create. +4. `prod` deploys after `stage` has converged on the same commit + (`environments.prod.promotion` in intent.yaml). +5. **The convergence run is the deployment.** A green run means every + planned lane applied. Failed lanes are retried with + `gh run rerun --failed`, which resumes the same execution. + +Caveats that matter: + +- A push that touches no component files plans zero lanes — that run is + green and deployed nothing. Never treat "latest run green" as "product + converged"; probe the URLs instead. +- `apps/web/wrangler.jsonc` is committed as the render of + `wrangler.template.jsonc` from `wiring.fixture.json` (a placeholder + project): edit the template and run `pnpm run wire:fixture`. The deploy + lanes render the real one in their own job tree; never commit a real + project's URL or key. +- The product's origin is ONE setting. Unset, it is the environment's + workers.dev URL (`<repo>-web-<env>.<subdomain>.workers.dev`); with a custom + domain, `SITE_URL` under the environment's `env:` in `intent.yaml`. The + supabase apply makes it Auth's Site URL and redirect allow-list, where + Supabase sends its links (confirmation, when it is on). The apply owns + those Auth settings: an edit in the dashboard is undone by the next apply. + +## Auth, roles and email + +Every new user is a member. The chat's other roles are rows in +`public.user_roles` (`moderator`, `admin`); the permissions each grants are +rows in `public.role_permissions` (`messages.delete` for both, +`channels.delete` for admins). The access-token hook +`public.custom_access_token_hook` copies the user's role into every access +token as the `user_role` claim, and `public.authorize(<permission>)` reads +that claim in the delete policies. The app reads the same claim +(`pages/_app.js`) to show the delete buttons; row-level security is what +enforces them. + +The hook must be ON in the project's Auth config, and only db-migrate turns +it on — after the migrations, every apply, so the function exists before +Auth points at it, and a dashboard edit is undone by the next deploy. The +supabase root never writes those two keys. + +As upstream ships it, `handle_new_user` (the trigger on `auth.users`) gives +an address containing `+supamod@` the moderator role and one containing +`+supaadmin@` the admin role. Anyone can choose such an address: before real +users arrive, replace that trigger in a new migration and grant roles by +inserting into `public.user_roles` instead. A new role reaches a session at +its next sign-in or token refresh. + +A Supabase project without an SMTP server of its own delivers email only to +the members of its organization, a few messages an hour. So the supabase +root turns email confirmation OFF (`authEmailConfirmation: "false"` in its +component.yaml): sign-up signs a new user straight in, and works for anyone +on the first deploy. To require confirmation, give each project SMTP of its +own (Supabase dashboard → Authentication → Emails → SMTP Settings), then set +`authEmailConfirmation: "true"` and merge; `/api/health` and the deployment +record then say `emailConfirmation: required`. + +The terraform manages only `site_url`, `uri_allow_list` and +`mailer_autoconfirm`; db-migrate manages the access-token hook; every other +Auth setting is the project's own. + +## Data, row-level security and Realtime + +Three tables in `public` carry the chat — `users` (one row per Auth user, +written by `handle_new_user`), `channels` and `messages` — plus `user_roles` +and `role_permissions`. Row-level security is on for every one of them: +signed-in users read every channel, message and user; each writes only as +themselves; deletes follow the roles above; the anonymous role reads +nothing. Keep that rule for every table you add to `public`: the +publishable key is public by design, so a table without RLS is readable by +anyone who loads the site. Check with: + +```sql +select relname from pg_class c join pg_namespace n on n.oid = c.relnamespace + where n.nspname = 'public' and c.relkind in ('r','p') and not c.relrowsecurity; +``` + +The browser subscribes to `channels`, `messages` and `users` through +Realtime, which streams what the `supabase_realtime` publication carries; +the migrations put those three tables in it with `replica identity full`, so +a deleted row reaches the browser whole. A table added to the chat joins the +publication in its own migration. + +`030_seed` creates `#public` and `#random` and their first messages under a +bot user who cannot sign in. The app sends a signed-in user to +`/channels/1`, so `#public` is not to be deleted. + +## Secrets model + +- **Brokered provider secrets**, minted per run from the workspace's + connections — no long-lived values at rest, nothing to rotate by hand: + `CLOUDFLARE_API_TOKEN` (Workers deploy), `CLOUDFLARE_ACCOUNT_ID`, + `SUPABASE_ACCESS_TOKEN` (project create, API keys, Auth settings, the + migrations and the hook) and `SUPABASE_ORG_ID`. +- **Published by the apply** onto the stage and prod rungs: + `WIRING_SUPABASE` (URL and publishable key — what the app reads), + `SUPABASE_PROJECT_REF`, `SUPABASE_DB_PASSWORD`, `SUPABASE_DB_URL` (the + database — what db-migrate reads). The service-role key is never + published, and nothing reads one. +- **No Worker secrets.** The publishable key is a wrangler var: it ships to + every browser by design, and row-level security is the boundary. +- Inspect by NAME only: `orun secrets list --org <ws> --project` and + `--env stage|prod`. No tooling in this repository prints a secret value, + and no document in `ai/context/` may contain one. + +## Verifying the system + +```bash +# the app and its health check on each environment (also recorded, probed, in deployment.md) +curl -s -o /dev/null -w '%{http_code}\n' https://supabase-slack-clone-web-stage.your-workers-subdomain.workers.dev/ +curl -s https://supabase-slack-clone-web-prod.your-workers-subdomain.workers.dev/api/health + +# workspace readiness (integrations + repository link) +orun integrations list --org <ws> --json && orun cloud check --org <ws> +``` + +## Common operations + +| task | how | +|---|---| +| deploy a change | merge to `main`; watch the run; failed lanes → `gh run rerun --failed` | +| deploy by hand | Orunbase's Deploy button, or `gh workflow run ci.yml --ref main -f environment=<env> [-f component=<a,b>]` — the named components (blank: every one) run in that environment as a merge runs them; started off `main` it is refused | +| change the schema | a new `packages/db/src/migrations/<NNN>_<name>/up.sql`, its manifest entry, `pnpm --filter @saas/db run manifest:fix`, and `pnpm test` (tests/db runs every migration); merge — db-migrate applies it before the app deploys. Never edit an applied one | +| grant a role | `insert into public.user_roles (user_id, role) values ('<uuid>', 'moderator')` in the SQL editor, or a migration; it reaches the user's session at the next sign-in | +| require email confirmation | SMTP first, then `authEmailConfirmation: "true"` (above) | +| redeploy without a change | edit the last line of the component's `component.yaml` (`# orun: redeploy <reason> <stamp>`) and merge — it is a deploy trigger, nothing reads it | +| serve a custom domain | attach it to the Worker in Cloudflare (README, "Custom domain"), set `SITE_URL` under `environments.prod.env` in `intent.yaml`, replace the placeholder `supabase-slack-clone.example.com` in `intent.yaml`'s `BASE_DOMAIN` with it (a record; nothing builds a URL from it), and touch the redeploy line of `infra/terraform/supabase/component.yaml` in the same PR (an `intent.yaml` change alone plans nothing) | +| headless credentials | `ORUN_TOKEN` (workspace-scoped) + `GITHUB_TOKEN` | + +The deployment record is the bootstrap's `02-docs` phase. Re-running it (the +Orun console's Retry on that phase, or `orun new … --phase 02-docs`) +re-probes the URLs and re-renders [deployment.md](deployment.md); it is +idempotent. + +## Evolution + +Structural changes (a second Worker, a queue, a storage bucket) follow the +same contract that deployed the product: add a component under `apps/`, +`infra/` or `packages/` with a `component.yaml` — declaring `dependsOn` on +any infrastructure whose published secrets it reads, enforced on main — land +it as a pull request, and the convergence run applies it. diff --git a/blueprint.yaml b/blueprint.yaml new file mode 100644 index 0000000..4f36122 --- /dev/null +++ b/blueprint.yaml @@ -0,0 +1,167 @@ +# The supabase-slack-clone card: what the console's Blueprints page renders and the +# platform's bootstrap door consumes. +# +# THIS FILE IS NOT THE BUILD. `spec.bootstrap.blueprint` names the build +# document — `repo-blueprint.yaml`, whose phases a runner places. This card is +# what an operator reads and fills in before pressing Build, and +# `testing/manifest.test.sh` compares every list below to the document that +# actually does the thing, not to a copy of itself. +# +# The division of labour with the registry is strict: 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. Neither +# restates the other, which is why there is no `tag` here: this file is +# fetched AT the tag the registry pins. +apiVersion: orun.io/v1 +kind: Blueprint +metadata: + name: supabase-slack-clone + displayName: Supabase Slack Clone — a Next.js team chat on Supabase and Cloudflare Workers + description: > + Supabase's Slack clone example as a product of its own: a team chat with + channels, messages that arrive live over Supabase Realtime, email and + password sign-up, and moderator and admin roles carried in each user's + session by an Auth hook and enforced by row-level security, built by + OpenNext into one Cloudflare Worker. Terraform creates a Supabase project + per environment — two in all, stage and prod, which is the free plan's + limit per organization — and points its Auth at the Worker; db-migrate + applies the chat schema and switches the hook on; CI deploys the app to + both on merge, after its project and its schema. Live in about fourteen + minutes. + tags: [supabase, realtime, chat, cloudflare, nextjs] +spec: + source: + repo: sourceplane/supabase-slack-clone + # No `tag`. The registry pins it; this file is fetched at it. + + # ── What the operator reads first ──────────────────────────────────────── + overview: + lede: > + A team chat — channels, live messages, members, moderators and admins — + on Cloudflare at the edge, its Supabase project held by Terraform and + its schema by migrations. + architecture: + - layer: Edge + items: [web] + - layer: Data + items: [Supabase Auth, Supabase Postgres, Supabase Realtime] + - layer: Delivery + items: [Terraform, db-migrate, GitHub Actions, OpenNext] + outcome: + - Live on stage and prod, sign-up and the two starter channels working + - A Supabase project per environment, migrated, its Auth pointed at the app + - Roles in every session, enforced by row-level security + + requires: + # GitHub arrives as the App installation plus the repo link; Cloudflare + # and Supabase are the two provider connections the build mints from. + # The Supabase organization needs room for TWO projects (stage and prod): + # the free plan allows two active projects per organization. + integrations: [github, cloudflare, supabase] + apiKeyRole: admin # secret writes need the admin floor + + # Every input is collected by the console: keys are lowercase (the + # platform's reader refuses anything else), every one carries the `pattern` + # its value is checked against before Continue, and a value the console + # already holds says so with `from`. repo-blueprint.yaml declares the same + # names; `repoPrivate`, `orunWorkspace` and `epicSlug` are build inputs with + # defaults (or filled from the build's workspace) and are not asked. + # + # NOR IS THE DOMAIN. The app goes live on workers.dev, and a domain is an + # owner's step after the bootstrap: `productdomain` defaults to empty, the + # rebrand writes the reserved placeholder `<reponame>.example.com` where + # the domain goes, and the product's README ("Custom domain") says how to + # set it. Nothing that needs a domain is removed — it waits for one. + inputs: + - key: reponame + label: Repo name + pattern: "^[a-z][a-z0-9-]{1,38}$" + # The operator picked the repository; its name IS this value. + from: repo.name + - key: productname + label: Product name + pattern: "^[A-Za-z0-9][A-Za-z0-9 .,'&-]{1,48}$" + help: The name people see — in every page title and on the sign-in page. + example: Acme Chat + - key: githuborg + label: GitHub organisation + pattern: "^[A-Za-z0-9][A-Za-z0-9-]*$" + help: The GitHub org or user the product's repository is created under. + # DERIVED FROM THE CHOSEN REPOSITORY: its owner IS this value. Declared + # because repo-blueprint.yaml requires it — a build may declare more + # inputs than this card, but not require one nobody supplies. + from: repo.owner + - key: subdomain + label: workers.dev subdomain + pattern: "^[a-z0-9][a-z0-9-]{0,62}$" + help: The workers.dev subdomain of the Cloudflare account the app deploys into. Supabase Auth sends its links there. + 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 the Site URL and redirect allow-list the Supabase + # project's Auth is given, the 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. The console + # renders no field for it, and 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 `orun.integrations/reconcile@v1` + # hooks mint these, brokered, during 01-product — one hook per provider. ─ + # Transcribed from those hooks' own `provider:` and `secrets:` ({key, + # template}) values, in their order, so testing/manifest.test.sh compares + # this list to the document that mints them. The console renders them + # read-only: no credential is ever typed, shown or stored. Keys that + # already exist are kept. Four keys, four scopes: the app needs no + # Hyperdrive, D1, KV or R2 — it reaches Supabase over HTTPS with the + # project's publishable key, which the Terraform apply publishes itself, + # and db-migrate reads the database credentials the same apply publishes. + secrets: + - key: CLOUDFLARE_API_TOKEN + provider: cloudflare + template: workers-deploy + why: Deploys the app's Worker and its static assets + - 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: Creates the projects, sets their Auth URLs, applies the migrations and switches on the Auth hook + - key: SUPABASE_ORG_ID + provider: supabase + template: org-id + why: Connection fact, not a secret + fact: true + + # ── PREVIEW ONLY. repo-blueprint.yaml's run-level `hooks.preInstantiate` + # opens these — the epic, every milestone in this order, every task — before + # the first phase places. Idempotent by identity, so a re-run finds what it + # made before. + programme: + epicSlug: team-chat-baselining # = repo-blueprint.yaml's `epicSlug` default + epicName: "Team chat baselining — {productname}" + milestones: + - name: 01-product + - name: 02-docs + + bootstrap: + # THE BUILD DOCUMENT. There is no umbrella workflow and no agent brief: + # every phase is declared in it and orun runs it. + blueprint: repo-blueprint.yaml + # Summed from the phases' expectedMinutes (13 + 1). An estimate until a + # bootstrap measures it: a Supabase project takes five to seven minutes to + # come up, the migrations wait on it, and the app's build waits on both. + expectedMinutes: 14 + tokenChannel: ORUN_TOKEN_FILE # how a runner hands over its refreshed token + verify: + urls: + - "https://{reponame}-web-{env}.{subdomain}.workers.dev" + - "https://{reponame}-web-{env}.{subdomain}.workers.dev/api/health" + envs: [stage, prod] diff --git a/docs/phases/01-product.md b/docs/phases/01-product.md new file mode 100644 index 0000000..e1e5a2e --- /dev/null +++ b/docs/phases/01-product.md @@ -0,0 +1,143 @@ +# 01-product — the product, in one landing + +The whole product lands as ONE pull request, and ONE convergence on main +provisions, migrates and deploys it on stage and prod: the Supabase project, +its Auth pointed at the app; the chat schema and the access-token hook; and +then the app — in that order, per environment. + +**Budget: 13 minutes** (`expectedMinutes`, an estimate until a bootstrap is +timed): the landing checked in the box and merged in about a minute, then +the Supabase project's five to seven minutes, a minute of migrations, and +the app's build, deploy and smoke — stage and prod side by side. + +**Places** every module `repo-blueprint.yaml` declares: the root manifests, +the product's README and `AGENTS.md` (where a coding agent starts), CI, +tooling and identity; `infra/terraform/supabase`; `packages/db` and +`infra/db-migrate`; `apps/web`; and `tests/web` and `tests/db`. +`testing/phases.test.sh` holds the set. + +**Requires** three live connections, probed and waited for (up to ten +minutes, so a consent can be clicked while it waits): the GitHub App on the +account that OWNS the repository — the platform sees a PR only through that +installation — and Cloudflare and Supabase, which every credential below is +minted from. The Supabase organization needs room for **two** projects, +`<reponame>-stage` and `<reponame>-prod` — the free plan's limit. + +## How one convergence keeps the order + +| what has to come first | how the plan holds it | +|---|---| +| the Supabase project before the migrations | `db-migrate` reads the project's ref and database credentials (`SUPABASE_PROJECT_REF`, `SUPABASE_DB_PASSWORD`, `SUPABASE_DB_URL`, which the `supabase` apply lease-publishes) as `secretEnv` — fail-closed — and declares `dependsOn: supabase`, `mode: enforced` on main. A job resolves its secrets when it STARTS, so they are there | +| the migrations before the app | `web` declares `dependsOn: db-migrate` (and `supabase`), `mode: enforced` on main: the browser reads the tables the migrations create, and signs in through the hook they make | +| the hook's function before Auth points at it | the runner switches the access-token hook on in the project's Auth config only after the migrations that create `public.custom_access_token_hook` (`packages/db/src/auth-config.ts`) | +| the project's Auth before anyone signs up | the supabase apply sets the project's Site URL and redirect allow-list to the Worker and turns email confirmation off, after the project reports healthy | +| stage before prod | deferred during the bootstrap (below), so both environments run their chains side by side | + +Every edge is **advisory on a pull request**, which applies and deploys +nothing. `testing/placement.test.sh` plans the placed product's own push to +main and reads the order off it: `supabase → db-migrate → web`. + +## What runs + +The run's task set-up — the epic, both milestones, both tasks — runs in the +background from the start (`background: true`), so every hook up to `task` +runs beside it; `task` is the first that waits for it. + +| hook | what it does | +|---|---| +| `retouch` | one trailing `# orun: redeploy 01-product <stamp>` line in each component `.baseline/tasks/01-product.TaskContract.yaml` names (supabase, db-migrate, web), so a RE-RUN has a diff to land | +| `git-init`, `stage` | the tree becomes a git repository with a populated index (the rebrand enumerates `git ls-files`) | +| `rebrand` | renames the baseline's identity to the product's: the slug (intent, worker, secret project, the `repo` the Supabase project is named after), the name seam, the domain, the workers.dev subdomain (the Worker's URL and the project's Auth Site URL). The upstream template's own links are left alone | +| `orun-workspace` | writes the product's workspace into `intent.yaml` | +| `work-tree` | strips this repository's `work:` block from the product's intent | +| `promotion`, `dev-lanes` | defer prod's wait on stage and dev's push lanes until `02-docs` | +| `restage`, `rebrand-verify` | the sweep: no baseline identity left | +| `repo` | `orun.repo/ensure@v1`: creates (or finds) `<githuborg>/<reponame>` | +| `link` | the repository becomes the workspace's (`orun cloud link`, best effort; `orun cloud check` is the gate). Every convergence lane authenticates over GitHub OIDC through that link | +| `secrets-cloudflare` | `orun.integrations/reconcile@v1`, Cloudflare's two keys in one hook, each under its own scope, created side by side: `CLOUDFLARE_API_TOKEN` (workers-deploy, the app's deploy) and `CLOUDFLARE_ACCOUNT_ID` (account-id). Keys that exist are kept | +| `secrets-supabase` | the same for Supabase's two: `SUPABASE_ACCESS_TOKEN` (management-access: the project, its API keys, its Auth settings, the migrations and the hook) and `SUPABASE_ORG_ID` (org-id) | +| `task` | finds the phase's task and yields its key — waiting, if it must, for the background set-up | +| `land` | one PR bound to the task, its commit checked in the box first (`checks: local`: `orun validate`, then `orun plan` as the PR and as the merge would plan it, under a second); merged without waiting for the PR's CI (`plan` alone on a bootstrap branch); labelled `Product` in the build panel | +| `converge` (await) | `orun.run/watch@v1` on the merge commit's run, read every 5 s; resumes it up to three times | +| `verify` (await) | `orun.http/probe@v1`: `/` and `/api/health` on both workers.dev URLs | + +## What the convergence does, per environment + +1. **supabase** — `terraform apply`: one project, `<reponame>-<env>`, in the + org `SUPABASE_ORG_ID` names, with a generated database password; then, + once the project reports `ACTIVE_HEALTHY`, its API keys are read and its + Auth is set — Site URL and redirect allow-list + `https://<reponame>-web-<env>.<subdomain>.workers.dev` (or the + environment's `SITE_URL`), email confirmation off. Its outputs are lease-published as `WIRING_SUPABASE` + (the URL and the publishable key), `SUPABASE_PROJECT_REF`, + `SUPABASE_DB_PASSWORD` and `SUPABASE_DB_URL`. A new project takes five to + seven minutes to come up. +2. **db-migrate** — installs, builds `@saas/db`, and applies every migration + the project's ledger (`_migrations.applied`) does not hold, through the + Management API's query endpoint, each checked against its manifest + checksum: `000_control`, then upstream's `010_init` (the tables, the + roles, the policies, the Realtime publication), `020_auth_hook` and + `030_seed` (`#public`, `#random`). Then it switches the access-token hook + on in the project's Auth config and reads it back. A re-run applies + nothing and re-asserts the hook. +3. **web** — installs, re-renders `wrangler.jsonc` from this environment's + wiring document, builds with OpenNext (`next build` inlines the same URL + and key into the browser bundle), deploys `<reponame>-web-<env>`, and + smoke-tests it: the sign-in page, and `/api/health`, which answers only + when the project's Auth answers the key the build inlined and its Data + API knows the `channels` table. + +No SMTP server is in it: sign-up works without one, because confirmation is +off. The owner turns it on later (the product's README, "Email"). + +## Verify / done means + +- The convergence for the merge commit is green on stage and prod — in it, + db-migrate resolved the three database credentials and the app's deploy + resolved `WIRING_SUPABASE`, from stage and prod, where every later run + reads them, and each fails without them, so there is no separate check + that they exist. +- `/` and `/api/health` answer on both workers.dev URLs — the health check + only once the schema is in place. + +## Failure modes + +| symptom | meaning → fix | +|---|---| +| parks on the `providers` probe | a connection is missing — GitHub on the repository's owner, Cloudflare, or Supabase. Connect it (console → Integrations); the probe is a wait, not a failure | +| supabase apply: project limit reached | the organization has no room for two more projects (the free plan allows two active ones). Pause or delete one, or upgrade, then re-run the phase | +| supabase apply: `does not support oauth access` | the provider is above 1.5.x, which reads billing endpoints an OAuth token cannot — `~> 1.5.1` is pinned for this reason | +| supabase apply: `Unable to read API keys` or `Unable to update auth settings` (401/403) | the Supabase connection's grant does not reach the project's API keys or its Auth configuration. Reconnect Supabase with a personal access token (console → Integrations → Supabase), or set the Site URL by hand and remove `supabase_settings` — then re-run | +| supabase apply: the project never reports `ACTIVE_HEALTHY` | the project is still coming up after ten minutes, or failed to. Its state is in the Supabase dashboard; re-run the phase once it is healthy (the project is adopted, not recreated) | +| supabase apply: project name already exists | `adopt.tf` looks the project up by name and imports it — if you removed that file, restore it | +| db-migrate: a missing `SUPABASE_DB_URL` (or ref, or password) before the first step | the supabase apply for that environment did not publish — read its log; db-migrate waits on it, so it shows as not run | +| db-migrate: `PATCH config/auth answered HTTP 401/403` | the Supabase grant reaches the query endpoint but not the project's Auth config. Reconnect Supabase with a personal access token and re-run; the applied migrations are not applied again | +| db-migrate: `checksum mismatch` | an applied migration was edited; restore it and make the change a new migration | +| web: `wire: missing wiring documents … WIRING_SUPABASE_<ENV>` | the supabase apply for that environment did not publish — read its log; web waits on it, so it shows as not run | +| `land`: `the landing's own check failed — orun plan for …` | the placed tree does not plan; the next line is orun's own error. Nothing was pushed. Fix it (or the baseline) and re-run the phase | +| `land` waits on CI after all | the product's repository requires a status check on `main` (branch protection or a ruleset), so GitHub refused the early merge; the landing waits for the check as a `checks: ci` landing would, then merges | +| web smoke: `/api/health` 503 | `schema: not migrated` — db-migrate did not run against this project; `auth: key refused` — the key the build inlined is not the project's (a stale wiring document); `auth: unreachable` — the project is paused or the URL is wrong | +| `build-app` fails: `Symlink apps/web/node_modules/next is invalid, it points out of the filesystem root` | the product's intent pins stack-tectonic ≥ 0.20.0 (lane-scoped install), which Next 16's Turbopack refuses. Pin 0.19.0 — `intent.yaml` says why | +| `verify-app-structure` fails: `test -f wrangler.jsonc` | `apps/web/wrangler.jsonc` is not committed. It must be: the check runs before the build, in a fresh checkout (`pnpm run wire:fixture` renders it) | +| the watch says green, the probe says 404 | another workflow ran on the push and the watch took its run. Only `ci.yml` may run on a push to main | +| re-run lands nothing | the hooks did not run (`--run-hooks`), or the contract names no component — `node tooling/bootstrap/retouch.mjs --check --affects .baseline/tasks/01-product.TaskContract.yaml` in the product's tree says which | + +## Re-running + +Idempotent: placement is additive, the rebrand is a no-op on branded files, +`git init` and the repo step are guarded, and the Supabase project is +adopted rather than recreated. A re-run of a phase whose PR already merged +lands the retouch markers alone, which re-plans exactly the components they +name. Once the tree is branded the phase derives as `drifted`, so `--resume` +leaves it alone; re-run it deliberately with `--phase 01-product` (or +`--redo 01-product`). + +## What one convergence will run, before running it + +From a placed product's tree: + +```bash +node <baseline>/tooling/bootstrap/promotion.mjs --defer && node <baseline>/tooling/bootstrap/dev-lanes.mjs --defer +orun plan --intent intent.yaml --trigger github-push-main -v lanes +git checkout intent.yaml +``` diff --git a/docs/phases/02-docs.md b/docs/phases/02-docs.md new file mode 100644 index 0000000..5be3767 --- /dev/null +++ b/docs/phases/02-docs.md @@ -0,0 +1,43 @@ +# 02-docs — the deployment, recorded + +**Budget: 1 minute** (`expectedMinutes`): the render's probes, a landing +checked in the box, a merge. + +**Places** nothing. Its work is hooks: it records what `01-product` built, +from probed facts rather than from what the blueprint intended, and it puts +back the two things `01-product` deferred for the bootstrap's sake. + +**Requires** `01-product` placed. (A hook-only phase derives as `unknown`, so +no phase may require this one.) + +## What runs + +| hook | what it does | +|---|---| +| `promotion` | restores `environments.prod.promotion` — from now on prod deploys only after stage | +| `dev-lanes` | restores dev's activation on pushes to main | +| `render` | `hooks/render-deployment-docs.sh`: probes `/` and `/api/health` on both environments, reads from the health check whether sign-up is open, whether it asks for email confirmation and whether the chat schema is in place, and regenerates `ai/context/deployment.md` — the identity, the probed URLs, how sign-up behaves, the secrets the product uses by name and where each lives — and the README's live-deployment section. It asks the platform nothing: what the workspace holds right now is on the console's Secrets and Integrations pages, which the record points to | +| `task` | finds the phase's task and yields its key | +| `land` | one PR, its commit checked in the box (`checks: local`) and merged, labelled `Docs` in the build panel. It touches no component, so it deploys nothing — and there is nothing after it to wait for: the render's probes are the phase's check, and the panel keeps the one set of addresses `01-product` filed | + +## Re-running it + +Idempotent, and the way to refresh the record after a redeploy, a custom +domain, or turning email confirmation on: every generated section is +re-rendered from scratch. + +```bash +orun new --blueprint repo-blueprint.yaml --out <product-checkout> \ + --run-hooks --phase 02-docs --values <values.yaml> +``` + +## If a bootstrap stops before this phase + +The promotion gate and dev's push activation stay deferred: `intent.yaml` +carries a `# @promotion-deferred:…` and a `# @dev-lanes-deferred:…` marker. +Running this phase restores both, or by hand from the baseline checkout: + +```bash +node tooling/bootstrap/promotion.mjs --restore --file <product>/intent.yaml +node tooling/bootstrap/dev-lanes.mjs --restore --file <product>/intent.yaml +``` diff --git a/docs/phases/README.md b/docs/phases/README.md new file mode 100644 index 0000000..6ef540f --- /dev/null +++ b/docs/phases/README.md @@ -0,0 +1,148 @@ +# The phases — one blueprint, two selections, one landing that deploys + +`repo-blueprint.yaml` declares two phases that take a product from +**nothing** to **live on stage and prod, documented**. Run them one at a time +with `--phase <name>`, or both unattended with `--resume`. There is no +umbrella workflow and no per-phase document: 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 → check them in the box and land them as +> one pull request → watch the convergence that merge triggers +> (auto-resumed) → verify the outcome.** + +The run's task set-up — the epic, a milestone per phase, a task per landing +— runs in the background from the start; the first hook that needs it, the +phase's `task`, waits for it. + +Run from the baseline checkout (the blueprint's source is `path: .`); the +product's repository is wherever `--out` points. + +## Execution order + +| phase | minutes | lands | verified by | +|---|---|---|---| +| [`01-product`](01-product.md) | 13 | **the GitHub repo created**, then the WHOLE product in one PR: intent, CI, tooling, the Supabase Terraform root, the migrations, the app and their tests — one convergence provisions, migrates and deploys it in dependency order | convergence green (db-migrate resolving the database credentials and the app's deploy the `WIRING_SUPABASE` the apply published, each fail-closed); `/` and `/api/health` answer on both | +| [`02-docs`](02-docs.md) | 1 | the live-deployment record; the promotion gate and dev's lanes put back | committed manifest matches probed reality | + +Fourteen minutes in all (`expectedMinutes` 13 + 1, the card's estimate) — +estimates until a bootstrap is timed. + +**One landing builds the product.** The order the chat needs — the Supabase +project, then its schema, then the app that talks to both — is not a +sequence of landings. It is the components' own `dependsOn`, each edge +`mode: enforced` on a push to `main` and advisory on a pull request: + +``` +supabase ──▶ db-migrate ──▶ web (per environment) +``` + +A job resolves its secrets when it starts, so db-migrate reads the project's +ref and database credentials the apply published, and the app's deploy +reads the wiring document: the project's URL and publishable key, rendered +into the Worker's vars and inlined into the browser bundle. +`testing/placement.test.sh` reads that order off the product's own +`orun plan --trigger github-push-main`. Each reads its keys from the place +every later run looks, and fails without them, so a green convergence +already says every published key is there — there is no separate check. + +Every landing is a pull request on a branch named for its task +(`orun/BASE-<n>-<phase>`), checked before it is pushed: `orun validate`, then +`orun plan` as the pull request and as the merge would plan it, in the box, +in under a second (`checks: local`). Then it merges; nothing waits for the +PR's CI. On those branches `ci.yml` runs `plan` only and skips the lanes, +because the merge runs them on main a minute later, for real, and that +convergence is what the phase watches. The product carries no other +workflow. Its pull requests run `ci.yml`'s verify lanes — the app built and +dry-deployed per environment, the Supabase root planned, the migrations' +checksums verified offline — which type-check, +lint and test nothing; the baseline's own CI (Tier 2) installs, renders the +fixture, type-checks, lints, tests and builds this landing before a tag is +cut, and the product's README and `AGENTS.md` tell its developers to run +those steps before they push. + +There is no custom-domain phase: the app answers on workers.dev. Attaching a +domain needs zone permissions the brokered `workers-deploy` token does not +carry, so it is an owner's step after the bootstrap (the product's README, +"Custom domain"). + +## What a phase says + +The console's build panel shows a hook's `narrate:` verbatim as the build's +progress and a phase's `narrate.await` as what it is waiting on; from orun +v2.86 the engine's facts pin the repository, the epic, each pull request and +the live addresses beside them. So every line says one true thing about the +world, briefly, and no line asserts a state (`testing/phases.test.sh`): + +- neither phase authors an `await` line: the engine says what a phase waits + on — "<title>: <reason>" — which is also the line while `01-product`'s + probe waits for a connection, and only the engine knows the reason; +- a line holds for every outcome its hook can have: the repository's says + whether this build created it, a landing names its pull request or says + there was nothing to land, a brokered key's holds whether it was minted now + or kept; +- each landing carries a `label:` (`Product`, `Docs`), and `02-docs` has no + re-probe — its render probes as it writes — so the panel gets the one set + of addresses `01-product`'s probe filed. + +## Inputs + +`01-product` takes the product's identity once and writes it into the repo +(`.rebrand/values.json`); `02-docs` reads it back from the placed tree. But +the blueprint's **required** inputs — `reponame`, `productname`, +`githuborg` — are validated before any phase runs, so they must be supplied +on every invocation, single-phase ones included. A `--values` file is easier +than repeating `--set`. + +- `productdomain` — NOT ASKED, default empty. The app goes live on + workers.dev; empty brands the reserved placeholder `<reponame>.example.com` + into `BASE_DOMAIN`, for an owner to replace when they attach a domain (the + product's README, "Custom domain", which also sets `SITE_URL` so the + Supabase project's Auth follows it). Pass it only for a + product that already has its domain. + +- `subdomain` — the workers.dev subdomain of the Cloudflare account you + deploy into. It is in every URL the phases probe, and it is the origin the + Supabase project's Auth sends its links to. A console or `--from bst_…` + build reads it from the Cloudflare connection; pass it only for a hand-run + build. +- `orunWorkspace` — workspace id (`ws_…`). Unset, it is the workspace the + build runs in (`from: workspace`); with none anywhere, a placeholder that + fails loudly rather than silently claiming another tenant's workspace. +- `epicSlug` (default `team-chat-baselining`) — the epic every phase + clubs its task under. Found by slug, so a fresh run and a resumed run find + the same work. +- `repoPrivate` (default `true`) — the repository's visibility at creation. + +```bash +orun new --blueprint repo-blueprint.yaml \ + --out $HOME/products/acme-chat --run-hooks --phase 01-product \ + --values ~/acme-chat.values.yaml +``` + +Drop `--run-hooks` (or add `--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`, +`testing/e2e.test.sh`). + +## Email is not a phase + +A fresh Supabase project emails only its organization's own members, so the +bootstrap creates each project with email confirmation off — sign-up signs a +user straight in, for anyone, from the first deploy — and asks for no SMTP +server. The owner turns confirmation on once a project has SMTP of its own +(the product's README, "Email"), and re-running `02-docs` records it. + +## When a phase fails + +- **Before it lands** (a probe that timed out, a rebrand residue, a refused + link): nothing was merged. Fix what the message names and re-run the phase. +- **After it lands** (the convergence went red): the files are on main. + `orun.run/watch@v1` has already resumed the run up to three times. Re-run + the phase (`--phase 01-product`, `--redo 01-product` under `--resume`, or + the console's Retry): its `retouch` hook gives the landing a diff and the + components it names re-plan. The Supabase project is adopted rather than + recreated (`adopt.tf`). diff --git a/hooks/render-deployment-docs.sh b/hooks/render-deployment-docs.sh new file mode 100755 index 0000000..1dc24ad --- /dev/null +++ b/hooks/render-deployment-docs.sh @@ -0,0 +1,191 @@ +#!/usr/bin/env bash +# Render the product's LIVE-DEPLOYMENT documentation from verified state. +# Called by phase 02-docs as a `run:` hook (and safe to run by hand, from the +# product's checkout). Idempotent: the generated file and the README section +# are fully re-rendered on every run, so re-running after a redeploy, a custom +# domain or turning email confirmation on refreshes them. +# +# hooks/render-deployment-docs.sh <out> <workspace> <baseline-dir> +# +# What it writes (in <out>): +# ai/context/deployment.md — REGENERATED: URLs with live probe results +# (the app, its health check — the project's +# Auth and the chat schema — and how sign-up +# behaves there), identity, and the +# secrets the deployment uses BY NAME +# ai/context/operations.md — healed from the baseline's copy if absent +# (the static operating contract; never rewritten) +# README.md — the section between <!-- 02-docs:begin/end --> +# is replaced (appended after the title if the +# README predates the markers) +# +# No secret VALUE is ever read or written here — secrets are named, not read. +# +# IT ASKS THE PLATFORM NOTHING. The record used to carry the workspace's slug, +# its secrets listed per rung and its integrations — five CLI calls, one after +# another, from the build box — and all of it is what the console shows live +# and this file could only show as it was the day it was written. The record +# keeps what the repository is the right place for: the identity the code +# names, what answered at the URLs, and where to look for the rest. +set -euo pipefail + +out="${1:?usage: render-deployment-docs.sh <out> <workspace> <baseline-dir>}" +ws="${2:-}" +L="${3:?usage: render-deployment-docs.sh <out> <workspace> <baseline-dir>}" + +cd "$out" +vals=".rebrand/values.json" +[ -f "$vals" ] || { echo "render-docs: $vals missing — is this a bootstrapped product?" >&2; exit 1; } +val() { python3 -c "import json,sys;print(json.load(open('$vals')).get(sys.argv[1],'') or '')" "$1"; } + +repo="$(val reponame)" +brand="$(val brandSlug)"; [ -n "$brand" ] || brand="$repo" +sub="$(val subdomain)"; [ -n "$sub" ] || sub="your-workers-subdomain" +[ -n "$ws" ] || ws="$(sed -n 's/^[[:space:]]*workspace:[[:space:]]*\([^[:space:]#]*\).*/\1/p' intent.yaml | head -1)" +[ -n "$ws" ] || ws="?" + +# 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*) echo "LIVE ($1)" ;; 000) echo "unreachable" ;; *) echo "answering $1" ;; esac; } + +stage_url="https://${brand}-web-stage.${sub}.workers.dev" +prod_url="https://${brand}-web-prod.${sub}.workers.dev" + +# How sign-up behaves on the environment's Supabase project: /api/health +# reports the project's own Auth settings (open or closed, email confirmation +# required or off) and whether the chat schema is there. Read from any answer +# that carries them: a 503 before the migrations still knows Auth. +auth_state() { + local body code + body="$(mktemp)" + code="$(curl -s -o "$body" -w '%{http_code}' --max-time 20 "$1/api/health" 2>/dev/null)" || true + code="${code:-000}" + if [ "$code" != 200 ] && [ "$code" != 503 ]; then echo "unknown (/api/health $(badge "$code"))" + else python3 - "$body" <<'PY' || echo "unknown (/api/health unreadable)" +import json, sys +h = json.load(open(sys.argv[1])) +if h.get("auth") != "reachable": + print(f"unknown (Auth {h.get('auth', '?')})") + sys.exit(0) +signup = {"open": "open", "closed": "closed"}.get(h.get("signup"), "?") +confirm = {"off": "signs the user straight in", "required": "asks for email confirmation first"}.get(h.get("emailConfirmation"), "?") +schema = {"migrated": "the chat schema in place"}.get(h.get("schema"), f"the chat schema {h.get('schema', '?')}") +print(f"sign-up {signup}; {confirm}; {schema}") +PY + fi + rm -f "$body" +} + +rows="" +for pair in "stage|$stage_url" "prod|$prod_url"; do + env="${pair%%|*}"; url="${pair#*|}" + rows+="| app (${env}) | ${url} | $(badge "$(probe "$url/")") |"$'\n' + rows+="| health check (${env}) | ${url}/api/health | $(badge "$(probe "$url/api/health")") |"$'\n' +done +auth_stage="$(auth_state "$stage_url")"; auth_prod="$(auth_state "$prod_url")" + +now="$(date -u +%Y-%m-%dT%H:%M:%SZ)" + +# Heal the static operating contract 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 + git add ai/context/operations.md 2>/dev/null || true + 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 <<EOF +# ${repo} — live deployment manifest + +> GENERATED by the \`02-docs\` phase on ${now}; re-run it to refresh +> (idempotent; see [operations.md](operations.md)). Hand-edits here are +> overwritten. No secret values appear in this file — secrets are named only. + +## Identity + +| | | +|---|---| +| repository / project slug | \`${repo}\` | +| Orun workspace | \`${ws}\` | +| declared in | \`intent.yaml\` → \`execution.state.workspace\` | +| Workers | \`${brand}-web-stage\`, \`${brand}-web-prod\` on \`${sub}.workers.dev\` | +| CI lane CLI pin | orun \`${lanepin}\` (\`.github/workflows/ci.yml\`) | + +## Public URLs (probed ${now}) + +| surface | URL | status | +|---|---|---| +${rows} +\`/api/health\` answers 200 only when the environment's Supabase project +answers the URL and publishable key the Worker was built with AND its Data +API knows the \`channels\` table the migrations create. The \`dev\` +environment is verify-only by design — no deployed URL. + +## Sign-up and roles + +| environment | Supabase Auth | +|---|---| +| stage | ${auth_stage} | +| prod | ${auth_prod} | + +A project without an SMTP server of its own emails only its organization's +members, so email confirmation is off until the owner turns it on (README, +"Email"; \`authEmailConfirmation\` in the supabase component). Every new +user is a member; the chat's moderator and admin roles are rows in +\`public.user_roles\`, carried into each session by the access-token hook +db-migrate switches on (README, "Roles"). + +## Secrets (names only) + +| secret | where | what it is | +|---|---|---| +| \`CLOUDFLARE_API_TOKEN\` | the workspace | BROKERED from its Cloudflare connection (\`workers-deploy\`): deploys the app's Worker | +| \`CLOUDFLARE_ACCOUNT_ID\` | the workspace | the Cloudflare connection's account id — a fact, not a credential | +| \`SUPABASE_ACCESS_TOKEN\` | the workspace | BROKERED from its Supabase connection (\`management-access\`): creates the project, reads its API keys, sets its Auth, applies the migrations and switches on the access-token hook | +| \`SUPABASE_ORG_ID\` | the workspace | the Supabase connection's organization id — a fact, not a credential | +| \`WIRING_SUPABASE\` | \`${repo}\` on stage and on prod | written by the Supabase root's apply: the project's URL and publishable key, which the app's deploy reads — public by design, not a credential | +| \`SUPABASE_PROJECT_REF\`, \`SUPABASE_DB_PASSWORD\`, \`SUPABASE_DB_URL\` | \`${repo}\` on stage and on prod | written by the Supabase root's apply: the project's ref, its database password and its connection URL, which db-migrate reads | + +Brokered secrets are minted per run, so no long-lived value is at rest. The +service-role key is never published. What the workspace holds right now +(every secret by name, and its integrations and their health) is on the +console's Secrets and Integrations pages for \`${ws}\`. + +## How this deployment changes + +Merges to \`main\` converge automatically: CI plans the changed components and +runs each lane with \`orun run --remote-state\` against the workspace above. +See [operations.md](operations.md) for the full operating contract. +EOF +echo "render-docs: wrote ai/context/deployment.md" + +python3 - <<'PY' +import re +begin, end = "<!-- 02-docs:begin -->", "<!-- 02-docs:end -->" +body = f"""{begin} +This product is **live**. Verified URLs, identity, how sign-up behaves and +the secrets it uses are recorded in +[ai/context/deployment.md](ai/context/deployment.md) (re-rendered by the +`02-docs` phase); 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), lambda _m: body, s, count=1, flags=re.S) +else: + lines = s.splitlines(keepends=True) + at = 1 + while at < len(lines) and lines[at].strip() == "": + at += 1 + lines.insert(at, f"\n## Live deployment\n\n{body}\n") + s = "".join(lines) +open("README.md", "w").write(s) +print("render-docs: README live-deployment section rendered") +PY +echo "render-docs: done" diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml new file mode 100644 index 0000000..a5a2e4b --- /dev/null +++ b/repo-blueprint.yaml @@ -0,0 +1,766 @@ +apiVersion: orun.dev/v1 +kind: Blueprint +metadata: + name: supabase-slack-clone + description: >- + The supabase-slack-clone as a Blueprint of itself — instantiate a new + product repository (Supabase's Next.js Slack clone on Cloudflare Workers + + Static Assets, a Supabase project per environment for its Auth, its data + and its Realtime, provisioned by Terraform, the chat schema applied by + db-migrate) and take it from nothing to live on stage and prod in ONE + landing, then record what went live. Run one phase at a + time with `--phase <name>` or both with `--resume`; see + docs/phases/README.md for the contract every phase follows, and + BOOTSTRAP.md for the operator checklist no script can perform. + +# ── INPUTS ──────────────────────────────────────────────────────────────── +# The instance-identity contract, consumed by tooling/rebrand/rebrand.mjs via +# the `.rebrand/values.json` the `rebrand-values` module templates. Every +# input a later phase needs is in that file, because it is committed and so +# survives a fresh container; `.orun/provenance.lock` does not. +# +# The card (blueprint.yaml) declares a subset of these with the patterns the +# console validates; testing/manifest.test.sh fails if a card input is not +# one of these, or if one of these is required and nothing supplies it. +inputs: + reponame: + type: string + pattern: "^[a-z][a-z0-9-]*$" + required: true + description: >- + Repo slug (e.g. acme-chat) — intent metadata.name, the Worker name + prefix, the secret project, and the `repo` the Supabase project is + named after. + productname: + type: string + required: true + description: The product's display name (e.g. "Acme Chat") — in every page title and on the sign-in page. + productdomain: + type: string + default: "" + description: >- + The product's own domain, once it has one (e.g. acme.dev). NOT ASKED: + the app 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 `<reponame>.example.com` where the domain goes (BASE_DOMAIN + under each environment's `env:` in intent.yaml), so setting it later is + replacing that one string — the product's README, "Custom domain", says + how, together with the SITE_URL that moves the Supabase project's Auth + Site URL onto it. Pass it with --set only to + brand a hand-run build with a domain it already has. + githuborg: + type: string + pattern: "^[A-Za-z0-9][A-Za-z0-9-]*$" + required: true + description: >- + GitHub owner the product's repository is created under. 01-product waits + for the App installation on THIS owner before it creates anything: the + platform learns of a pull request only through the installation on the + account that owns the repository. + subdomain: + type: string + default: "your-workers-subdomain" + description: >- + The workers.dev subdomain of the Cloudflare account the app deploys + into — its URLs, the Site URL and redirect allow-list the Supabase + project's Auth is given, the probes. 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. + repoPrivate: + type: boolean + default: true + description: >- + Whether the repository is created private. Private is the safe default; + `orun.repo/ensure@v1` only sets it at creation — an existing repository + keeps the visibility it has. + 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 (ws_…) for the product's remote state and secrets. + Unset, it is the workspace the build runs in; with none anywhere, + 01-product writes a placeholder that fails loudly rather than silently + claiming another tenant's workspace. + epicSlug: + type: string + pattern: "^[a-z][a-z0-9-]*$" + default: team-chat-baselining + description: >- + The epic this bootstrap tracks itself under. Found by slug, so a run + that starts fresh and a run that resumes find the same work. + +# ── SOURCES ─────────────────────────────────────────────────────────────── +# The baseline is this repository itself. Run `orun new` from its root so +# `path: .` resolves to it; orun pins it by digest into its object store +# before any module reads it, so an instance is reproducible and provenanced. +sources: + - name: baseline + kind: dir + path: . + +# Derived build output, local secrets and state, and the factory's own lanes +# — never carried into an instance. +# +# WHAT `ignore` ACTUALLY EXCLUDES: orun matches an entry two ways, and which +# one depends on the entry. A pattern with no glob metacharacter is compared +# against each path SEGMENT; only a pattern containing one is compared against +# the whole relative path. So `apps/web/.dev.vars` on its own would match +# nothing — it needs the `**/`. testing/coverage.test.sh refuses an entry that +# names a path without a glob. +ignore: + - dist + - coverage + - .turbo + - .next + - .open-next + - .wrangler + - node_modules + - .orun + - .terraform + - plan.json + - "**/*.tsbuildinfo" + - "**/next-env.d.ts" + # Terraform state and what sits beside it: the `.backup`, the timestamped + # backups and the local lock (`.terraform.tfstate.lock.info`). + - "**/*.tfstate" + - "**/*.tfstate.*" + # Python bytecode, should a tool ever run beside a shipped file. + - __pycache__ + - "**/*.pyc" + # `orun new` snapshots the WORKING TREE, not the git index: an operator's + # local environment files would otherwise be copied into somebody else's + # repository. `.env.example` and `.dev.vars.example` are not among them, + # and ship — which is why this is not `.env*` and `.dev.vars*`. Every other + # name is: the bare file, a `.local` override, and a per-mode or + # per-environment file (`.env.production`, `.dev.vars.stage`). `[^e]` is + # path.Match's "any character but e", so only a suffix that starts with + # `e` gets past these, and testing/leak.test.sh lets only `.example` ship. + - "**/.env" + - "**/.env.local" + - "**/.env.*.local" + - "**/.env.[^e]*" + - "**/.dev.vars" + - "**/.dev.vars.local" + - "**/.dev.vars.*.local" + - "**/.dev.vars.[^e]*" + # THE FACTORY'S OWN LANES. `github-workflows` copies the whole of `.github`, + # so without these two entries every product built from this baseline would + # carry them — `baseline.yml` runs `testing/*.sh`, which no module places, + # and `tag.yml` cuts baseline tags a product does not have. + # testing/coverage.test.sh fails if a lane reading `testing/` is not here. + - "**/.github/workflows/baseline.yml" + - "**/.github/workflows/tag.yml" + +# ── MODULES ─────────────────────────────────────────────────────────────── +# One module per component or root file. Root files are single-file modules +# rather than one module with an include list: a file shipping to a product +# is a line in a diff, and nothing of the factory (specs/, tasks/, testing/, +# hooks/, docs/phases/, tooling/rebrand/, tooling/bootstrap/, the blueprints, +# BOOTSTRAP.md, .baseline/) can ship by accident. testing/leak.test.sh holds +# that line. +# +# Every module lands in ONE phase (01-product). `dependsOn` here orders the +# placement only — what has to exist before what is written — and mirrors the +# components' own graph; the DEPLOY order is the components' `dependsOn`, +# which the product's own plan enforces on main. +modules: + # ── the identity file every later phase reads back ─────────────────────── + # The only place blueprint inputs touch the tree; everything else is a + # verbatim copy the `rebrand` hook rewrites. Committed, so a phase run months + # later from a fresh container recovers what the operator answered. + - name: rebrand-values + mode: template + files: + ".rebrand/values.json": | + { + "reponame": "{{ .reponame }}", + "productname": "{{ .productname }}", + "productdomain": "{{ .productdomain }}", + "subdomain": "{{ .subdomain }}", + "orunWorkspace": "{{ .orunWorkspace }}", + "githuborg": "{{ .githuborg }}", + "epicSlug": "{{ .epicSlug }}" + } + + # ── root files ─────────────────────────────────────────────────────────── + - 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 + # The baseline's complete lockfile, as it is: the whole tree lands at once + # and the lockfile carries no identity, so there is nothing to re-resolve — + # the lanes install it with --frozen-lockfile, and the baseline's own CI + # (testing/e2e.test.sh) does the same on this exact tree before a tag. + - 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 README, not this repository's: this one is about the + # baseline (how to instantiate it, how it is tested), and a product's owner + # has no use for any of that. + - name: root-readme + mode: copy + source: baseline + from: .baseline/product/README.md + to: README.md + # The product's guide for a coding agent, at the root where agents look + # first. The build's last screen hands the owner a prompt that ends "Then + # clone <repo> and start building on it"; this is what the agent finds + # there: what the product is, what to read, how a change lands, what not + # to touch. The product's, like the README: this repository's own agents + # read ai/context/current.md. + - name: root-agents + mode: copy + source: baseline + from: .baseline/product/AGENTS.md + to: AGENTS.md + - name: github-workflows + mode: copy + source: baseline + from: .github + to: .github + - name: vscode + mode: copy + source: baseline + from: .vscode + to: .vscode + + # The two context pages a product genuinely owns: its operating contract, + # and the deployment manifest 02-docs renders. One module per file, so a new + # file in ai/context/ cannot ship without somebody writing a module for it. + - name: ai-operations + mode: copy + source: baseline + from: ai/context/operations.md + to: ai/context/operations.md + - name: ai-deployment + mode: copy + source: baseline + from: ai/context/deployment.md + to: ai/context/deployment.md + + # ── shared tooling ─────────────────────────────────────────────────────── + # Only what a PRODUCT runs: the TypeScript and ESLint configuration, the + # deploy-time wrangler renderer, and the migration-manifest checker + # packages/db's scripts call. The factory's tooling (rebrand, bootstrap) + # stays here. + - name: tooling-tsconfig + mode: copy + source: baseline + from: tooling/tsconfig + to: tooling/tsconfig + - name: tooling-eslint + mode: copy + source: baseline + from: tooling/eslint + to: tooling/eslint + - name: tooling-wire + mode: copy + source: baseline + from: tooling/wire + to: tooling/wire + - name: tooling-migrations + mode: copy + source: baseline + from: tooling/migrations + to: tooling/migrations + + # ── the data plane ─────────────────────────────────────────────────────── + # A Supabase project per environment — its Auth pointed at the app's + # Worker, its URL and publishable key published as WIRING_SUPABASE — and + # the chat schema, applied by db-migrate after the project exists. No + # Hyperdrive: the app never opens a Postgres connection; it speaks to Auth, + # the Data API and Realtime from the browser with supabase-js. + - name: db + mode: copy + source: baseline + from: packages/db + to: packages/db + dependsOn: [tooling-eslint, tooling-migrations, tooling-tsconfig] + - name: supabase + mode: copy + source: baseline + from: infra/terraform/supabase + to: infra/terraform/supabase + - name: db-migrate + mode: copy + source: baseline + from: infra/db-migrate + to: infra/db-migrate + dependsOn: [db, supabase] + + # ── the app ────────────────────────────────────────────────────────────── + - name: web + mode: copy + source: baseline + from: apps/web + to: apps/web + dependsOn: [db-migrate, supabase, tooling-eslint, tooling-tsconfig, tooling-wire] + + # ── the tests ──────────────────────────────────────────────────────────── + - name: db-tests + mode: copy + source: baseline + from: tests/db + to: tests/db + dependsOn: [db, tooling-eslint, tooling-tsconfig] + - name: web-tests + mode: copy + source: baseline + from: tests/web + to: tests/web + dependsOn: [tooling-eslint, tooling-tsconfig, tooling-wire, web] + +# ── THE WORK, UP FRONT ──────────────────────────────────────────────────── +# The bootstrap is work, so it lives where work lives — and all of it is on +# the plane before the first phase places a file: one epic, one milestone per +# phase in the order the phases run, one task per landing. +# +# `hooks.preInstantiate` (orun >= v2.60) runs under no phase, once per run, on +# a resume too. Everything here is find-or-create BY IDENTITY — the epic by +# slug, a milestone by name within its epic, a task by title within its epic — +# so a second run, a resume and a redo all find what the first run made. The +# milestones are created IN ORDER and BEFORE the tasks: the plane appends each +# new milestone after the last, and a task naming a milestone the epic does +# not have yet would create it out of order. +# +# IN THE BACKGROUND (orun >= v2.88.0, `background: true` on every hook here). +# Nothing a phase does before its landing reads the task plane — the provider +# check, the placement, the rebrand, the repository, the secrets — so the +# whole list runs beside 01-product instead of before it, in order. A hook +# that works on the plane (`orun.task/ensure@v1`, `orun.pr/land@v1`) waits +# for it to finish; a failure here stops the build at the next hook. +# +# Each phase's own `task` hook runs `orun.task/ensure@v1` on its task again, +# just before its landing. Same identity, so it finds rather than creates, +# and it is how the phase gets the task's KEY for its landing; it sits in +# `post` rather than `pre` so that everything before it overlaps with this +# list. +hooks: + preInstantiate: + - id: epic + uses: orun.task/ensure@v1 + background: true + narrate: 'Epic {{ .hooks.epic.outputs.key }} is open.' + with: + kind: epic + slug: "{{ .inputs.epicSlug }}" + name: "Team chat baselining — {{ .inputs.productname }}" + description: >- + Everything the supabase-slack-clone baseline builds for + {{ .inputs.productname }} in {{ .inputs.githuborg }}/{{ .inputs.reponame }}: + the repository and its CI, the Supabase project per environment with + its Auth pointed at the app, the chat schema, the app live on stage + and prod, and the record of what went live. One milestone per phase, in the + order the phases run; 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-product + exitCriteria: + - repository created under {{ .inputs.githuborg }}, linked to the workspace, the whole product merged + - the Supabase project applied, the chat schema migrated, then the app deployed, on stage and prod — in that order + - the home page and /api/health answer on both workers.dev URLs + - id: m02 + uses: orun.task/ensure@v1 + background: true + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 02-docs + exitCriteria: + - ai/context/deployment.md on main matches the probed live URLs + - prod waits on stage again, and dev verifies every merge to main again + - id: t01 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 01-product + name: "Build the product in one landing" + brief: >- + Create {{ .inputs.githuborg }}/{{ .inputs.reponame }} and land the + whole product as one pull request, branded as + {{ .inputs.productname }}: the intent, CI and tooling, the Supabase + Terraform root, the migrations and the app. The convergence that + merge triggers provisions the project, migrates it and deploys the + app, in that order, on stage and prod. + prefix: BASE + contract: .baseline/tasks/01-product.TaskContract.yaml + - id: t02 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 02-docs + name: "Record the live deployment" + brief: >- + Probe every live URL one last time and write the deployment record + into the repository from what actually answered — whether the schema + is in place included — not from what the blueprint intended. + prefix: BASE + contract: .baseline/tasks/02-docs.TaskContract.yaml + +# ── PHASES ──────────────────────────────────────────────────────────────── +# A phase is orun's own barrier over the module DAG and the whole of what a +# phase DOES: what it is for a person (`title`), what to budget +# (`expectedMinutes`), what must already be true (`requires`), 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 names +# the task plane's milestones carry. +# +# TWO PHASES, ONE LANDING THAT DEPLOYS. Everything the product is made of — +# root files, workflows, tooling, the Terraform root, the migrations, the app +# and its tests — lands as ONE pull request, and ONE convergence on main +# provisions, migrates and deploys it. The order the infrastructure needs is +# not a sequence of landings: it is the components' own `dependsOn`, each edge +# `mode: enforced` on a push to main — supabase → db-migrate → web, per +# environment. A job resolves its secrets when it starts, so each one finds +# what the apply before it lease-published. +# `02-docs` places nothing: it records the deployment and puts back what +# 01-product deferred. +phases: + - name: 01-product + title: The product, built in one landing + description: The whole tree — manifests, CI, tooling, the Supabase root, the migrations, the app and its tests — branded, landed as one pull request, and provisioned, migrated and deployed by one convergence. + # An estimate, not a measurement: no bootstrap of this baseline has been + # timed. The convergence is most of it — a Supabase project takes five to + # seven minutes to come up, then the migrations, then the app's build, + # deploy and smoke, stage and prod side by side: supabase-starter's figure + # on the v2.88.0 shape (12, the project and the app) plus a minute for the + # db-migrate lane between them. + expectedMinutes: 13 + # The console's build panel shows these lines verbatim, and the hooks' + # own `narrate:` below as its progress, so each says one true thing, + # briefly. NO `await` LINE, in either phase: a wait is also what the + # `requires.probe` below does while a connection is missing, and with no + # authored line the engine says it itself — "<title>: <what it waits + # on>" — where an authored one could only guess. + narrate: + start: "Landing the whole product as one pull request, then deploying it to stage and prod — about {{ .meta.expectedMinutes }} minutes." + done: "{{ .inputs.productname }} is live on stage and prod, each on its own migrated Supabase project ({{ .meta.elapsed }})." + failed: "The product is not up. The step above names what stopped it; whatever it already created is still there." + modules: [ai-deployment, ai-operations, db, db-migrate, db-tests, github-workflows, rebrand-values, root-agents, root-gitignore, root-intent, root-package-json, root-pnpm-lock, root-pnpm-workspace, root-readme, root-turbo, supabase, tooling-eslint, tooling-migrations, tooling-tsconfig, tooling-wire, vscode, web, web-tests] + # 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. So the owner's connection is asked for here, + # before a repository is created, and waited for like any other consent — + # with the Cloudflare and Supabase connections every credential below is + # minted from, since this is the phase that provisions and deploys. + requires: + probe: + - id: providers + uses: orun.doctor/check@v1 + with: + providers: [github, cloudflare, supabase] + githubOwner: "{{ .inputs.githuborg }}" + waitSeconds: 600 + pollSeconds: 20 + hooks: + post: + # A RE-RUN MUST HAVE SOMETHING TO LAND. A convergence can fail AFTER + # its PR merged, and the merge has already put every file 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`. retouch.mjs + # rewrites ONE trailing marker line — `# orun: redeploy <phase> + # <stamp>` — in each component.yaml the task contract names, so the + # landing has a diff and exactly those components re-plan. 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 }}/.baseline/tasks/01-product.TaskContract.yaml"] + # The identity chain. rebrand.mjs enumerates the tree with + # `git ls-files`, so the output has to be a git repository with a + # populated index BEFORE it runs. `git add -A` only stages; the + # landing commits. + - id: git-init + run: ["git", "init", "-q"] + - id: stage + run: ["git", "add", "-A"] + - id: rebrand + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--values", ".rebrand/values.json", "--allow-dirty"] + # Re-tenant the product. rebrand.mjs treats the orun state backend as + # org-owned and leaves it alone, so intent.yaml would keep THIS + # repository's `workspace:` — the product'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. + - 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 before = fs.readFileSync("intent.yaml", "utf8"); + // Look for the line rather than for a change: a product built + // into a workspace already named there rewrites the line to the + // value it already has, and "unchanged" is not "missing". + const line = /^(\s*workspace:\s*).*$/m; + if (!line.test(before)) { + console.error("orun-workspace: no `workspace:` line in intent.yaml — refusing to guess"); + process.exit(1); + } + fs.writeFileSync("intent.yaml", before.replace(line, "$1" + ws)); + console.log( + ws === "ws_SET_ME" + ? "orun-workspace: wrote placeholder ws_SET_ME — set your Orun Cloud workspace before enabling remote state" + : "orun-workspace: intent.yaml workspace -> " + ws, + ); + # The product carries no work tree of this repository's: `specs/` and + # `tasks/` never ship, so intent.yaml's `work:` block would point its + # every plan at two directories that do not exist. + - id: work-tree + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/work-tree.mjs", "--strip"] + # STAGE AND PROD DEPLOY SIDE BY SIDE UNTIL THE BOOTSTRAP IS DONE. The + # promotion gate makes prod wait out stage's whole chain (the Supabase + # project, the migrations, then the app); during a bootstrap both are empty + # and the convergence is watched to green, so it protects nothing and + # doubles the wall-clock. Deferred here, restored by 02-docs. + # 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, by the + # same mechanism: a third Next.js build and both test packages on the + # merge prove nothing the baseline's own CI did not. Pull requests keep + # their dev lanes. 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: restage + run: ["git", "add", "-A"] + - id: rebrand-verify + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] + # The repo has to exist before there is anywhere to land. + - id: repo + uses: orun.repo/ensure@v1 + 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, resolved through the repo link. + # `link` may be refused where the credential cannot write links (a + # workspace key) and the platform has linked the repository already, + # so it is best effort and `check` is the gate — an unlinked + # repository stops here, naming the fix, instead of in every lane. + - id: link + narrate: "The repository is linked to the workspace, so its CI can sign in." + 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 }}" + # The provider credentials, brokered, in ONE hook PER PROVIDER (orun + # >= v2.87.0): `secrets` mints each key under its own scope template + # from the one connection of that provider the build is bound to, + # reading the connections and the existing secrets once and creating + # the missing keys side by side. Two hooks, because a reconcile reads + # one connection: Cloudflare's two keys, then Supabase's two. Keys + # that already exist are kept. After the link, before the landing + # whose convergence uses them: + # CLOUDFLARE_API_TOKEN web's deploy (the composition's binding) + # CLOUDFLARE_ACCOUNT_ID web's deploy + # SUPABASE_ACCESS_TOKEN supabase's provider (the project, its API + # keys, its Auth settings) and db-migrate's + # runner (the Management API's query, and + # the access-token hook it switches on) + # SUPABASE_ORG_ID supabase (TF_VAR_supabaseOrgId) + # No Hyperdrive, D1, KV or R2 token: the app reaches Supabase over + # HTTPS with the publishable key, which the supabase apply publishes + # in WIRING_SUPABASE itself. + # + # Each line is static: a hook id with a `-` cannot be named in a + # template, and the line is true whether the keys were minted now or + # kept from an earlier run. + - id: secrets-cloudflare + uses: orun.integrations/reconcile@v1 + narrate: "CLOUDFLARE_API_TOKEN, for Workers deploys, and CLOUDFLARE_ACCOUNT_ID are in place from the Cloudflare connection." + with: + provider: cloudflare + secrets: + - { key: CLOUDFLARE_API_TOKEN, template: workers-deploy } + - { key: CLOUDFLARE_ACCOUNT_ID, template: account-id } + - id: secrets-supabase + uses: orun.integrations/reconcile@v1 + narrate: "SUPABASE_ACCESS_TOKEN, for the Supabase projects and their migrations, and SUPABASE_ORG_ID are in place from the Supabase connection." + with: + provider: supabase + secrets: + - { key: SUPABASE_ACCESS_TOKEN, template: management-access } + - { key: SUPABASE_ORG_ID, template: org-id } + # The task this landing closes, and its key. The run-level list above + # opens it in the background; this is the first hook that needs it, + # so it is the one that waits for that list (orun >= v2.88.0) — every + # hook before it ran while the task plane was still being set up. + - id: task + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: "{{ .phase.name }}" + name: "Build the product in one landing" + prefix: BASE + contract: .baseline/tasks/01-product.TaskContract.yaml + # THE PRODUCT IS A PULL REQUEST THAT IS CHECKED, THEN MERGED — checked + # HERE (`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 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 ~25 s. A tree that fails is never pushed. The PR's CI still + # runs (`plan` alone on a bootstrap branch, `orun/BASE-…`, ci.yml); + # nothing waits for it. The merge runs every lane on main a minute + # later, for real, and the convergence after it is what this phase + # watches to green. A landing succeeds only once its PR is merged; + # `landed` is "false" when main already had every file (a re-run + # with nothing to land). + - id: land + uses: orun.pr/land@v1 + label: Product + 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: "feat: {{ .inputs.productname }}, the whole product from the supabase-slack-clone baseline" + checks: local + await: + - id: converge + uses: orun.run/watch@v1 + narrate: "The convergence run is green: Supabase, the migrations, then the app, on stage and prod." + with: + # The run for the commit THIS landing merged (an unpinned watch + # reads the previous push's run). The budget is roughly three + # times expectedMinutes: a Supabase project can take ten minutes + # on a busy region, and there is room for one resume. + sha: "{{ .phase.hooks.land.outputs.mergeSha }}" + repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" + resumeBudget: 3 + waitSeconds: 3600 + # Read every 5 s, not the action's 40: the build goes on the + # moment the run is green instead of up to 40 s after it. + pollSeconds: 5 + # NO SEPARATE CHECK OF WHAT THE APPLY PUBLISHES. It lease-publishes + # its outputs to the project's stage and prod rungs, and each one is + # resolved IN THIS CONVERGENCE, from the place every later run looks, + # by a job that waits for the apply on main (`mode: enforced`): + # SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD, SUPABASE_DB_URL — + # db-migrate, per environment (its component.yaml `secretEnv`, + # fail-closed: a missing document fails the lane before it runs); + # WIRING_SUPABASE — the project URL and publishable key — web's + # deploy, this environment's document (apps/web/component.yaml's + # optionalSecretEnv), and its build's render + # (tooling/wire/live.mjs --env) fails the lane when it is missing. + # A green convergence already says every key is there, on stage and on + # prod. testing/phases.test.sh holds that, key by key, and asks for an + # `orun.secrets/exists@v1` here for any key that loses its reader. + - id: verify + uses: orun.http/probe@v1 + narrate: "The app and its health check — the project's Auth reachable, the chat schema in place — answered on stage and prod." + with: + urls: + - "https://{{ .inputs.reponame }}-web-stage.{{ .inputs.subdomain }}.workers.dev" + - "https://{{ .inputs.reponame }}-web-stage.{{ .inputs.subdomain }}.workers.dev/api/health" + - "https://{{ .inputs.reponame }}-web-prod.{{ .inputs.subdomain }}.workers.dev" + - "https://{{ .inputs.reponame }}-web-prod.{{ .inputs.subdomain }}.workers.dev/api/health" + + # Places nothing. It records what 01-product built, from PROBED facts rather + # than from what the blueprint intended — which is why it runs last. Its + # render probes every URL as it writes the record, and this landing + # redeploys nothing, so there is no probe after it to wait for. + - name: 02-docs + title: The deployment, recorded + description: The live-deployment manifest, rendered from probed reality, and the promotion gate and dev's lanes put back. + # An estimate: the render's probes, a landing checked in the box, a merge. + expectedMinutes: 1 + narrate: + start: "Probing the live URLs and writing down what answered." + done: "The deployment record is on main, and prod waits on stage again ({{ .meta.elapsed }})." + failed: "The step above names what stopped it. This phase changes nothing the product runs." + modules: [] + requires: + phases: [01-product] + hooks: + post: + # THE PRODUCT GOES LIVE WITH ITS PROMOTION GATE. 01-product 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-product deferred it). + - id: dev-lanes + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/dev-lanes.mjs", "--restore"] + - id: render + narrate: "ai/context/deployment.md and the README's live section are written from what each URL answered." + run: ["bash", "{{ .baseline.dir }}/hooks/render-deployment-docs.sh", ".", "{{ .inputs.orunWorkspace }}", "{{ .baseline.dir }}"] + - id: task + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: "{{ .phase.name }}" + name: "Record the live deployment" + prefix: BASE + contract: .baseline/tasks/02-docs.TaskContract.yaml + # Checked here and merged, as 01-product's landing is. Nothing after + # it: the render's probes are this phase's check, and 01-product's + # probe already filed the addresses, once. + - 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 the live deployment state" + checks: local diff --git a/specs/epics/README.md b/specs/epics/README.md index 1f2ac13..189fa80 100644 --- a/specs/epics/README.md +++ b/specs/epics/README.md @@ -7,6 +7,6 @@ folder is the adoption; the merge creates the epic in the workspace. | Epic | Cluster | Status | What it is | |------|---------|--------|------------| -| [`supabase-slack-clone/`](./supabase-slack-clone/) | **SL** | In progress | Supabase's Next.js Slack clone, equivalent in code and function, on Cloudflare Workers with the Supabase project provisioned and migrated by Orun — and an Orun baseline that instantiates it in one landing (SL4, `baseline-v1`) | +| [`supabase-slack-clone/`](./supabase-slack-clone/) | **SL** | ✅ Shipped (`baseline-v1`); live bootstrap pending | Supabase's Next.js Slack clone, equivalent in code and function, on Cloudflare Workers with the Supabase project provisioned and migrated by Orun — and an Orun baseline that instantiates it in one landing (SL4, `baseline-v1`) | As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`. diff --git a/specs/epics/supabase-slack-clone/IMPLEMENTATION-STATUS.md b/specs/epics/supabase-slack-clone/IMPLEMENTATION-STATUS.md index 3df86d2..bbc204b 100644 --- a/specs/epics/supabase-slack-clone/IMPLEMENTATION-STATUS.md +++ b/specs/epics/supabase-slack-clone/IMPLEMENTATION-STATUS.md @@ -9,13 +9,12 @@ at `9eaae4cd2cf8e67f9aeadab044e9a14429331c13`. | SL0 — the spec | [#1](https://github.com/sourceplane/supabase-slack-clone/pull/1) | ✅ merged | | SL1 — the chat app on Workers | [#2](https://github.com/sourceplane/supabase-slack-clone/pull/2) | ✅ merged | | SL2 — the Supabase project and the schema | [#3](https://github.com/sourceplane/supabase-slack-clone/pull/3) | ✅ merged | -| SL3 — ready to instantiate | [#4](https://github.com/sourceplane/supabase-slack-clone/pull/4) | in review | -| SL4 — a baseline | [#5](https://github.com/sourceplane/supabase-slack-clone/pull/5) | planned | +| SL3 — ready to instantiate | [#4](https://github.com/sourceplane/supabase-slack-clone/pull/4) | ✅ merged | +| SL4 — a baseline | [#5](https://github.com/sourceplane/supabase-slack-clone/pull/5) | ✅ merged, tagged `baseline-v1` | -The app builds and its tests pass; the migrations apply on a -Supabase-shaped Postgres in process. Nothing has been applied against a real -Supabase organization (risk SL-A); the baseline that bootstraps a product, -and the tiers that prove it end to end, are SL4. +Proven offline (Baseline CI, against a local Supabase stand-in); the +Terraform apply, the migrations and the deploy are gated until a workspace +is linked, and no live bootstrap has run (risk SL-A). ## Departures from upstream @@ -36,7 +35,7 @@ byte. | `supabase/migrations`, `supabase/seed.sql` | `supabase db push`, `seed.sql` | `packages/db/src/migrations/010_init`, `020_auth_hook`, `030_seed`, byte for byte, applied by db-migrate | One runner and one ledger per project; the seed's `#public` is where the app sends a signed-in user | | `supabase/config.toml` `[auth.hook.custom_access_token]` | `supabase config push` | `packages/db/src/auth-config.ts`, set by the runner after the migrations | Auth must not point at a function that does not exist yet (risk SL-B) | | `supabase/config.toml` `enable_confirmations = true` | confirmation on | off until the project has SMTP (`authEmailConfirmation`) | A fresh project's built-in email reaches only its organization's members (risk SL-H) | -| `README.md`, "Deploy with Vercel" | a Vercel clone button | Orun's pipeline (SL4: `orun new`) | A product on Cloudflare does not offer its visitors that | +| `README.md`, "Deploy with Vercel" | a Vercel clone button | `orun new` | A product on Cloudflare does not offer its visitors that | ## SL0 — the spec @@ -95,3 +94,35 @@ wrangler config. The README (the upstream example first, the mapping to Vercel and Supabase, how to run, test, preview and deploy) and this status. + +## SL4 — a baseline + +In supabase-starter's current shape (`SS10`), with db-migrate between the +project and the app: + +- `blueprint.yaml` (requires github, cloudflare, supabase; subdomain from + the Cloudflare connection; no domain asked; four brokered secrets; 14 + minutes) and `repo-blueprint.yaml` (`01-product`, 13 minutes; `02-docs`, + 1). No await but the convergence watch and the probe: every key the apply + publishes is read fail-closed in the convergence (`testing/phases.test.sh` + holds it key by key). +- `.baseline/`: the identity, the product's README (with "Deploy by hand", + "Roles", "Your first migration", "Email", "Custom domain") and AGENTS.md, + the two task contracts. +- The rebrand (the `SITE_NAME` seam; migrations never rewritten; the + example's home protected), the bootstrap helpers, the deployment record + (sign-up, roles and whether the schema is in place, read from + `/api/health`), the context pack, the generated component docs. +- The tiers: contract tests, the blueprint read by orun v2.88.0, the leak + gate, the offline bootstrap and the product's plans + (`supabase → db-migrate → web`, enforced; advisory on a pull request), and + the e2e: the landing's own checks; db-migrate's own steps against the + stand-in, which now runs the configured hook; the web lane in its staged + job tree with the stage wiring inlined; the smoke refused before the + migrations and passing after; and the chat as a member, a moderator and an + admin — roles in their sessions, the starter channels with authors, a + message posted and read back, deletes allowed and refused by role, a + channel added and removed, nothing for the bare publishable key, the + publication. + +Not proven live: risk SL-A. diff --git a/specs/epics/supabase-slack-clone/README.md b/specs/epics/supabase-slack-clone/README.md index 74cf262..1101fba 100644 --- a/specs/epics/supabase-slack-clone/README.md +++ b/specs/epics/supabase-slack-clone/README.md @@ -8,13 +8,14 @@ The upstream code stays the code: `lib/Store.js` (the client, the data hooks, th | Field | Value | |-------|-------| -| Status | In progress — SL0–SL2 shipped ([#1](https://github.com/sourceplane/supabase-slack-clone/pull/1)–[#3](https://github.com/sourceplane/supabase-slack-clone/pull/3)), SL3 in review, SL4 next | +| Status | ✅ SL0–SL4 shipped (SL4 tagged `baseline-v1`). Supabase apply, migration and live deploy gated on a linked workspace; not yet proven by a live bootstrap (risk SL-A) | | Cluster | **SL** (SL0–SL4) | | Owner(s) | `apps/web` (the app) · `tests/web` · `infra/terraform/supabase` (the project) · `packages/db` + `infra/db-migrate` (the schema) · `tests/db` | | Builds on | `supabase-starter` — the shape of the repository and of the baseline, the `supabase` Terraform root, the stand-in; `sveltekit-saas` — the db-migrate lane on a Supabase project | | Upstream | [supabase/supabase `examples/slack-clone/nextjs-slack-clone`](https://github.com/supabase/supabase/tree/master/examples/slack-clone/nextjs-slack-clone), at `9eaae4cd2cf8e67f9aeadab044e9a14429331c13` | | Licence | the example's `package.json` says MIT; the supabase/supabase repository is Apache-2.0, whose text `apps/web/LICENSE` carries | | Decisions locked | (1) OpenNext on Workers + Static Assets, no Hyperdrive: nothing on the server opens a Postgres connection. (2) The publishable key is a wrangler var; no service-role key is published or read. (3) Upstream's migrations and seed are db-migrate migrations, byte for byte. (4) The access-token hook is set by the runner after the migrations, not by Terraform. (5) supabase → db-migrate → web, enforced on main, advisory on pull requests. (6) `/api/health` is read-only and answers only from the Worker. | +| Shipped as | `baseline-v1` (SL4) | ## Read order diff --git a/testing/bootstrap-defer.test.sh b/testing/bootstrap-defer.test.sh new file mode 100755 index 0000000..526e2b4 --- /dev/null +++ b/testing/bootstrap-defer.test.sh @@ -0,0 +1,67 @@ +#!/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 + +echo "── work-tree.mjs — the baseline's work tree does not ship" +f="$tmp/intent.yaml"; cp "$root/intent.yaml" "$f" +node "$root/tooling/bootstrap/work-tree.mjs" --check --file "$f" | grep -q declared && ok "this repository declares a work tree" || bad "this repository declares a work tree" +node "$root/tooling/bootstrap/work-tree.mjs" --strip --file "$f" >/dev/null +node "$root/tooling/bootstrap/work-tree.mjs" --check --file "$f" | grep -q absent && ok "--strip removes it" || bad "--strip removes it" +python3 - "$f" "$root/intent.yaml" <<'PY' && ok "everything else in the intent is untouched" || bad "everything else in the intent is untouched" +import sys, yaml +after, before = (yaml.safe_load(open(p)) for p in sys.argv[1:3]) +assert "work" not in after, list(after) +before.pop("work") +assert after == before, "a key other than work: changed" +PY +grep -q 'Where the work lives' "$f" && bad "the block's own comment is left behind" || ok "the block's own comment goes with it" +cp "$f" "$tmp/once.yaml"; node "$root/tooling/bootstrap/work-tree.mjs" --strip --file "$f" >/dev/null +cmp -s "$f" "$tmp/once.yaml" && ok "a second --strip changes nothing" || bad "a second --strip changes nothing" + +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/coverage.test.sh b/testing/coverage.test.sh new file mode 100755 index 0000000..fd5ddd9 --- /dev/null +++ b/testing/coverage.test.sh @@ -0,0 +1,264 @@ +#!/usr/bin/env bash +# EVERY COMPONENT THIS REPO SHIPS IS PLACED BY EXACTLY ONE PHASE +# (saas-bootstrap-engine BE5, Tier 0). +# +# `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 test suite a product genuinely needs, and the next +# baseline-only directory should have to be argued for in a diff. +# EMPTY: every component here is a product's. The baseline's own suites live in +# `testing/`, which is not a component at all and so is not one this gate can +# miss. The map stays so that the next baseline-only directory has to be +# argued for in a diff; the check below refuses an exemption whose directory is +# absent, so a stale entry cannot linger. +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 THE CATALOG SEES OF EACH COMPONENT ─────────────────────────────── +# +# Every component ships its generated pages (overview, architecture, runbook) +# and must ATTACH them in `spec.docs`: a `docs/` folder no manifest declares is +# never attached, so a fresh product's Docs library showed nothing for any +# component and the catalog failed every one of them on docs and on runbook. +# A component also needs a description: it is the catalog's one-line answer to +# "what is this", and the two test suites had none. +# +# And a domain may not share a component's name. The catalog keys entities by +# name, so the `web` domain (`spec.domain: web`) took the `web` component's +# place, and the product's one deployable was missing from its own catalog. +WANT_DOCS = {"overview": "docs/overview.md", "architecture": "docs/architecture.md", "runbook": "docs/runbook.md"} +names, domains = {}, {} +for comp in components: + if comp in BASELINE_ONLY: + continue + doc = yaml.safe_load((root / comp / "component.yaml").read_text()) or {} + meta, spec = doc.get("metadata") or {}, doc.get("spec") or {} + names[meta.get("name")] = comp + for domain in (spec.get("domain"), (meta.get("labels") or {}).get("domain")): + if domain: + domains.setdefault(domain, comp) + if not (meta.get("description") or "").strip(): + bad(f"{comp}/component.yaml has no metadata.description — the catalog shows the component with nothing to say") + docs = spec.get("docs") or {} + got = {"overview": docs.get("overview")} + for page in docs.get("pages") or []: + got[page.get("role")] = page.get("path") + for role, path in WANT_DOCS.items(): + if got.get(role) != path: + bad(f"{comp}/component.yaml does not attach {path} as its {role} " + f"(spec.docs) — the page ships and the catalog never sees it") + elif not (root / comp / path).is_file(): + bad(f"{comp}/component.yaml attaches {path}, which does not exist") +for domain, comp in sorted(domains.items()): + if domain in names: + bad(f"{comp} declares domain `{domain}`, which is also the name of the " + f"component in {names[domain]} — the catalog keeps one of the two") + +# ── 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 this file's own +# blueprint, 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. +# A nightly lane did exactly this once: shipped, on a cron, reading an intent +# file no product has. +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.') + +# ONE WORKFLOW ON A PUSH TO MAIN, in what a product carries. The bootstrap +# watches each phase's convergence with `orun.run/watch@v1` and `sha:`, which +# takes the newest workflow run for the merge commit — from any workflow. A +# second one on push (checks.yml did this) can be the run it finds: the first +# live bootstrap watched Checks go green while ci.yml's deploy lanes had +# failed. So every shipped workflow but ci.yml stays off pushes to main. +import yaml as _yaml +on_push = [] +for wf in workflows: + rel = f".github/workflows/{wf.name}" + if f"**/{rel}" in ignored or rel in ignored: + continue # the factory's own; never in a product + doc = _yaml.safe_load(wf.read_text(encoding="utf-8")) or {} + on = doc.get("on", doc.get(True)) # PyYAML reads a bare `on:` key as True + if isinstance(on, str): + on = {on: None} + elif isinstance(on, list): + on = {k: None for k in on} + push = (on or {}).get("push", "absent") + if push == "absent": + continue + branches = (push or {}).get("branches") if isinstance(push, dict) else None + if branches is None or "main" in branches: + on_push.append(wf.name) +if on_push != ["ci.yml"]: + bad(f"the workflows a product runs on a push to main are {on_push or 'none'}; " + f"it must be exactly ci.yml — orun.run/watch@v1 watches the newest run " + f"for a commit from ANY workflow, so a second one hides the convergence") + +# A MANUAL RUN (the deploys contract, packages/contracts DEPLOY_WORKFLOW in +# orun-cloud). Orunbase's Run and Deploy buttons dispatch ci.yml on main with +# inputs component, environment and deploy_id, then find the run by the deploy +# id in its name; GitHub refuses a dispatch whose inputs the workflow does not +# declare (422), so a product without them has dead buttons. The plan step +# must plan a dispatch under the push-to-main binding (what a merge deploys), +# on main only, and read the inputs from env, never interpolate them. +import yaml as _ydisp +_ci_path = root / ".github" / "workflows" / "ci.yml" +_ci = _ydisp.safe_load(_ci_path.read_text(encoding="utf-8")) or {} +_on = _ci.get("on", _ci.get(True)) or {} +_wd = _on.get("workflow_dispatch") if isinstance(_on, dict) else None +_inputs = (_wd or {}).get("inputs") or {} +if set(_inputs) != {"component", "environment", "deploy_id"}: + bad(f"ci.yml's workflow_dispatch declares inputs {sorted(_inputs) or 'none'}; Orunbase " + f"dispatches component, environment and deploy_id, and GitHub refuses unknown inputs") +else: + _intent = _ydisp.safe_load((root / "intent.yaml").read_text(encoding="utf-8")) or {} + _envs = set((_intent.get("environments") or {}).keys()) + _opts = set(_inputs["environment"].get("options") or []) + if _inputs["environment"].get("type") != "choice" or _opts != _envs: + bad(f"ci.yml's environment input offers {sorted(_opts)}; intent.yaml declares {sorted(_envs)}") + if "github-push-main" not in ((_intent.get("automation") or {}).get("triggerBindings") or {}): + bad("a manual run plans under intent.yaml's github-push-main binding, which is missing") +if "inputs.deploy_id" not in str(_ci.get("run-name", "")): + bad("ci.yml's run-name must carry inputs.deploy_id: Orunbase finds a deploy's run by that id") +_steps = (_ci.get("jobs") or {}).get("plan", {}).get("steps") or [] +_plan_step = next((s for s in _steps if "plan_args" in str(s.get("run", ""))), None) +if _plan_step is None: + bad("ci.yml's plan job has no step that builds plan_args") +else: + _run = _plan_step["run"] + for _needle, _why in ( + ('"$GITHUB_EVENT_NAME" = "workflow_dispatch"', "plans a dispatch on its own branch"), + ("--trigger github-push-main", "plans a dispatch as a merge to main"), + ('"$GITHUB_REF" != "refs/heads/main"', "refuses a dispatch started off main"), + ('--env "$DISPATCH_ENVIRONMENT"', "filters a dispatch to its environment"), + ): + if _needle not in _run: + bad(f"ci.yml's plan step no longer {_why} ({_needle!r} is gone)") + if "${{" in _run and "inputs." in _run: + bad("ci.yml's plan step interpolates inputs.* into its script; read them from env") + _env = _plan_step.get("env") or {} + if "inputs.component" not in str(_env.get("DISPATCH_COMPONENT", "")) \ + or "inputs.environment" not in str(_env.get("DISPATCH_ENVIRONMENT", "")): + bad("ci.yml's plan step must take DISPATCH_COMPONENT / DISPATCH_ENVIRONMENT from inputs in env") + +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/e2e.test.sh b/testing/e2e.test.sh new file mode 100644 index 0000000..956278d --- /dev/null +++ b/testing/e2e.test.sh @@ -0,0 +1,516 @@ +#!/usr/bin/env bash +# TIER 2 — the product a bootstrap produces builds, migrates, deploys (dry), +# serves, and chats: members, a moderator and an admin, through Supabase +# Auth, the Data API and the access-token hook. +# +# placement.test.sh proves the tree a bootstrap ends with is the right tree, +# and that its own plan converges in the right order. This proves it WORKS, +# by doing to it what its own pipelines will: +# +# 1. at the 01-product landing (the commit its PR merges), install with the +# lockfile the product ships, render the wrangler fixture (which must +# change nothing: the render is committed), typecheck, lint, test, build. +# The landing itself is checked in the build box with `orun validate` +# and `orun plan` alone (`checks: local`), its PR runs `plan` alone (an +# `orun/BASE-*` branch), and a product's pull-request lanes run none of +# these steps, so THIS is where a product those steps refuse is caught: +# before the tag, not after a build has merged it; +# 2. a Supabase project of its own, stood in for: a Postgres on a random +# port with Supabase's roles, its `auth` schema and the +# `supabase_realtime` publication (testing/lib/local-postgres.sh), and +# the endpoints this product calls on a project — Auth (GoTrue, which +# runs the project's access-token hook when one is configured), the +# Data API (PostgREST: filters, ordering, embedded authors, writes under +# row-level security), and the Management API's query and Auth-config +# endpoints the migration runner calls (testing/lib/fake-supabase-api.py); +# 3. the web lane's own steps for stage, rendered for a pull request (the +# verify profile carries deploy-dry-run; the deploy profile does not) and +# run in its staged job tree: install, `verify-app-structure` (the +# committed wrangler.jsonc must exist BEFORE the build, in a tree with no +# build output), `build-app` — which re-renders the config from the +# stage wiring document it is handed, as the deploy does, and inlines +# that project into the browser bundle — then `verify-build-output` and +# `deploy-dry-run`; +# 4. the built Worker under `wrangler dev`, with NO .dev.vars, over a +# project with NO schema yet: the component's OWN `smokeCommand`, +# verbatim, must REFUSE it — /api/health says the schema is missing; +# 5. the db-migrate lane's own steps for stage, rendered for the push that +# merges 01-product and run in its staged job tree: install, build +# @saas/db, apply — upstream's three SQL files, verbatim, and then the +# access-token hook switched on in the project's Auth config; applied +# again: nothing, the hook re-asserted; and the pull request's offline +# plan step; +# 6. the smoke again, now passing, and every route the product promises +# under the product's own name; then the chat as the browser drives it: +# a member, a moderator and an admin sign up with their roles in their +# sessions, the two starter channels and their messages with authors, a +# message posted and read back by somebody else, deletes allowed and +# refused by role, a channel added and removed, nothing at all for the +# bare publishable key, and the three tables in the Realtime publication +# with full row images. +# +# WHAT IS ONLY OFFLINE HERE. The browser is not driven: the pages run their +# Supabase calls client-side, and those calls — supabase-js, from the +# product's own installed copy, with the same arguments lib/Store.js and +# pages/_app.js use — are made from Node (testing/lib/chat-client.mjs). +# Realtime's websocket is not stood in for: the publication it streams is +# asserted instead. Supabase is a stand-in, faithful to the requests the app +# and the runner make and no further. The platform's half — create the +# repository, mint the brokered tokens, create a real Supabase project, read +# its keys, set its Auth, migrate and deploy for real and probe workers.dev — +# is a bootstrap against a workspace (BOOTSTRAP.md); the Terraform root is +# validated below when terraform is on PATH, never applied. +# +# Needs: orun, node, pnpm, python3 (+PyYAML), git, curl, psql and a +# PostgreSQL server install (initdb, pg_ctl), and the network for +# `pnpm install` (or a warm store). A few minutes: three installs, two builds. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" +# shellcheck source=lib/bootstrap.sh +source "$here/lib/bootstrap.sh" +# shellcheck source=lib/local-postgres.sh +source "$here/lib/local-postgres.sh" + +for bin in orun node pnpm python3 git curl psql; do + command -v "$bin" >/dev/null || { echo "e2e.test.sh needs $bin on PATH" >&2; exit 1; } +done +pg_bin >/dev/null || { echo "e2e.test.sh needs a PostgreSQL server install (initdb, pg_ctl)" >&2; exit 1; } + +scratch="$(mktemp -d)" +pgdir="$(mktemp -d)" +dev_pid="" +api_pid="" +# wrangler dev runs under pnpm, node and two workerd processes; a TERM to the +# first does not reach the rest, and waiting on it then never returns. So each +# server is started as its own process group (setsid) and the group stopped. +stop_group() { + local pid="$1" + [ -n "$pid" ] || return 0 + kill -TERM -- "-$pid" 2>/dev/null || true + for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 -- "-$pid" 2>/dev/null || break; sleep 0.5; done + kill -KILL -- "-$pid" 2>/dev/null || true +} +cleanup() { + stop_group "$dev_pid" + stop_group "$api_pid" + pg_down "$pgdir" + [ -n "$pgdir" ] && [ -d "$pgdir" ] && rm -rf "$pgdir" + [ -n "$scratch" ] && [ -d "$scratch" ] && rm -rf "$scratch" +} +trap cleanup EXIT +free_port() { python3 -c "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print(s.getsockname()[1]);s.close()"; } +values="$here/fixtures/acme.json" +repo="$(python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['reponame'])" "$values")" +export CI=1 WRANGLER_SEND_METRICS=false NEXT_TELEMETRY_DISABLED=1 TURBO_TELEMETRY_DISABLED=1 + +# The landing's own checks, step for step — what the product's Checks +# workflow ran on a pull request before the product carried ci.yml alone — +# run here at once on the whole tree. +LANDING_CHECKS=( + "pnpm install --frozen-lockfile" + "pnpm run wire:fixture" + "pnpm typecheck" + "pnpm lint" + "pnpm test" + "pnpm build" +) +checks() { # DIR LOG + local dir="$1" log="$2" cmd + for cmd in "${LANDING_CHECKS[@]}"; do + echo " \$ $cmd" | tee -a "$log" + if ! (cd "$dir" && bash -c "$cmd") >> "$log" 2>&1; then + echo "FAIL: \`$cmd\` failed in $dir" >&2; tail -40 "$log" >&2; return 1 + fi + done +} + +# One job of a plan, written out as the runner would run it: each `run:` step +# (the `use:` actions are setup-node and setup-pnpm, which this machine has) +# as a numbered script, the job's env, and the component path the steps run +# in. Steps are picked BY ID when given, else every `run:` step in order. +extract_job() { # PLAN JOB-ID OUT-DIR [STEP-ID…] + python3 - "$@" <<'PY' +import json, pathlib, sys +plan, jid, out, *want = sys.argv[1:] +job = next((j for j in json.load(open(plan))["jobs"] if j["id"] == jid), None) +if job is None: + sys.exit(f"the plan has no job {jid}") +out = pathlib.Path(out); out.mkdir(parents=True) +steps = [s for s in job["steps"] if s.get("run")] +if want: + by = {s["id"]: s for s in steps} + missing = [w for w in want if w not in by] + if missing: + sys.exit(f"{jid} has no step(s) {missing}") + steps = [by[w] for w in want] +for i, s in enumerate(steps): + (out / f"{i:02d}.sh").write_text(s["run"]) + (out / f"{i:02d}.id").write_text(s["id"]) +(out / "path").write_text(job.get("path") or ".") +with (out / "env").open("w") as f: + for k, v in (job.get("env") or {}).items(): + f.write(f"export {k}={json.dumps(v)}\n") +PY +} +run_job() { # STEPS-DIR WORK-TREE ENV LOG-PREFIX + local steps="$1" work="$2" envname="$3" logp="$4" s id + for s in "$steps"/[0-9][0-9].sh; do + id="$(cat "${s%.sh}.id")" + echo " ▸ $id" + if ! (cd "$work/$(cat "$steps/path")" && source "$steps/env" && export ORUN_ENVIRONMENT="$envname" \ + && bash -e "$s") > "$logp-$id.log" 2>&1; then + echo "FAIL: the lane's $id step" >&2; tail -40 "$logp-$id.log" >&2; return 1 + fi + done +} + +echo "── the offline bootstrap (testing/lib/bootstrap.sh)" +tree="$scratch/$repo" +bootstrap_offline "$root" "$tree" "$values" "$scratch/logs" > "$scratch/bootstrap.log" 2>&1 || { + echo "FAIL: the offline bootstrap stopped" >&2; tail -40 "$scratch/bootstrap.log" >&2; exit 1; } +echo " 2 phases placed and landed" + +# ── 1. the product's own pull request ────────────────────────────────────── +echo "── 01-product's landing: install, the fixture render, typecheck, lint, test, build" +s01="$(git -C "$tree" rev-parse HEAD~1)" +at01="$scratch/at-01/$repo" +git -C "$tree" worktree add -q "$at01" "$s01" +checks "$at01" "$scratch/checks.log" +dirty="$(git -C "$at01" status --porcelain)" +[ -z "$dirty" ] || { echo "FAIL: the checks changed tracked files — the committed wrangler.jsonc is not the fixture render:" >&2; echo "$dirty" >&2; exit 1; } +echo " the checks left the tree as committed (wire:fixture rendered the committed wrangler.jsonc)" + +# The Supabase root, as far as it goes without a cloud: formatted, and valid +# against the pinned providers its lock file names. +if command -v terraform >/dev/null; then + echo "── the product's supabase root: terraform fmt, init -backend=false, validate" + tfdir="$scratch/tf" + cp -r "$tree/infra/terraform/supabase/terraform" "$tfdir" + (cd "$tfdir" && terraform fmt -check -diff . && terraform init -backend=false -input=false \ + && terraform validate) > "$scratch/terraform.log" 2>&1 \ + || { echo "FAIL: the product's supabase root" >&2; tail -30 "$scratch/terraform.log" >&2; exit 1; } + cmp -s "$tfdir/.terraform.lock.hcl" "$tree/infra/terraform/supabase/terraform/.terraform.lock.hcl" \ + || { echo "FAIL: terraform init changed the committed lock file" >&2; exit 1; } + echo " formatted and valid; the committed lock file is what init resolves" +else + echo "── the product's supabase root: SKIPPED (no terraform on PATH)" +fi + +# ── 2. a Supabase project, stood in for ──────────────────────────────────── +echo "── a local Postgres with Supabase's roles, and the Supabase stand-in" +pgport="$(free_port)" +pgurl="$(pg_up "$pgdir" "$pgport")" || { echo "FAIL: Postgres did not start" >&2; exit 1; } +admin="postgres://supabase_admin@127.0.0.1:$pgport/postgres" +api_port="$(free_port)" +ref="localproject" +setsid python3 "$here/lib/fake-supabase-api.py" "$api_port" "$pgurl" --ref "$ref" --auth "$admin" \ + > "$scratch/api.log" 2>&1 < /dev/null & +api_pid=$! +for _ in $(seq 1 30); do grep -q '^anon-key ' "$scratch/api.log" 2>/dev/null && curl -s -o /dev/null "http://127.0.0.1:$api_port/" && break; sleep 0.3; done +anon="$(sed -n 's/^anon-key //p' "$scratch/api.log")" +[ -n "$anon" ] || { echo "FAIL: the Supabase stand-in did not start" >&2; cat "$scratch/api.log" >&2; exit 1; } +supabase_url="http://127.0.0.1:$api_port" +echo " $pgurl; the project on $supabase_url (no migration yet)" + +# The two plans the lanes below run from, each in the product's own tree: a +# push to main at the 01-product commit (the db-migrate lane's APPLY profile), +# and a pull request over the finished product against an empty base (the web +# lane's VERIFY profile, which carries deploy-dry-run, and db-migrate's PLAN). +(cd "$at01" && orun plan --intent intent.yaml --trigger github-push-main --env stage --output "$scratch/plan-main.json") > "$scratch/plan-main.log" 2>&1 \ + || { echo "FAIL: orun plan (push to main)" >&2; tail -15 "$scratch/plan-main.log" >&2; exit 1; } +git -C "$tree" worktree remove --force "$at01" +mkdir -p "$scratch/pr" +git clone -q "$tree" "$scratch/pr/$repo" +prtree="$scratch/pr/$repo" +git -C "$prtree" checkout -q --orphan empty +git -C "$prtree" rm -rqf . +git -C "$prtree" -c user.email=t@example.invalid -c user.name=t commit -qm empty --allow-empty +git -C "$prtree" checkout -q main +(cd "$prtree" && orun plan --intent intent.yaml --trigger github-pull-request --base empty --head HEAD --env stage \ + --output "$scratch/plan-pr.json") > "$scratch/plan-pr.log" 2>&1 \ + || { echo "FAIL: orun plan (pull request)" >&2; tail -15 "$scratch/plan-pr.log" >&2; exit 1; } +# This tier runs the bootstrap floor, newer than the orun the product's CI +# pins, and both read the per-edge `modeRules`: on a pull request — which +# applies and deploys nothing — the infrastructure edges that order a push to +# main are advisory, so no lane waits on another. (placement.test.sh checks +# the push to main's order.) +python3 - "$scratch/plan-pr.json" <<'PY' +import json, sys +jobs = {j["component"]: j for j in json.load(open(sys.argv[1]))["jobs"] if j["environment"] == "stage"} +chain = ["supabase", "db-migrate", "web"] +for a, b in zip(chain, chain[1:]): + ja, jb = jobs[a], jobs[b] + if ja["id"] in (jb.get("dependsOn") or []) or ja["id"] not in (jb.get("advisoryDependsOn") or []): + sys.exit(f"FAIL: on a pull request {b}@stage must name {a}@stage as advisory, not wait on it") +print(" pull request: " + " → ".join(chain) + ", every edge advisory") +PY + +# ── 3. the web lane's steps, for stage ───────────────────────────────────── +echo "── the stage web lane: install, verify-app-structure, build-app, verify-build-output, deploy-dry-run" +extract_job "$scratch/plan-pr.json" web.stage.verify-deploy "$scratch/steps-web" \ + install-workspace-dependencies verify-app-structure build-app verify-build-output deploy-dry-run +work="$prtree/.orun/runs/e2e/web.stage.verify-deploy/work" +# The job's private tree, staged as orun stages it — no build output, no +# node_modules: under stack-tectonic 0.19.0 the job installs inside it. +python3 "$here/lib/stage-job.py" "$prtree" "$work" +[ ! -e "$work/apps/web/.open-next" ] && [ -f "$work/apps/web/wrangler.jsonc" ] \ + || { echo "FAIL: the staged tree is not a fresh checkout with the committed wrangler.jsonc" >&2; exit 1; } +echo " staged: $(realpath --relative-to="$prtree" "$work") — no build output, the committed wrangler.jsonc" +# The stage wiring document, as the supabase apply publishes it and the lane +# resolves it (optionalSecretEnv WIRING_SUPABASE_STAGE): the stand-in's URL +# and its anon key. +export WIRING_SUPABASE_STAGE="{\"supabase_url\":\"$supabase_url\",\"supabase_anon_key\":\"$anon\"}" +run_job "$scratch/steps-web" "$work" stage "$scratch/web" +unset WIRING_SUPABASE_STAGE +grep -q "\"NEXT_PUBLIC_SUPABASE_URL\": \"$supabase_url\"" "$work/apps/web/wrangler.jsonc" \ + || { echo "FAIL: build-app did not re-render wrangler.jsonc from the stage wiring document" >&2; exit 1; } +[ "$(node -e 'const fs=require("fs");process.stdout.write(String(fs.readdirSync(process.argv[1]).length))' "$work/node_modules")" -gt 0 ] && [ ! -L "$work/node_modules" ] \ + || { echo "FAIL: the job's install did not land inside its own tree" >&2; exit 1; } +# `next build` inlined the SAME project into the browser bundle — not the +# committed fixture's. +grep -rqF "$supabase_url" "$work/apps/web/.open-next/assets/_next/static" \ + && ! grep -rqF "stage-project-ref.supabase.co" "$work/apps/web/.open-next/assets/_next/static" \ + || { echo "FAIL: the browser bundle does not carry the project the stage wiring names" >&2; exit 1; } +echo " the staged build ran inside its own tree; the Worker's vars and the browser bundle name the stage project it was handed" + +# ── 4. serve it, over a project with no schema ───────────────────────────── +echo "── wrangler dev over the built Worker, before any migration" +[ ! -e "$work/apps/web/.dev.vars" ] || { echo "FAIL: the staged tree carries a .dev.vars" >&2; exit 1; } +port="$(free_port)" +(cd "$work/apps/web" && exec setsid pnpm exec wrangler dev --config wrangler.jsonc --ip 127.0.0.1 --port "$port" \ + --name "$repo-web-stage" --show-interactive-dev-session=false) > "$scratch/dev.log" 2>&1 < /dev/null & +dev_pid=$! +url="http://127.0.0.1:$port" +for _ in $(seq 1 90); do + curl -s -o /dev/null "$url/" && break + kill -0 "$dev_pid" 2>/dev/null || { echo "FAIL: wrangler dev exited" >&2; tail -30 "$scratch/dev.log" >&2; exit 1; } + sleep 1 +done +curl -s -o /dev/null "$url/" || { echo "FAIL: wrangler dev never answered" >&2; tail -30 "$scratch/dev.log" >&2; exit 1; } +smoke="$(python3 -c "import yaml,sys;print(yaml.safe_load(open(sys.argv[1]))['spec']['parameters']['smokeCommand'])" "$tree/apps/web/component.yaml")" +if DEPLOYED_URL="$url" bash -c "$smoke" > /dev/null 2>&1; then + echo "FAIL: the deploy's smoke passed over a project with no schema — it proves nothing about the migrations" >&2; exit 1 +fi +before="$(curl -s -w ' %{http_code}' "$url/api/health")" +[ "$before" = '{"ok":false,"auth":"reachable","signup":"open","emailConfirmation":"off","schema":"not migrated"} 503' ] \ + || { echo "FAIL: /api/health before the migrations answered $before" >&2; exit 1; } +echo " the component's own smokeCommand refuses it: /api/health answers 503, schema not migrated" + +# ── 5. the db-migrate lane, in its staged job tree ───────────────────────── +echo "── the stage db-migrate lane: install, build @saas/db, apply — then apply again, and the PR's plan" +extract_job "$scratch/plan-main.json" db-migrate.stage.migrate "$scratch/steps-migrate" \ + install-dependencies build-db-package "Migration Apply" +extract_job "$scratch/plan-main.json" db-migrate.stage.migrate "$scratch/steps-migrate-again" "Migration Apply" +extract_job "$scratch/plan-pr.json" db-migrate.stage.migrate "$scratch/steps-migrate-plan" "Migration Plan" +# Staged from the fresh clone (a CI checkout: no build output, no +# node_modules); its migrations are the 01-product commit's, byte for byte. +mwork="$prtree/.orun/runs/e2e/db-migrate.stage.migrate/work" +python3 "$here/lib/stage-job.py" "$prtree" "$mwork" +# The component's secretEnv, as the lane resolves it: the supabase apply's +# published credentials and the brokered access token. SUPABASE_API_URL is +# the one value no lane has — it points the runner at the stand-in. +export SUPABASE_ACCESS_TOKEN=e2e-token SUPABASE_PROJECT_REF="$ref" SUPABASE_DB_PASSWORD=postgres \ + SUPABASE_DB_URL="$pgurl" SUPABASE_API_URL="$supabase_url" +hook_config() { curl -s -H "authorization: Bearer e2e-token" "$supabase_url/v1/projects/$ref/config/auth" \ + | python3 -c 'import json,sys;c=json.load(sys.stdin);print(c.get("hook_custom_access_token_enabled"), c.get("hook_custom_access_token_uri"))'; } +[ "$(hook_config)" = "False None" ] || { echo "FAIL: the project's Auth has a hook before any migration: $(hook_config)" >&2; exit 1; } +run_job "$scratch/steps-migrate" "$mwork" stage "$scratch/migrate" +result() { python3 -c "import json,sys;t=open(sys.argv[1]).read();r=json.loads(t[t.index('{'):t.rindex('}')+1]);print(' '.join(r['applied']), '|', ','.join((r.get('auth') or {}).get('configured') or []))" "$1"; } +want="000_control_baseline 010_init 020_auth_hook 030_seed | hook_custom_access_token_enabled,hook_custom_access_token_uri" +[ "$(result "$scratch/migrate-Migration Apply.log")" = "$want" ] \ + || { echo "FAIL: the first apply did '$(result "$scratch/migrate-Migration Apply.log")', not '$want'" >&2; exit 1; } +[ "$(hook_config)" = "True pg-functions://postgres/public/custom_access_token_hook" ] \ + || { echo "FAIL: the apply did not switch the access-token hook on: $(hook_config)" >&2; exit 1; } +echo " applied ${want%% |*}, then switched the access-token hook on" +run_job "$scratch/steps-migrate-again" "$mwork" stage "$scratch/migrate-again" +again="| hook_custom_access_token_enabled,hook_custom_access_token_uri" +[ "$(result "$scratch/migrate-again-Migration Apply.log")" = " $again" ] \ + || { echo "FAIL: a second apply did '$(result "$scratch/migrate-again-Migration Apply.log")'" >&2; exit 1; } +echo " a second apply applied nothing and re-asserted the hook (the ledger holds $(psql "$pgurl" -XAtc 'select count(*) from _migrations.applied') migrations)" +run_job "$scratch/steps-migrate-plan" "$mwork" stage "$scratch/migrate-plan" +[ "$(result "$scratch/migrate-plan-Migration Plan.log")" = "${want%% |*} | " ] \ + || { echo "FAIL: the pull request's offline plan did '$(result "$scratch/migrate-plan-Migration Plan.log")'" >&2; exit 1; } +echo " the pull request's plan step verifies every migration's checksum offline and touches no Auth" +unset SUPABASE_ACCESS_TOKEN SUPABASE_PROJECT_REF SUPABASE_DB_PASSWORD SUPABASE_DB_URL SUPABASE_API_URL +rm -rf "$mwork" + +# ── 6. the product, migrated ─────────────────────────────────────────────── +echo "── the migrated product" +echo " ▸ the component's own smokeCommand, DEPLOYED_URL=$url" +DEPLOYED_URL="$url" bash -c "$smoke" || { echo "FAIL: the deploy's smoke refused the migrated product" >&2; tail -20 "$scratch/dev.log" >&2; exit 1; } + +echo " ▸ every route the product promises; the chat, as members, a moderator and an admin" +python3 - "$url" "$values" "$supabase_url" "$anon" "$work/apps/web" "$here/lib/chat-client.mjs" "$pgurl" <<'PY' \ + || { echo "FAIL: the routes or the chat; wrangler dev said:" >&2; tail -40 "$scratch/dev.log" >&2; exit 1; } +import html, http.client, json, re, subprocess, sys, time, urllib.error, urllib.request +base, values, supabase, anon, app, client, pgurl = sys.argv[1], json.load(open(sys.argv[2])), *sys.argv[3:] +name = values["productname"] +problems = [] +def bad(m): problems.append(m) + +def req(path, headers=None): + # A GET whose CONNECTION drops (not one that answers an error) is asked + # again, twice at most, and says so: `wrangler dev` on a loaded machine + # has dropped one. + for attempt in range(3): + r = urllib.request.Request(base + path, headers=headers or {}) + try: + with urllib.request.urlopen(r, timeout=60) as resp: + return resp.status, resp.headers, resp.read().decode("utf-8", "replace") + except urllib.error.HTTPError as e: + return e.code, e.headers, e.read().decode("utf-8", "replace") + except (http.client.RemoteDisconnected, ConnectionResetError) as e: + if attempt == 2: + raise + print(f" (GET {path}: the connection dropped ({e.__class__.__name__}) — asking again)") + time.sleep(1) +def text(page): + # React separates adjacent text with `<!-- -->`: drop those, then tags. + return html.unescape(re.sub(r"<[^>]+>", " ", re.sub(r"<!--.*?-->", "", page, flags=re.S))) +def title(page): + # next/head marks what it renders: `<title data-next-head="">`. + m = re.search(r"<title[^>]*>(.*?)", page, re.S) + return m and html.unescape(m.group(1)) +def chat(*args): + out = subprocess.run(["node", client, app, supabase, anon, *args], capture_output=True, text=True) + if out.returncode != 0: + raise SystemExit(f"chat-client {args[0]} failed: {out.stderr.strip()[-400:]}") + return json.loads(out.stdout) +def psql(sql): + out = subprocess.run(["psql", pgurl, "-X", "-q", "-At", "-v", "ON_ERROR_STOP=1", "-c", sql], + capture_output=True, text=True) + if out.returncode != 0: + raise SystemExit(f"psql: {out.stderr.strip()[:300]}") + return out.stdout.strip() + +# ── the pages, under the product's own name ─────────────────────────────── +s, _, home = req("/") +if s != 200: + bad(f"/ answered {s}") +if title(home) != name: + bad(f"the sign-in page's is {title(home)!r}, not {name!r}") +h1 = re.search(r"<h1[^>]*>(.*?)</h1>", home, re.S) +if not h1 or html.unescape(re.sub(r"<!--.*?-->", "", h1.group(1))).strip() != name: + bad(f"the sign-in page's heading is {h1 and h1.group(1)!r}, not {name!r}") +for want in ('type="password"', "Sign up", "Login"): + if want not in home: + bad(f"the sign-in page has no {want!r}") +if "Slack Clone" in text(home) and "Slack Clone" not in name: + bad("the sign-in page still carries the baseline's name") +s, _, page = req("/channels/1") +if s != 200 or title(page) != name: + bad(f"/channels/1 answered {s} titled {title(page)!r}") +s, _, _ = req("/no-such-page") +if s != 404: + bad(f"/no-such-page answered {s}, not 404") +s, h, body = req("/api/health") +if s != 200 or json.loads(body) != {"ok": True, "auth": "reachable", "signup": "open", + "emailConfirmation": "off", "schema": "migrated"} \ + or h.get("cache-control") != "no-store": + bad(f"/api/health answered {s} {body} ({h.get('cache-control')})") + +# ── sign-up: every user a member, the plus-addresses their roles ────────── +pw = "correct horse battery" +sam, kim, lee = "sam@chat.example", "kim+supamod@chat.example", "lee+supaadmin@chat.example" +want_roles = {sam: None, kim: "moderator", lee: "admin"} +ids = {} +for email, role in want_roles.items(): + up = chat("signup", email, pw) + if not up["ok"] or up["userRole"] != role: + bad(f"sign-up of {email} gave {up} — its session must carry user_role {role!r}") + ids[email] = up.get("user") +wrong = chat("signin", sam, "not the password") +if wrong["ok"] or wrong["code"] != "invalid_credentials": + bad(f"a wrong password was not refused: {wrong}") +again = chat("signin", kim, pw) +if not again["ok"] or again["userRole"] != "moderator": + bad(f"kim signed in again without her role: {again}") + +# ── the starter channels, their messages and their authors ─────────────── +ch = chat("channels", sam, pw) +if not ch["ok"] or sorted(c["slug"] for c in ch["rows"]) != ["public", "random"]: + bad(f"sam sees channels {ch.get('rows')}, not #public and #random") +public = next((c["id"] for c in ch.get("rows") or [] if c["slug"] == "public"), None) +msgs = chat("messages", sam, pw, str(public)) +first = (msgs.get("rows") or [{}])[0] +if not msgs["ok"] or first.get("message") != "Hello World 👋" \ + or (first.get("author") or {}).get("username") != "supabot+supaadmin@example.com": + bad(f"#public's first message is {first}, not the seed's, with its author") +seed_id = first.get("id") + +# ── a message, posted by one member and read by another ────────────────── +post = chat("post", sam, pw, str(public), "hello from sam") +mine = (post.get("rows") or [{}])[0] +if not post["ok"] or mine.get("user_id") != ids[sam]: + bad(f"sam's message did not post as sam: {post}") +seen = chat("messages", kim, pw, str(public)) +last = (seen.get("rows") or [{}])[-1] +if last.get("message") != "hello from sam" or (last.get("author") or {}).get("username") != sam: + bad(f"kim reads #public's last message as {last}, not sam's, by sam") +# …and nobody posts as somebody else: the insert policy is auth.uid(). +as_sam = (f"SET ROLE authenticated; SELECT set_config('request.jwt.claims', " + f"'{{\"sub\":\"{ids[sam]}\",\"role\":\"authenticated\"}}', false);") +w = subprocess.run(["psql", pgurl, "-X", "-q", "-At", "-c", + f"{as_sam} INSERT INTO public.messages (message, channel_id, user_id) " + f"VALUES ('as kim', {int(public)}, '{ids[kim]}')"], capture_output=True, text=True) +if "row-level security" not in w.stderr: + bad(f"sam posted as kim, or was refused for another reason: {w.stderr.strip()[:160]}") +def exists(mid): + return psql(f"select count(*) from public.messages where id = {int(mid)}") == "1" + +# ── deletes, by role ────────────────────────────────────────────────────── +chat("delete-message", sam, pw, str(seed_id)) +if not exists(seed_id): + bad("a member deleted somebody else's message") +chat("delete-message", sam, pw, str(mine["id"])) +if exists(mine["id"]): + bad("a member could not delete their own message") +other = (chat("post", sam, pw, str(public), "moderate me")["rows"] or [{}])[0] +chat("delete-message", kim, pw, str(other["id"])) +if exists(other["id"]): + bad("a moderator could not delete a member's message") +added = chat("add-channel", sam, pw, "sams-room") +room = (added.get("rows") or [{}])[0] +if not added["ok"] or room.get("created_by") != ids[sam]: + bad(f"sam could not add a channel: {added}") +def channel(cid): + return psql(f"select count(*) from public.channels where id = {int(cid)}") == "1" +chat("delete-channel", kim, pw, str(room["id"])) +if not channel(room["id"]): + bad("a moderator deleted a channel — only its creator and admins may") +chat("delete-channel", lee, pw, str(room["id"])) +if channel(room["id"]): + bad("an admin could not delete a member's channel") +chat("delete-channel", sam, pw, str(public)) +if not channel(public): + bad("a member deleted #public") + +# ── the bare publishable key reads nothing ──────────────────────────────── +for table in ("channels", "messages", "users", "user_roles"): + r = chat("anon", table) + if r.get("rows"): + bad(f"anon reads {table}: {r['rows'][:2]}") + +# ── what Realtime streams ───────────────────────────────────────────────── +pub = psql("select string_agg(tablename, ',' order by tablename) from pg_publication_tables " + "where pubname = 'supabase_realtime'") +if pub != "channels,messages,users": + bad(f"the supabase_realtime publication carries {pub!r}, not channels, messages and users") +full = psql("select string_agg(relname || '=' || relreplident::text, ',' order by relname) from pg_class " + "where relnamespace = 'public'::regnamespace and relname in ('channels','messages','users')") +if full != "channels=f,messages=f,users=f": + bad(f"the streamed tables' replica identity is {full!r}, not full (a delete must carry its row)") + +if problems: + for p in problems: + print(f" ✕ {p}", file=sys.stderr) + sys.exit(1) +print(f" /, /channels/1 and a 404, titled {name!r}; /api/health ok; a member, a moderator and an " + f"admin signed up with their roles in their sessions; #public and #random with the seed's " + f"messages and authors; a message posted and read back by somebody else; deletes allowed " + f"and refused by role; a channel added and removed; nothing for the bare publishable key; " + f"three tables streamed with full row images") +PY + +echo "e2e.test.sh: ok" diff --git a/testing/fixtures/acme.json b/testing/fixtures/acme.json new file mode 100644 index 0000000..df7a889 --- /dev/null +++ b/testing/fixtures/acme.json @@ -0,0 +1,23 @@ +{ + "_comment": [ + "The inputs the placement, leak and e2e gates render with. 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 product name with an apostrophe and an", + "ampersand (both legal in the card's pattern, both special in TypeScript", + "strings, HTML and a PR title), a hyphenated repo slug that CONTAINS the", + "word `slack`, an owner other than the baseline's, and NO domain — a", + "console build asks for none, so the placeholder <reponame>.example.com", + "is what a product is born with — 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-slack", + "productname": "Sam's Chat & Co", + "githuborg": "acme-inc", + "subdomain": "acme", + "orunWorkspace": "ws_0000000000000000000000000000000f", + "epicSlug": "team-chat-baselining" +} diff --git a/testing/fixtures/baseline-identity.supabase-slack-clone.json b/testing/fixtures/baseline-identity.supabase-slack-clone.json new file mode 100644 index 0000000..3fecba9 --- /dev/null +++ b/testing/fixtures/baseline-identity.supabase-slack-clone.json @@ -0,0 +1,9 @@ +{ + "_comment": "THE IDENTITY testing/rebrand.test.sh PINS ITS FIXTURES TO. That suite tests the rename ENGINE, and its fixtures spell this baseline's identity out literally; passed as --baseline-identity, a later change to .baseline/identity.json (a baseline promoted under a new name) cannot silently turn every case into a comparison against the wrong FROM side.", + "slug": "supabase-slack-clone", + "pascal": "SupabaseSlackClone", + "productName": "Slack Clone", + "domain": "supabase-slack-clone.example.com", + "subdomain": "your-workers-subdomain", + "githubOwner": "sourceplane" +} diff --git a/testing/leak.test.sh b/testing/leak.test.sh new file mode 100755 index 0000000..d86abf2 --- /dev/null +++ b/testing/leak.test.sh @@ -0,0 +1,188 @@ +#!/usr/bin/env bash +# THE LEAK GATE — what a product carries, and what stays in the factory. +# +# A product built from this baseline is somebody's team chat, not a copy of +# this repository. It gets the product: the app, the Terraform root, the +# migrations, the tests, its CI, its tooling, its README, its AGENTS.md and +# its two context pages. It does NOT get the factory: the blueprints, the bootstrap and +# rebrand tooling, the test gates, the task contracts and identity under +# `.baseline/`, this repository's own epic and task tree, or BOOTSTRAP.md — +# and no file it does get may NAME one of those paths, because in the +# product they point at nothing. +# +# This asks orun to DERIVE the placement — every file every phase would write +# — and gates that set, then reads every shipped file's source. Derivation +# runs no hooks, contacts nothing and writes nothing. +# testing/placement.test.sh gates the same rules over a tree that is actually +# placed and branded. +# +# Needs: orun + python3 (+PyYAML) + node. 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" +sets=() +while IFS=$'\t' read -r k v; do sets+=( --set "$k=$v" ); done < <( + python3 - "$here/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 +) +orun new --blueprint "$root/repo-blueprint.yaml" --status --json \ + --out "$scratch/empty" "${sets[@]}" > "$scratch/status.json" + +# intent.yaml ships with this repository's `work:` block, and the bootstrap +# strips it before the first landing (work-tree.mjs). Read the intent the +# product actually gets. +cp "$root/intent.yaml" "$scratch/intent.yaml" +node "$root/tooling/bootstrap/work-tree.mjs" --strip --file "$scratch/intent.yaml" >/dev/null + +python3 - "$scratch/status.json" "$root" "$scratch/intent.yaml" <<'PY' +import json, pathlib, re, sys +import yaml + +status = json.load(open(sys.argv[1])) +root = pathlib.Path(sys.argv[2]) +stripped_intent = pathlib.Path(sys.argv[3]) +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) < 100: + sys.exit(f"only {len(placed)} files derived — the tree is not a product") + +# ── the context pack, exactly ───────────────────────────────────────────── +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 ─────────────────────────────────────────────── +NEVER = (".baseline/", "specs/", "tasks/", "testing/", "hooks/", "docs/phases/", + "tooling/rebrand/", "tooling/bootstrap/", ".github/workflows/baseline.yml", + ".github/workflows/tag.yml", "BOOTSTRAP.md", "repo-blueprint.yaml", + "blueprint.yaml", "flows/", "agents/") +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") + +# ── nothing local and nothing built ─────────────────────────────────────── +# `.env.example` and `.dev.vars.example` ship (they document the keys); a +# real `.env` or `.dev.vars` of any other name — a `.local` override, a +# per-mode `.env.production`, a per-environment `.dev.vars.stage` — never +# does, nor Terraform state, nor Python bytecode. +LOCAL = re.compile(r"(^|/)(\.env(\.(?!example$)[^/]+)?|\.dev\.vars(\.(?!example$)[^/]+)?|node_modules|\.next|" + r"\.open-next|\.wrangler|\.turbo|\.orun|\.terraform|[^/]*\.tfstate(\.[^/]+)?|" + r"next-env\.d\.ts|[^/]*\.tsbuildinfo|dist|__pycache__|[^/]*\.pyc)(/|$)") +for p in placed: + if LOCAL.search(p): + bad(f"{p} would ship — a local or built file of whoever ran the bootstrap") + +# ── what a product cannot run without ───────────────────────────────────── +if "README.md" not in placed: + bad("README.md would not ship") +# The build's last screen tells the owner to point a coding agent at the +# repository; this is what the agent reads first. +if "AGENTS.md" not in placed: + bad("AGENTS.md would not ship — a coding agent starts there") +MUST = ( + ".github/workflows/ci.yml", ".rebrand/values.json", + "apps/web/component.yaml", "apps/web/lib/site.ts", "apps/web/lib/Store.js", + "apps/web/LICENSE", + # The build reads the Supabase project from the wrangler config: + "apps/web/next.config.ts", + # COMMITTED, because the composition checks it exists before the build: + "apps/web/wrangler.jsonc", "apps/web/wrangler.template.jsonc", "apps/web/wiring.fixture.json", + "apps/web/pages/api/health.ts", "apps/web/pages/channels/[id].js", + "apps/web/.env.example", "apps/web/.dev.vars.example", + "infra/terraform/supabase/component.yaml", "infra/terraform/supabase/terraform/main.tf", + "infra/terraform/supabase/terraform/adopt.tf", + "infra/terraform/supabase/terraform/.terraform.lock.hcl", + "infra/db-migrate/component.yaml", + "packages/db/src/manifest.ts", "packages/db/src/auth-config.ts", + "packages/db/src/migrations/010_init/up.sql", + "packages/db/src/migrations/020_auth_hook/up.sql", + "packages/db/src/migrations/030_seed/up.sql", + "tooling/wire/live.mjs", "tooling/wire/render.mjs", "tooling/migrations/manifest.mjs", + "tests/web/component.yaml", "tests/db/component.yaml", +) +for must in MUST: + if must not in placed: + bad(f"{must} would not ship, and a product needs it") + +# ── every shipped file, read for the factory's paths ────────────────────── +# A file that ships naming `testing/`, `.baseline/` or `repo-blueprint` +# points the product's reader — or its CI — at something it does not have. +# Each placed path is mapped back to the source its module copies from. +bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text()) +copies = [(m["to"].rstrip("/"), m["from"].rstrip("/")) for m in bp.get("modules") or [] + if m.get("mode") == "copy"] +def source_of(dest): + for to, frm in sorted(copies, key=lambda c: -len(c[0])): + if dest == to: + return root / frm + if dest.startswith(to + "/"): + return root / frm / dest[len(to) + 1:] + return None +FACTORY_PATH = re.compile(r"repo-blueprint|(?<![\w./-])(?:testing|specs|tasks|\.baseline|docs/phases)/" + r"|BOOTSTRAP\.md|tooling/(?:rebrand|bootstrap)\b") +scanned = 0 +for p in placed: + src = stripped_intent if p == "intent.yaml" else source_of(p) + if src is None or not src.is_file(): + continue + try: + text = src.read_text() + except UnicodeDecodeError: + continue + scanned += 1 + for n, line in enumerate(text.splitlines(), 1): + m = FACTORY_PATH.search(line) + if m: + bad(f"{p}:{n} names the factory's {m.group(0)!r}, which the product does not have: {line.strip()[:80]}") + +# ── PROVENANCE, which rebrand has no rule for ───────────────────────────── +# Not a search for this baseline's name: the rebrand rewrites that, and this +# gate reads the sources before it runs. What the rebrand cannot rewrite is a +# sentence about where the product CAME FROM, or one about being a baseline. +PROVENANCE = re.compile( + r"\bfork(ed)? (of|from)\b|\bbaseline (repo|repository|commit|tag)\b|\bthis baseline\b" + r"|BOOTSTRAP\.md|repo-blueprint|specs/epics|\.baseline/", + re.I, +) +SOURCES = {"README.md": ".baseline/product/README.md", + "AGENTS.md": ".baseline/product/AGENTS.md", + "ai/context/operations.md": "ai/context/operations.md", + "ai/context/deployment.md": "ai/context/deployment.md", + "apps/web/README.md": "apps/web/README.md"} +for shipped, src in SOURCES.items(): + for n, line in enumerate((root / src).read_text(errors="replace").splitlines(), 1): + if PROVENANCE.search(line): + bad(f"{shipped} (from {src}:{n}) tells the product about the factory: {line.strip()[:80]}") + +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; {scanned} text files read") +print(f" ai/context is exactly {len(ALLOWED_AI)} declared file(s); none of the " + f"{len(NEVER)} factory paths ships or is named by a shipped file; nothing local or " + f"built; no provenance prose") +PY + +echo "leak.test.sh: ok" diff --git a/testing/lib/bootstrap.sh b/testing/lib/bootstrap.sh new file mode 100755 index 0000000..9ecb534 --- /dev/null +++ b/testing/lib/bootstrap.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# The offline bootstrap: every phase of repo-blueprint.yaml, placed by orun and +# finished by the blueprint's own `run:` hooks, in order, the way a real +# `orun new --run-hooks --resume` takes a product from nothing to its last +# landing — minus the platform. Sourced by placement.test.sh and e2e.test.sh. +# +# bootstrap_offline <root> <tree> <values.json> <log-dir> [until-phase] +# +# What stands in for the platform: +# - the typed actions (`uses:` — task, repo, reconcile, land, watch, probe) +# are skipped; a landing becomes a commit on `main`, which is what the +# next phase's placement sees on the real thing too; +# - `link` (a `run:` hook that calls `orun cloud`) is skipped — it needs a +# workspace; +# - `{{ .inputs.* }}` render from the fixture. +# Everything else — the retouch marker, the rebrand, the re-tenant, the +# work-tree strip, the deferrals and their restore, the deployment-docs +# render — runs exactly as declared. +# +# The output directory starts EMPTY, as a real one does: no discovery root is +# made here, so a phase that leaves orun's repo-scale gate one to find (apps/, +# infra/, packages/, tests/) fails here as it would live. +# +# Needs: orun, node, pnpm, python3 (+PyYAML), git. + +bootstrap_offline() { + local root="$1" tree="$2" values="$3" logs="$4" until="${5:-}" + local sets=() k v phase + while IFS=$'\t' read -r k v; do sets+=( --set "$k=$v" ); done < <( + python3 - "$values" <<'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 + ) + mkdir -p "$tree" "$logs" + + for phase in $(python3 -c "import yaml,sys;print(' '.join(p['name'] for p in yaml.safe_load(open(sys.argv[1]))['phases']))" "$root/repo-blueprint.yaml"); do + echo "── $phase: place" + if ! orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" --phase "$phase" \ + "${sets[@]}" > "$logs/place-$phase.log" 2>&1; then + echo "FAIL: $phase did not place" >&2; tail -20 "$logs/place-$phase.log" >&2; return 1 + fi + echo "── $phase: post hooks" + if ! python3 "$root/testing/lib/run-hooks.py" "$root/repo-blueprint.yaml" "$phase" post \ + "$tree" "$root" "$values" --skip link > "$logs/hooks-$phase.log" 2>&1; then + echo "FAIL: $phase's post hooks" >&2; tail -30 "$logs/hooks-$phase.log" >&2; return 1 + fi + sed 's/^/ /' "$logs/hooks-$phase.log" + # The landing: what the PR merges is what the next phase is placed onto. + ( + cd "$tree" + git config user.email bootstrap@example.invalid + git config user.name "offline bootstrap" + git checkout -q -B main 2>/dev/null || true + git add -A + git commit -q -m "land $phase" --allow-empty + ) || { echo "FAIL: $phase did not commit" >&2; return 1; } + [ "$phase" = "$until" ] && break + done + return 0 +} diff --git a/testing/lib/chat-client.mjs b/testing/lib/chat-client.mjs new file mode 100644 index 0000000..e335ea7 --- /dev/null +++ b/testing/lib/chat-client.mjs @@ -0,0 +1,88 @@ +#!/usr/bin/env node +// The browser's half of the chat, for the e2e. +// +// chat-client.mjs <app-dir> <supabase-url> <anon-key> <action> [args…] +// +// signup <email> <password> pages/index.js's "Sign up" +// signin <email> <password> its "Login" +// channels <email> <password> lib/Store.js fetchChannels +// messages <email> <password> <channel> fetchMessages (with each author) +// post <email> <password> <channel> <text> addMessage +// delete-message <email> <password> <id> deleteMessage +// add-channel <email> <password> <slug> addChannel +// delete-channel <email> <password> <id> deleteChannel +// anon <table> a read with the bare publishable key +// +// The pages render in the browser and their JavaScript, which this suite does +// not drive, calls supabase-js. So this makes the same calls with the same +// arguments as lib/Store.js and pages/_app.js do, from the product's OWN +// installed @supabase/supabase-js (resolved from <app-dir>, the staged job +// tree), signed in first as the given user — and decodes the access token the +// way _app.js does, so `userRole` is the `user_role` claim the access-token +// hook added. +// +// Prints one JSON object: { ok, userRole, code, message, rows }. +import { createRequire } from "node:module"; +import * as path from "node:path"; + +const [appDir, url, key, action, ...args] = process.argv.slice(2); +const require = createRequire(path.join(path.resolve(appDir), "package.json")); +const { createClient } = require("@supabase/supabase-js"); + +const supabase = createClient(url, key, { auth: { persistSession: false, autoRefreshToken: false } }); + +function claimsOf(token) { + const body = token.split(".")[1]; + return JSON.parse(Buffer.from(body, "base64url").toString("utf8")); +} + +async function signIn(email, password) { + const { data, error } = await supabase.auth.signInWithPassword({ email, password }); + if (error) throw Object.assign(new Error(error.message), { code: error.code ?? String(error.status) }); + return data.session; +} + +const out = { ok: true }; +try { + if (action === "signup" || action === "signin") { + const [email, password] = args; + const { data, error } = + action === "signup" + ? await supabase.auth.signUp({ email, password }) + : await supabase.auth.signInWithPassword({ email, password }); + if (error) throw Object.assign(new Error(error.message), { code: error.code ?? String(error.status) }); + out.user = data.user?.id ?? null; + out.userRole = data.session ? (claimsOf(data.session.access_token).user_role ?? null) : null; + } else if (action === "anon") { + const { data, error } = await supabase.from(args[0]).select("*"); + if (error) throw Object.assign(new Error(error.message), { code: error.code }); + out.rows = data; + } else { + const [email, password, ...rest] = args; + const session = await signIn(email, password); + out.user = session.user.id; + out.userRole = claimsOf(session.access_token).user_role ?? null; + let res; + if (action === "channels") res = await supabase.from("channels").select("*"); + else if (action === "messages") + res = await supabase + .from("messages") + .select(`*, author:user_id(*)`) + .eq("channel_id", rest[0]) + .order("inserted_at", { ascending: true }); + else if (action === "post") + res = await supabase.from("messages").insert([{ message: rest[1], channel_id: rest[0], user_id: session.user.id }]).select(); + else if (action === "delete-message") res = await supabase.from("messages").delete().match({ id: rest[0] }); + else if (action === "add-channel") + res = await supabase.from("channels").insert([{ slug: rest[0], created_by: session.user.id }]).select(); + else if (action === "delete-channel") res = await supabase.from("channels").delete().match({ id: rest[0] }); + else throw new Error(`unknown action ${action}`); + if (res.error) throw Object.assign(new Error(res.error.message), { code: res.error.code }); + out.rows = res.data; + } +} catch (error) { + out.ok = false; + out.code = error.code ?? null; + out.message = error.message; +} +process.stdout.write(JSON.stringify(out) + "\n"); diff --git a/testing/lib/fake-supabase-api.py b/testing/lib/fake-supabase-api.py new file mode 100755 index 0000000..80b2ce4 --- /dev/null +++ b/testing/lib/fake-supabase-api.py @@ -0,0 +1,820 @@ +#!/usr/bin/env python3 +"""A stand-in for the Supabase endpoints this product touches, over a local +Postgres (testing/lib/local-postgres.sh). + + fake-supabase-api.py <port> <postgres-url> [--ref <project-ref>] + [--auth <superuser-url>] [--confirm-email] + +Without `--auth` it is the Management API endpoints the migration runner +uses, + + POST /v1/projects/<ref>/database/query {"query": "<sql>"} + GET|PATCH /v1/projects/<ref>/config/auth the project's Auth settings — the + runner PATCHes the access-token + hook on after the migrations + +which hands the SQL to `psql` as the `postgres` role and answers the rows of +the last statement as a JSON array, an error as a non-2xx JSON `message` +carrying Postgres's own text. Only the bearer token's presence is checked. + +`--auth <superuser-url>` adds what a PROJECT has before any migration runs and +what it answers on its own URL, as far as this app reaches it: + + the schemas Supabase creates itself, through the superuser URL: `auth` + (`auth.users`, `auth.uid()`, `auth.role()`, `auth.jwt()`) and + `storage` (`buckets`, `objects`, row-level security on), with + the grants the template's migration needs from `postgres` — a + foreign key to and a trigger on `auth.users`, a row in + `storage.buckets`, policies on `storage.objects` (owned by + `supabase_storage_admin`, which `postgres` is a member of) — + so the migration means here what it means there; + the access-token hook, as Auth runs it: once config/auth has + hook_custom_access_token_enabled and a pg-functions:// URI, every + access token /token and /signup issue is the hook function's + answer, called as `supabase_auth_admin` with Auth's event + ({user_id, claims, authentication_method}) — and a hook that + fails fails the sign-in with 500 `unexpected_failure`, as Auth's + does; + /auth/v1/* a GoTrue stand-in — settings, signup, token (password and + refresh_token grants), user (GET, PUT), logout, recover, + verify (token_hash), health, and the admin API's + GET/DELETE /admin/users/<id> (service role only; a soft delete + keeps the row, obfuscated, and the user can no longer sign + in). Users are rows in `auth.users` of the same database, so + the migration's trigger writes their profile as Supabase's + would. Access tokens are HS256 JWTs with no `kid`, so + supabase-js checks each one by calling GET /auth/v1/user — the + path the app's safeGetSession() takes. Every /auth/v1 call must + carry one of the project's API keys (`apikey`), as Supabase's + gateway requires; + /rest/v1/<table> + a PostgREST stand-in for the calls the app's supabase-js makes: + GET and HEAD (`select` of `*`, a column list or a many-to-one + embed `alias:fk_column(*)` resolved through the foreign key, + `eq`/`neq`/`is` + filters, `order`, `limit`, `Prefer: count=exact` answered in + Content-Range, `.single()`'s object Accept — one row or 406 + PGRST116), POST (insert; `resolution=merge-duplicates` upsert on + the primary key or `on_conflict`; `return=representation` or + minimal), PATCH (update) and DELETE, filtered the same way. The + request's JWT (the user's, the anon key or the service-role + key) becomes `SET LOCAL ROLE` and `request.jwt.claims`, exactly + what PostgREST does, so row-level security decides — and the + service role, BYPASSRLS as on Supabase, sees everything. + +The keys are printed on stdout at startup as `anon-key <jwt>` and +`service-role-key <jwt>`. Email is never sent: what Supabase would mail is +kept, and GET /__fake/outbox reads it back. POST /__fake/config with +{"mailer_autoconfirm": bool, "email_allowed": [..] | null} switches whether +sign-up confirms at once (the default unless --confirm-email, as the +product's Terraform sets it), and models the built-in SMTP's members-only +rule (anyone else gets 400 `email_address_not_authorized`). +""" +import base64 +import hashlib +import hmac +import http.server +import json +import re +import secrets +import subprocess +import sys +import threading +import time +import urllib.parse +import uuid + +PORT = int(sys.argv[1]) +DB = sys.argv[2] +REF = sys.argv[sys.argv.index("--ref") + 1] if "--ref" in sys.argv else None +ADMIN = sys.argv[sys.argv.index("--auth") + 1] if "--auth" in sys.argv else None +ROUTE = re.compile(r"^/v1/projects/([a-z0-9]+)/database/query$") +AUTH_CONFIG_ROUTE = re.compile(r"^/v1/projects/([a-z0-9]+)/config/auth$") +HOOK_URI = re.compile(r"^pg-functions://postgres/([a-z_][a-z0-9_]*)/([a-z_][a-z0-9_]*)$") +NAME = re.compile(r"^[a-z_][a-z0-9_]*$") +JWT_SECRET = secrets.token_hex(32).encode() +BASE = f"http://127.0.0.1:{PORT}" +CONFIG = {"mailer_autoconfirm": "--confirm-email" not in sys.argv, "email_allowed": None} +# The project's Auth config as the Management API keeps it (config/auth). +AUTH_CONFIG = {"hook_custom_access_token_enabled": False, "hook_custom_access_token_uri": None, + "mailer_autoconfirm": CONFIG["mailer_autoconfirm"]} +OUTBOX: list = [] +REFRESH: dict = {} +LOCK = threading.Lock() + + +def psql(sql: str, url: str = DB, **params) -> subprocess.CompletedProcess: + argv = ["psql", url, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"] + for k, v in params.items(): + argv += ["-v", f"{k}={v}"] + return subprocess.run(argv, input=sql, capture_output=True, text=True) + + +def b64(data: bytes) -> str: + return base64.urlsafe_b64encode(data).rstrip(b"=").decode() + + +def jwt_encode(claims: dict) -> str: + head = b64(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode()) + body = b64(json.dumps(claims, separators=(",", ":")).encode()) + sig = hmac.new(JWT_SECRET, f"{head}.{body}".encode(), hashlib.sha256).digest() + return f"{head}.{body}.{b64(sig)}" + + +def jwt_decode(token: str): + try: + head, body, sig = token.split(".") + want = hmac.new(JWT_SECRET, f"{head}.{body}".encode(), hashlib.sha256).digest() + if not hmac.compare_digest(b64(want), sig): + return None + claims = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4))) + return claims if claims.get("exp", 0) > time.time() else None + except Exception: + return None + + +def api_key(role: str) -> str: + now = int(time.time()) + return jwt_encode({"iss": "supabase-demo", "role": role, "iat": now, "exp": now + 10 * 365 * 86400}) + + +ANON_KEY = api_key("anon") +SERVICE_KEY = api_key("service_role") + +PROJECT_SCHEMAS = """ +CREATE SCHEMA IF NOT EXISTS auth; +CREATE TABLE IF NOT EXISTS auth.users ( + id uuid PRIMARY KEY, + email text UNIQUE NOT NULL, + encrypted_password text, + email_confirmed_at timestamptz, + raw_user_meta_data jsonb NOT NULL DEFAULT '{}', + last_sign_in_at timestamptz, + deleted_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); +CREATE OR REPLACE FUNCTION auth.uid() RETURNS uuid LANGUAGE sql STABLE AS $$ + SELECT nullif(coalesce(nullif(current_setting('request.jwt.claim.sub', true), ''), + (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')), '')::uuid +$$; +CREATE OR REPLACE FUNCTION auth.role() RETURNS text LANGUAGE sql STABLE AS $$ + SELECT coalesce(nullif(current_setting('request.jwt.claim.role', true), ''), + (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'role'))::text +$$; +CREATE OR REPLACE FUNCTION auth.jwt() RETURNS jsonb LANGUAGE sql STABLE AS $$ + SELECT coalesce(nullif(current_setting('request.jwt.claims', true), ''), '{}')::jsonb +$$; +GRANT USAGE ON SCHEMA auth TO postgres, anon, authenticated, service_role; +GRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES, TRIGGER ON auth.users TO postgres; +GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA auth TO PUBLIC; + +-- Auth's own role: what a pg-functions:// hook runs as. +DO $$ BEGIN + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'supabase_auth_admin') THEN + CREATE ROLE supabase_auth_admin NOLOGIN NOINHERIT; + END IF; +END $$; +GRANT USAGE ON SCHEMA auth TO supabase_auth_admin; + +-- The extensions schema every project carries, with uuid-ossp in it. +CREATE SCHEMA IF NOT EXISTS extensions; +CREATE EXTENSION IF NOT EXISTS "uuid-ossp" SCHEMA extensions; +GRANT USAGE ON SCHEMA extensions TO postgres, anon, authenticated, service_role; + +-- The (empty) publication Realtime listens to, owned by `postgres` as on a +-- project, so a migration may add tables to it or re-create it. +DO $$ BEGIN + IF NOT EXISTS (SELECT FROM pg_publication WHERE pubname = 'supabase_realtime') THEN + CREATE PUBLICATION supabase_realtime; + END IF; +END $$; +ALTER PUBLICATION supabase_realtime OWNER TO postgres; + +DO $$ BEGIN + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'supabase_storage_admin') THEN + CREATE ROLE supabase_storage_admin NOLOGIN; + END IF; +END $$; +CREATE SCHEMA IF NOT EXISTS storage AUTHORIZATION supabase_storage_admin; +CREATE TABLE IF NOT EXISTS storage.buckets ( + id text PRIMARY KEY, + name text NOT NULL UNIQUE, + owner uuid, + public boolean DEFAULT false, + created_at timestamptz DEFAULT now(), + updated_at timestamptz DEFAULT now() +); +CREATE TABLE IF NOT EXISTS storage.objects ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + bucket_id text REFERENCES storage.buckets (id), + name text, + owner uuid, + metadata jsonb, + created_at timestamptz DEFAULT now(), + updated_at timestamptz DEFAULT now() +); +ALTER TABLE storage.objects ENABLE ROW LEVEL SECURITY; +ALTER TABLE storage.buckets OWNER TO supabase_storage_admin; +ALTER TABLE storage.objects OWNER TO supabase_storage_admin; +GRANT supabase_storage_admin TO postgres; +GRANT USAGE ON SCHEMA storage TO anon, authenticated, service_role; +GRANT ALL ON storage.buckets, storage.objects TO anon, authenticated, service_role; +""" + +USER_JSON = """ +SELECT json_build_object( + 'id', id, 'aud', 'authenticated', 'role', 'authenticated', 'email', email, 'phone', '', + 'email_confirmed_at', email_confirmed_at, 'confirmed_at', email_confirmed_at, + 'last_sign_in_at', last_sign_in_at, + 'app_metadata', json_build_object('provider', 'email', 'providers', json_build_array('email')), + 'user_metadata', raw_user_meta_data, + 'identities', json_build_array(json_build_object( + 'identity_id', id, 'id', id, 'user_id', id, 'provider', 'email', + 'identity_data', json_build_object('sub', id, 'email', email, 'email_verified', email_confirmed_at IS NOT NULL), + 'created_at', created_at, 'updated_at', updated_at, 'last_sign_in_at', last_sign_in_at)), + 'created_at', created_at, 'updated_at', updated_at, 'deleted_at', deleted_at, 'is_anonymous', false) +FROM auth.users""" + + +def hash_password(password: str) -> str: + salt = secrets.token_hex(8) + digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 10000).hex() + return f"pbkdf2${salt}${digest}" + + +def check_password(password: str, stored: str) -> bool: + try: + _, salt, digest = stored.split("$") + except ValueError: + return False + got = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 10000).hex() + return hmac.compare_digest(got, digest) + + +def user_by(where: str, **params): + # A soft-deleted user is gone as far as Auth is concerned. + run = psql(f"{USER_JSON} WHERE deleted_at IS NULL AND ({where});", ADMIN, **params) + out = run.stdout.strip() + return json.loads(out) if run.returncode == 0 and out else None + + +class HookFailed(Exception): + pass + + +def run_hook(user_id: str, claims: dict) -> dict: + """The access-token hook, as Auth runs one: as supabase_auth_admin, with + Auth's event, its answer's `claims` the token's. Off until config/auth + turns it on.""" + if not AUTH_CONFIG.get("hook_custom_access_token_enabled"): + return claims + m = HOOK_URI.match(AUTH_CONFIG.get("hook_custom_access_token_uri") or "") + if not m: + raise HookFailed(f"unsupported hook URI {AUTH_CONFIG.get('hook_custom_access_token_uri')!r}") + event = {"user_id": user_id, "claims": claims, "authentication_method": "password"} + run = psql(f"SET ROLE supabase_auth_admin;\nSELECT {m.group(1)}.{m.group(2)}(:'event'::jsonb)::text;", + ADMIN, event=json.dumps(event)) + lines = run.stdout.strip().splitlines() + if run.returncode != 0 or not lines: + raise HookFailed(run.stderr.strip() or "the hook answered nothing") + answer = json.loads(lines[-1]) + if not isinstance(answer.get("claims"), dict): + raise HookFailed("the hook's answer has no claims object") + return answer["claims"] + + +def session_for(user: dict) -> dict: + now = int(time.time()) + claims = {"aud": "authenticated", "exp": now + 3600, "iat": now, "iss": f"{BASE}/auth/v1", + "sub": user["id"], "email": user["email"], "phone": "", "role": "authenticated", + "aal": "aal1", "amr": [{"method": "password", "timestamp": now}], + "app_metadata": user["app_metadata"], "user_metadata": user["user_metadata"], + "session_id": str(uuid.uuid4()), "is_anonymous": False} + claims = run_hook(user["id"], claims) + refresh = secrets.token_urlsafe(24) + with LOCK: + REFRESH[refresh] = user["id"] + psql("UPDATE auth.users SET last_sign_in_at = now() WHERE id = :'id';", ADMIN, id=user["id"]) + return {"access_token": jwt_encode(claims), "token_type": "bearer", "expires_in": 3600, + "expires_at": now + 3600, "refresh_token": refresh, "user": user} + + +def may_email(email: str) -> bool: + allowed = CONFIG["email_allowed"] + return allowed is None or email in allowed + + +def mail(email: str, kind: str, redirect_to): + token_hash = secrets.token_hex(28) + with LOCK: + OUTBOX.append({"email": email, "type": kind, "token_hash": token_hash, "redirect_to": redirect_to}) + + +# ── PostgREST: the query string a supabase-js call becomes ──────────────── +RESERVED = {"select", "order", "limit", "offset", "on_conflict", "columns"} + + +class Refused(Exception): + def __init__(self, status, body): + super().__init__(body.get("message")) + self.status, self.body = status, body + + +def ident(name: str) -> str: + name = name.strip().strip('"') + if not NAME.match(name): + raise Refused(400, {"code": "PGRST100", "message": f"unsupported identifier {name!r}"}) + return f'"{name}"' + + +def where_clause(pairs, params: dict) -> str: + conds = [] + for key, value in pairs: + if key in RESERVED: + continue + col = ident(key) + neg = False + op, _, arg = value.partition(".") + if op == "not": + neg = True + op, _, arg = arg.partition(".") + if op in ("eq", "neq"): + p = f"p{len(params)}" + params[p] = arg + cond = f"{col} {'=' if op == 'eq' else '<>'} :'{p}'" + elif op == "is" and arg in ("null", "true", "false"): + cond = f"{col} IS {arg.upper()}" + else: + raise Refused(400, {"code": "PGRST100", "message": f"unsupported filter {key}={value}"}) + conds.append(f"NOT ({cond})" if neg else cond) + return " AND ".join(conds) or "true" + + +EMBED = re.compile(r"^(?:([a-z_][a-z0-9_]*):)?([a-z_][a-z0-9_]*)\((.*)\)$", re.S) + + +def split_top(select: str) -> list: + """A select list's items, split on the commas outside parentheses.""" + items, depth, cur = [], 0, "" + for ch in select: + if ch == "," and depth == 0: + items.append(cur.strip()) + cur = "" + continue + depth += {"(": 1, ")": -1}.get(ch, 0) + cur += ch + if cur.strip(): + items.append(cur.strip()) + return items + + +def foreign_key(table: str, column: str): + """The table and column a public.<table>.<column> foreign key points at.""" + run = psql("SELECT c.confrelid::regclass::text || ' ' || ra.attname FROM pg_constraint c " + "JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1] " + "JOIN pg_attribute ra ON ra.attrelid = c.confrelid AND ra.attnum = c.confkey[1] " + "WHERE c.contype = 'f' AND c.conrelid = ('public.' || :'t')::regclass " + "AND array_length(c.conkey, 1) = 1 AND a.attname = :'c';", ADMIN, t=table, c=column) + out = run.stdout.split() + if run.returncode != 0 or len(out) != 2: + raise Refused(400, {"code": "PGRST200", "message": f"no relationship from {table}.{column}"}) + ref = out[0] if "." in out[0] else f"public.{out[0]}" + return ref, out[1] + + +def select_list(select: str, table: str, src: str, depth: int = 0) -> str: + """PostgREST's select: `*`, columns, and many-to-one embeds + (`author:user_id(*)`) resolved through the column's foreign key, the + embedded row a JSON object (null when there is none) read under the same + role, so its own row-level security applies.""" + if depth > 3: + raise Refused(400, {"code": "PGRST100", "message": "embeds nest too deep"}) + out = [] + for item in split_top(select.strip() or "*"): + if item == "*": + out.append(f"{src}.*") + continue + m = EMBED.match(item) + if not m: + out.append(f"{src}.{ident(item)}") + continue + alias, column, inner = m.group(1) or m.group(2), m.group(2), m.group(3) + ref, refcol = foreign_key(table, column) + ref_table = ref.split(".", 1)[1] + inner_src = f"e{depth}" + out.append(f"(SELECT row_to_json(x{depth}) FROM (SELECT {select_list(inner, ref_table, inner_src, depth + 1)} " + f"FROM {ref} AS {inner_src} WHERE {inner_src}.{ident(refcol)} = {src}.{ident(column)}) x{depth}) AS {ident(alias)}") + return ", ".join(out) + + +def order_of(order: str) -> str: + if not order: + return "" + parts = [] + for term in order.split(","): + col, _, direction = term.partition(".") + parts.append(f"{ident(col)} {'DESC' if direction.startswith('desc') else 'ASC'}") + return " ORDER BY " + ", ".join(parts) + + +def primary_key(table: str) -> list: + run = psql("SELECT a.attname FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid " + "AND a.attnum = ANY(i.indkey) WHERE i.indrelid = ('public.' || :'t')::regclass " + "AND i.indisprimary ORDER BY a.attnum;", ADMIN, t=table) + return [ident(c) for c in run.stdout.split()] if run.returncode == 0 else [] + + +def as_role(claims: dict, sql: str, **params) -> subprocess.CompletedProcess: + role = claims.get("role") + if role not in ("anon", "authenticated", "service_role"): + role = "anon" + return psql(f"BEGIN; SET LOCAL ROLE {role}; " + f"SELECT set_config('request.jwt.claims', :'claims', true) \\g /dev/null\n" + f"{sql}\nCOMMIT;", DB, claims=json.dumps(claims), **params) + + +def pg_error(run: subprocess.CompletedProcess, claims: dict) -> Refused: + msg = re.sub(r"^(psql:<stdin>:\d+: )?ERROR:\s+", "", run.stderr.strip().splitlines()[0] if run.stderr.strip() else "") + if "row-level security" in msg or "permission denied" in msg: + status = 401 if claims.get("role") == "anon" else 403 + return Refused(status, {"code": "42501", "details": None, "hint": None, "message": msg}) + if "duplicate key" in msg: + return Refused(409, {"code": "23505", "details": None, "hint": None, "message": msg}) + # A table the schema does not have is not in PostgREST's schema cache: it + # answers 404 PGRST205 — what a project's Data API says before the + # migrations ran. + missing = re.match(r'relation "(?:public\.)?([^"]+)" does not exist', msg) + if missing: + return Refused(404, {"code": "PGRST205", "details": None, "hint": None, + "message": f"Could not find the table 'public.{missing.group(1)}' in the schema cache"}) + return Refused(400, {"code": "PGRST000", "details": None, "hint": None, "message": msg}) + + +class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, fmt, *args): # quiet: the e2e prints what matters + pass + + def answer(self, status: int, body=None, headers=None, raw: bytes = None) -> None: + data = raw if raw is not None else (b"" if body is None else json.dumps(body).encode()) + self.send_response(status) + self.send_header("content-type", "application/json; charset=utf-8") + self.send_header("content-length", str(len(data))) + self.send_header("x-supabase-api-version", "2024-01-01") + # Supabase's gateway answers every origin, with CORS headers: the + # chat calls the project from the browser, which enforces them. + self.send_header("access-control-allow-origin", "*") + self.send_header("access-control-expose-headers", "content-range, x-supabase-api-version") + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + if self.command != "HEAD": + self.wfile.write(data) + + def fail(self, status: int, code: str, msg: str) -> None: + self.answer(status, {"code": code, "error_code": code, "msg": msg}) + + def body(self): + return json.loads(self.raw or b"{}") + + def bearer(self): + auth = self.headers.get("authorization") or "" + return auth[7:] if auth.lower().startswith("bearer ") else None + + # ── routing ────────────────────────────────────────────────────────── + def route(self, method: str) -> None: + # The body is read before anything answers: the connection is kept + # alive, and an unread body would be the next request's first bytes. + self.raw = self.rfile.read(int(self.headers.get("content-length") or 0)) + url = urllib.parse.urlsplit(self.path) + path = url.path + pairs = urllib.parse.parse_qsl(url.query, keep_blank_values=True) + query = dict(pairs) + if method == "POST" and ROUTE.match(path): + return self.management_query(path) + if method in ("GET", "PATCH") and AUTH_CONFIG_ROUTE.match(path): + return self.management_auth_config(method, path) + if ADMIN and path.startswith("/__fake/"): + return self.fake_admin(method, path) + if ADMIN and path.startswith("/auth/v1/"): + if self.headers.get("apikey") not in (ANON_KEY, SERVICE_KEY): + return self.answer(401, {"message": "Invalid API key"}) + try: + return self.auth(method, path[len("/auth/v1"):], query) + except HookFailed as e: + return self.answer(500, {"code": 500, "error_code": "unexpected_failure", + "msg": f"Error running hook URI: {e}"}) + if ADMIN and path.startswith("/rest/v1/"): + if self.headers.get("apikey") not in (ANON_KEY, SERVICE_KEY): + return self.answer(401, {"message": "Invalid API key"}) + try: + return self.rest(method, path[len("/rest/v1/"):], pairs) + except Refused as r: + return self.answer(r.status, r.body) + return self.answer(404, {"message": f"no such endpoint {method} {path}"}) + + def handle_route(self, method: str) -> None: + try: + self.route(method) + except Exception as e: # a stand-in that drops the connection hides what broke + self.answer(500, {"message": f"fake-supabase-api: {e.__class__.__name__}: {e}"}) + + def do_OPTIONS(self): # a browser's preflight, as the gateway answers it + self.rfile.read(int(self.headers.get("content-length") or 0)) + self.answer(204, None, { + "access-control-allow-methods": "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS", + "access-control-allow-headers": self.headers.get("access-control-request-headers") or "*", + "access-control-max-age": "3600"}) + + def do_GET(self): + self.handle_route("GET") + + def do_HEAD(self): + self.handle_route("HEAD") + + def do_POST(self): + self.handle_route("POST") + + def do_PUT(self): + self.handle_route("PUT") + + def do_PATCH(self): + self.handle_route("PATCH") + + def do_DELETE(self): + self.handle_route("DELETE") + + # ── the Management API's query endpoint ────────────────────────────── + def management_query(self, path: str) -> None: + m = ROUTE.match(path) + if REF and m.group(1) != REF: + return self.answer(404, {"message": f"no such project {m.group(1)}"}) + if not self.bearer(): + return self.answer(401, {"message": "missing bearer token"}) + query = self.body()["query"] + # A read returns its rows; anything else runs as written and returns + # none, as the real endpoint does for DDL. + if re.match(r"^\s*select\b", query, re.I): + run = psql(f"select coalesce(json_agg(t), '[]'::json) from ({query.rstrip().rstrip(';')}) t;") + else: + run = psql(query) + if run.returncode != 0: + return self.answer(400, {"message": run.stderr.strip()}) + out = run.stdout.strip() + return self.answer(201, json.loads(out) if out.startswith("[") else []) + + # ── the Management API's Auth config ───────────────────────────────── + def management_auth_config(self, method: str, path: str) -> None: + m = AUTH_CONFIG_ROUTE.match(path) + if REF and m.group(1) != REF: + return self.answer(404, {"message": f"no such project {m.group(1)}"}) + if not self.bearer(): + return self.answer(401, {"message": "missing bearer token"}) + if method == "PATCH": + body = self.body() + uri = body.get("hook_custom_access_token_uri") + if uri is not None and not HOOK_URI.match(uri) and not uri.startswith("https://"): + return self.answer(400, {"message": f"invalid hook_custom_access_token_uri {uri!r}"}) + with LOCK: + AUTH_CONFIG.update(body) + if "mailer_autoconfirm" in body: + CONFIG["mailer_autoconfirm"] = bool(body["mailer_autoconfirm"]) + with LOCK: + return self.answer(200, dict(AUTH_CONFIG)) + + # ── what the e2e reads back and switches ───────────────────────────── + def fake_admin(self, method: str, path: str) -> None: + if path == "/__fake/outbox" and method == "GET": + with LOCK: + return self.answer(200, list(OUTBOX)) + if path == "/__fake/config" and method == "POST": + CONFIG.update({k: v for k, v in self.body().items() if k in CONFIG}) + return self.answer(200, CONFIG) + return self.answer(404, {"message": "no such fake endpoint"}) + + # ── GoTrue ─────────────────────────────────────────────────────────── + def auth(self, method: str, path: str, query: dict) -> None: + if path == "/health" and method == "GET": + return self.answer(200, {"version": "fake", "name": "GoTrue", "description": "stand-in"}) + if path == "/settings" and method == "GET": + return self.answer(200, { + "external": {"email": True, "phone": False, "anonymous_users": False}, + "disable_signup": False, "mailer_autoconfirm": CONFIG["mailer_autoconfirm"], + "phone_autoconfirm": False, "sms_provider": "", "saml_enabled": False}) + if path == "/.well-known/jwks.json" and method == "GET": + return self.answer(200, {"keys": []}) + if path == "/signup" and method == "POST": + return self.signup(self.body(), query.get("redirect_to")) + if path == "/token" and method == "POST": + return self.token(query.get("grant_type"), self.body()) + if path.startswith("/admin/users/"): + return self.admin_user(method, path[len("/admin/users/"):]) + if path == "/user": + claims = jwt_decode(self.bearer() or "") + if not claims or claims.get("role") != "authenticated": + return self.fail(403, "bad_jwt", "invalid JWT: unable to parse or verify signature") + user = user_by("id = :'id'", id=claims["sub"]) + if not user: + return self.fail(403, "user_not_found", "User from sub claim in JWT does not exist") + if method == "GET": + return self.answer(200, user) + if method == "PUT": + body = self.body() + if body.get("password"): + psql("UPDATE auth.users SET encrypted_password = :'pw', updated_at = now() WHERE id = :'id';", + ADMIN, pw=hash_password(body["password"]), id=user["id"]) + return self.answer(200, user_by("id = :'id'", id=user["id"])) + if path == "/logout" and method == "POST": + return self.answer(204) + if path == "/recover" and method == "POST": + email = (self.body().get("email") or "").lower() + if not may_email(email): + return self.fail(400, "email_address_not_authorized", + f'Email address "{email}" cannot be used as it is not authorized') + if user_by("email = :'email'", email=email): + mail(email, "recovery", query.get("redirect_to")) + return self.answer(200, {}) + if path == "/verify" and method == "POST": + body = self.body() + with LOCK: + hit = next((m for m in OUTBOX if m["token_hash"] == body.get("token_hash") + and not m.get("used")), None) + if hit: + hit["used"] = True + if not hit: + return self.fail(403, "otp_expired", "Email link is invalid or has expired") + psql("UPDATE auth.users SET email_confirmed_at = coalesce(email_confirmed_at, now()) " + "WHERE email = :'email';", ADMIN, email=hit["email"]) + return self.answer(200, session_for(user_by("email = :'email'", email=hit["email"]))) + return self.answer(404, {"message": f"no such auth endpoint {method} {path}"}) + + def admin_user(self, method: str, uid: str) -> None: + claims = jwt_decode(self.bearer() or "") + if not claims or claims.get("role") != "service_role": + return self.fail(403, "not_admin", "User not allowed") + try: + uid = str(uuid.UUID(uid)) + except ValueError: + return self.fail(400, "validation_failed", "user id must be a UUID") + user = user_by("id = :'id'", id=uid) + if not user: + return self.fail(404, "user_not_found", "User not found") + if method == "GET": + return self.answer(200, user) + if method == "DELETE": + if self.body().get("should_soft_delete"): + # GoTrue's soft delete: the row stays (so nothing cascades), + # its email is obfuscated and Auth treats the user as gone. + run = psql("UPDATE auth.users SET deleted_at = now(), updated_at = now(), " + "email = 'deleted-' || id || '@deleted.invalid' WHERE id = :'id';", ADMIN, id=uid) + else: + run = psql("DELETE FROM auth.users WHERE id = :'id';", ADMIN, id=uid) + if run.returncode != 0: + return self.answer(500, {"message": run.stderr.strip()}) + return self.answer(200, user) + return self.answer(405, {"message": f"{method} /admin/users/<id> is not supported"}) + + def signup(self, body: dict, redirect_to) -> None: + email, password = (body.get("email") or "").lower(), body.get("password") or "" + if not re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", email): + return self.fail(400, "validation_failed", "Unable to validate email address: invalid format") + if len(password) < 6: + return self.answer(422, {"code": "weak_password", "msg": "Password should be at least 6 characters.", + "weak_password": {"reasons": ["length"]}}) + if user_by("email = :'email'", email=email): + return self.fail(422, "user_already_exists", "User already registered") + confirm = not CONFIG["mailer_autoconfirm"] + if confirm and not may_email(email): + return self.fail(400, "email_address_not_authorized", + f'Email address "{email}" cannot be used as it is not authorized') + uid = str(uuid.uuid4()) + run = psql("INSERT INTO auth.users (id, email, encrypted_password, email_confirmed_at, raw_user_meta_data) " + "VALUES (:'id', :'email', :'pw', " + ("NULL" if confirm else "now()") + ", :'meta');", + ADMIN, id=uid, email=email, pw=hash_password(password), meta=json.dumps(body.get("data") or {})) + if run.returncode != 0: + return self.answer(500, {"message": run.stderr.strip()}) + user = user_by("id = :'id'", id=uid) + if confirm: + mail(email, "signup", redirect_to) + return self.answer(200, user) + return self.answer(200, session_for(user)) + + def token(self, grant: str, body: dict) -> None: + if grant == "password": + email = (body.get("email") or "").lower() + run = psql("SELECT encrypted_password, email_confirmed_at IS NOT NULL FROM auth.users " + "WHERE email = :'email' AND deleted_at IS NULL;", ADMIN, email=email) + row = run.stdout.strip().split("|") if run.stdout.strip() else None + if not row or not check_password(body.get("password") or "", row[0]): + return self.fail(400, "invalid_credentials", "Invalid login credentials") + if row[1] != "t": + return self.fail(400, "email_not_confirmed", "Email not confirmed") + return self.answer(200, session_for(user_by("email = :'email'", email=email))) + if grant == "refresh_token": + with LOCK: + uid = REFRESH.pop(body.get("refresh_token") or "", None) + user = uid and user_by("id = :'id'", id=uid) + if not user: + return self.fail(400, "refresh_token_not_found", "Invalid Refresh Token: Refresh Token Not Found") + return self.answer(200, session_for(user)) + return self.fail(400, "unsupported_grant_type", f"unsupported grant_type {grant!r}") + + # ── PostgREST ──────────────────────────────────────────────────────── + def rest(self, method: str, table: str, pairs: list) -> None: + if not NAME.match(table): + raise Refused(400, {"message": "bad table name"}) + claims = jwt_decode(self.bearer() or self.headers.get("apikey") or "") + if not claims: + raise Refused(401, {"code": "PGRST301", "message": "JWT invalid"}) + query = dict(pairs) + prefer = {p.strip() for p in (self.headers.get("prefer") or "").split(",") if p.strip()} + single = "application/vnd.pgrst.object+json" in (self.headers.get("accept") or "") + params: dict = {} + where = where_clause(pairs, params) + rel = f'public.{ident(table)}' + returning = "return=representation" in prefer + + if method in ("GET", "HEAD"): + limit = f" LIMIT {int(query['limit'])}" if query.get("limit", "").isdigit() else "" + # jsonb, not json: json_agg breaks lines between rows, and the + # answer is read back as one line. + sql = (f"SELECT jsonb_build_object('rows', coalesce((SELECT jsonb_agg(t) FROM (SELECT {select_list(query.get('select', '*'), table, 'src')} " + f"FROM {rel} AS src WHERE {where}{order_of(query.get('order', ''))}{limit}) t), '[]'::jsonb), " + f"'count', (SELECT count(*) FROM {rel} WHERE {where}))::text;") + status = 200 + elif method == "POST": + body = self.body() + rows = body if isinstance(body, list) else [body] + cols = [ident(c) for c in (query["columns"].split(",") if query.get("columns") + else dict.fromkeys(k for r in rows for k in r))] + if not cols: + raise Refused(400, {"message": "nothing to insert"}) + params["body"] = json.dumps(rows) + conflict = "" + if "resolution=merge-duplicates" in prefer or "resolution=ignore-duplicates" in prefer: + target = [ident(c) for c in query["on_conflict"].split(",")] if query.get("on_conflict") else primary_key(table) + if "resolution=ignore-duplicates" in prefer: + conflict = f" ON CONFLICT ({', '.join(target)}) DO NOTHING" + else: + conflict = (f" ON CONFLICT ({', '.join(target)}) DO UPDATE SET " + + ", ".join(f"{c} = EXCLUDED.{c}" for c in cols)) + insert = (f"INSERT INTO {rel} ({', '.join(cols)}) SELECT {', '.join(cols)} " + f"FROM json_populate_recordset(NULL::{rel}, :'body'){conflict}") + sql = self.write(insert, returning, query, table) + status = 201 + elif method == "PATCH": + body = self.body() + cols = [ident(c) for c in body] + if not cols: + raise Refused(400, {"message": "nothing to update"}) + params["body"] = json.dumps(body) + update = (f"UPDATE {rel} SET ({', '.join(cols)}) = (SELECT {', '.join(cols)} " + f"FROM json_populate_record(NULL::{rel}, :'body')) WHERE {where}") + sql = self.write(update, returning, query, table) + status = 200 if returning else 204 + elif method == "DELETE": + sql = self.write(f"DELETE FROM {rel} WHERE {where}", returning, query, table) + status = 200 if returning else 204 + else: + raise Refused(405, {"message": f"{method} is not supported"}) + + run = as_role(claims, sql, **params) + if run.returncode != 0: + raise pg_error(run, claims) + lines = run.stdout.strip().splitlines() + result = json.loads(lines[-1]) if lines else {"rows": [], "count": 0} + data, count = result.get("rows") or [], result.get("count") + headers = {} + if count is not None: + total = count if any(p.startswith("count=") for p in prefer) or method in ("GET", "HEAD") else "*" + headers["content-range"] = f"0-{len(data) - 1}/{total}" if data else f"*/{total}" + if method in ("GET", "HEAD") or returning: + if single: + if len(data) != 1: + raise Refused(406, {"code": "PGRST116", "details": f"The result contains {len(data)} rows", + "hint": None, "message": "JSON object requested, multiple (or no) rows returned"}) + return self.answer(status, data[0], headers) + return self.answer(status, data, headers) + return self.answer(status, None, headers) + + @staticmethod + def write(statement: str, returning: bool, query: dict, table: str) -> str: + if returning: + cols = select_list(query.get("select", "*"), table, "w") + return (f"WITH w AS ({statement} RETURNING *) SELECT jsonb_build_object('rows', " + f"coalesce((SELECT jsonb_agg(t) FROM (SELECT {cols} FROM w) t), '[]'::jsonb), " + f"'count', (SELECT count(*) FROM w))::text;") + # return=minimal: no RETURNING, so no SELECT policy is asked — as + # PostgREST does it. + return f"{statement};" + + +if ADMIN: + run = psql(PROJECT_SCHEMAS, ADMIN) + if run.returncode != 0: + sys.exit(f"fake-supabase-api: could not create the project's auth and storage schemas: {run.stderr.strip()}") + print(f"anon-key {ANON_KEY}", flush=True) + print(f"service-role-key {SERVICE_KEY}", flush=True) +http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever() diff --git a/testing/lib/local-postgres.sh b/testing/lib/local-postgres.sh new file mode 100755 index 0000000..74f7147 --- /dev/null +++ b/testing/lib/local-postgres.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# A throwaway Postgres for the e2e — the database a Supabase project would be, +# with Supabase's roles — on a random local port. Sourced. +# +# pg_up <dir> <port> start it in <dir> — a fresh `mktemp -d`, which it +# takes over — and print the URL the app and the +# migrations use (role `postgres`) on stdout +# pg_down <dir> stop it +# +# THE ROLES ARE SUPABASE'S, because what is tested here is whether the app +# still works once every table in `public` has row-level security: +# supabase_admin the bootstrap superuser (Supabase's own) +# postgres LOGIN, NOT a superuser and WITHOUT BYPASSRLS: what the +# dashboard's SQL editor (the Management API's query +# endpoint) runs as, and so db-migrate — it owns the tables +# it creates, and ownership is the only thing that exempts it +# from row-level security here +# anon, authenticated, service_role +# what Supabase's Data API runs requests as — the anon key, +# a signed-in user's JWT, the service-role key — with the +# grants Supabase gives them on `public` by default (every +# table the `postgres` role creates); `service_role` has +# BYPASSRLS, as on Supabase. `postgres` is a member of all +# three, so the Data API stand-in and a test can `SET ROLE` +# +# Postgres refuses to run as root, so when the caller is root the server runs +# as the `postgres` system user (Debian's packages create one). Trust auth on +# 127.0.0.1 only: a URL's password is ignored, which is what lets the same +# `postgres://postgres:postgres@…` shape the wrangler config uses reach it. +# +# Needs: a PostgreSQL server install (initdb, pg_ctl) — /usr/lib/postgresql/*/bin +# is searched when they are not on PATH — and psql. + +pg_bin() { + local b + if command -v initdb >/dev/null 2>&1; then dirname "$(command -v initdb)"; return; fi + for b in /usr/lib/postgresql/*/bin; do [ -x "$b/initdb" ] && { echo "$b"; return; }; done + return 1 +} + +pg_as() { # run a command as the user that owns the cluster + if [ "$(id -u)" = 0 ]; then runuser -u postgres -- "$@"; else "$@"; fi +} + +pg_up() { + local dir="$1" port="$2" bin + bin="$(pg_bin)" || { echo "pg_up: no PostgreSQL server binaries (initdb, pg_ctl)" >&2; return 1; } + mkdir -p "$dir" + [ "$(id -u)" = 0 ] && chown postgres "$dir" && chmod 700 "$dir" + pg_as "$bin/initdb" -D "$dir/data" -U supabase_admin --auth=trust -E UTF8 >"$dir/initdb.log" 2>&1 \ + || { cat "$dir/initdb.log" >&2; return 1; } + pg_as "$bin/pg_ctl" -D "$dir/data" -l "$dir/server.log" -w -t 60 \ + -o "-p $port -c listen_addresses=127.0.0.1 -k $dir -c fsync=off" start >/dev/null \ + || { cat "$dir/server.log" >&2; return 1; } + psql "postgres://supabase_admin@127.0.0.1:$port/postgres" -X -q -v ON_ERROR_STOP=1 >"$dir/roles.log" 2>&1 <<'SQL' \ + || { cat "$dir/roles.log" >&2; return 1; } +CREATE ROLE postgres LOGIN NOSUPERUSER NOBYPASSRLS CREATEDB CREATEROLE; +GRANT CREATE ON DATABASE postgres TO postgres; +GRANT USAGE, CREATE ON SCHEMA public TO postgres; +CREATE ROLE anon NOLOGIN NOINHERIT; +CREATE ROLE authenticated NOLOGIN NOINHERIT; +CREATE ROLE service_role NOLOGIN NOINHERIT BYPASSRLS; +GRANT anon, authenticated, service_role TO postgres; +GRANT USAGE ON SCHEMA public TO anon, authenticated, service_role; +ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO anon, authenticated, service_role; +ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO anon, authenticated, service_role; +ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO anon, authenticated, service_role; +SQL + echo "postgres://postgres:postgres@127.0.0.1:$port/postgres" +} + +pg_down() { + local dir="$1" bin + bin="$(pg_bin)" || return 0 + [ -d "$dir/data" ] && pg_as "$bin/pg_ctl" -D "$dir/data" -m immediate stop >/dev/null 2>&1 || true +} diff --git a/testing/lib/run-hooks.py b/testing/lib/run-hooks.py new file mode 100755 index 0000000..31a1ea3 --- /dev/null +++ b/testing/lib/run-hooks.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Run one phase's `run:` hooks EXACTLY as repo-blueprint.yaml declares them. + + run-hooks.py <blueprint> <phase> <slot> <tree> <baseline-dir> <values.json> [--skip id,id] + +The offline bootstrap (testing/lib/bootstrap.sh) uses this so that what it +exercises is the blueprint's own hook list, not a transcription of it: a hook +added, removed or reordered in the blueprint is added, removed or reordered +here with no edit. Argv templates are rendered the way orun renders them for +the hooks this baseline uses — `{{ .baseline.dir }}`, `{{ .phase.name }}`, +`{{ .inputs.<key> }}` — and anything else left between braces is an error, so +a hook that starts using a template this cannot render fails loudly rather +than running with a literal `{{ … }}` in its argv. + +`uses:` hooks are the platform's typed actions (task, repo, land, watch, +probe, reconcile). They need a workspace and the network, and are reported as +skipped; the caller stands in for the ones whose effect the tree needs (a +landing is a commit). +""" +import json +import pathlib +import re +import subprocess +import sys + +import yaml + + +def main() -> int: + args = sys.argv[1:] + skip = set() + if "--skip" in args: + i = args.index("--skip") + skip = {s for s in args[i + 1].split(",") if s} + args = args[:i] + args[i + 2:] + blueprint, phase_name, slot, tree, baseline_dir, values_path = args + bp = yaml.safe_load(pathlib.Path(blueprint).read_text()) + phase = next((p for p in bp.get("phases") or [] if p.get("name") == phase_name), None) + if phase is None: + print(f"run-hooks: no phase {phase_name!r}", file=sys.stderr) + return 2 + inputs = {k: v for k, v in json.loads(pathlib.Path(values_path).read_text()).items() if not k.startswith("_")} + + def render(arg: str) -> str: + out = arg.replace("{{ .baseline.dir }}", baseline_dir).replace("{{ .phase.name }}", phase_name) + out = re.sub(r"\{\{ \.inputs\.([A-Za-z0-9_]+) \}\}", lambda m: str(inputs.get(m.group(1), "")), out) + if "{{" in out: + raise SystemExit(f"run-hooks: cannot render {arg!r} — a template this harness does not know") + return out + + for hook in ((phase.get("hooks") or {}).get(slot) or []): + hid = hook.get("id") + if "uses" in hook: + print(f" · {phase_name}/{slot}/{hid}: {hook['uses']} (platform action — skipped offline)") + continue + if hid in skip: + print(f" · {phase_name}/{slot}/{hid}: skipped by the caller") + continue + argv = [render(a) for a in hook.get("run") or []] + print(f" ▸ {phase_name}/{slot}/{hid}") + r = subprocess.run(argv, cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + for line in (r.stdout or "").splitlines()[-6:]: + print(f" {line}") + if r.returncode != 0: + print(f"run-hooks: {phase_name}/{slot}/{hid} exited {r.returncode}", file=sys.stderr) + print(r.stdout, file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/testing/lib/stage-job.py b/testing/lib/stage-job.py new file mode 100755 index 0000000..1f80c10 --- /dev/null +++ b/testing/lib/stage-job.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Stage a job's private tree the way orun's runner does. + + stage-job.py <source-tree> <work-dir> [--shared-deps] + +orun runs every job of a run in an isolated copy of the source checkout, +`.orun/runs/<exec>/<job>/work` (orun internal/runner/workspace.go, +`materializeTree`). What it does with installed dependencies depends on the +composition the component's lane runs: + + default the job installs them itself, so `node_modules` is left out + at every level and the job's install step recreates it + INSIDE the work tree (stack-tectonic < 0.20.0, or a + composition with no lane-scoped install); + --shared-deps a `scope: lane` install ran once in the source checkout + (stack-tectonic >= 0.20.0, orun >= 2.78.2): the TOP-LEVEL + `node_modules` is a SYMLINK to the source tree's, and every + nested one is COPIED with its pnpm symlinks intact — so they + resolve up through that link, OUT of the work tree. + +Either way `.git` and `.orun` are left out, and so are build outputs and +caches (.next, .nuxt, .turbo, .svelte-kit, dist, build, target, .venv, venv, +__pycache__, .terraform, .pytest_cache, .mypy_cache). + +Why a test builds here rather than in a plain checkout: the first live +bootstrap of this baseline died in the --shared-deps layout — Next.js 16's +Turbopack refuses a dependency that resolves outside its project root +("Symlink … points out of the filesystem root") — in a lane that +testing/e2e.test.sh had run green over a plain checkout. +""" +import os +import shutil +import sys + +OUTPUT_DIRS = {".next", ".nuxt", ".turbo", ".svelte-kit", "dist", "build", "target", + ".venv", "venv", "__pycache__", ".terraform", ".pytest_cache", ".mypy_cache"} +SKIP = {".git", ".orun"} + + +def stage(src: str, dst: str, top: bool, shared_deps: bool) -> None: + os.makedirs(dst, exist_ok=True) + for entry in os.scandir(src): + name = entry.name + s, d = entry.path, os.path.join(dst, name) + if name in SKIP: + continue + if entry.is_symlink(): + os.symlink(os.readlink(s), d) + continue + if entry.is_dir(): + if name in OUTPUT_DIRS: + continue + if name == "node_modules": + if not shared_deps: + continue # the job installs its own + if top: + os.symlink(os.path.abspath(s), d) # the lane's one install + else: + shutil.copytree(s, d, symlinks=True) # copied, links intact + continue + stage(s, d, False, shared_deps) + continue + shutil.copy2(s, d) + + +def main() -> int: + args = sys.argv[1:] + shared = "--shared-deps" in args + paths = [a for a in args if a != "--shared-deps"] + if len(paths) != 2: + print("usage: stage-job.py <source-tree> <work-dir> [--shared-deps]", file=sys.stderr) + return 2 + src, dst = (os.path.abspath(p) for p in paths) + if os.path.exists(dst): + print(f"stage-job: {dst} exists", file=sys.stderr) + return 2 + stage(src, dst, True, shared) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/testing/manifest.test.sh b/testing/manifest.test.sh new file mode 100755 index 0000000..0a88c7f --- /dev/null +++ b/testing/manifest.test.sh @@ -0,0 +1,446 @@ +#!/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). +# +# `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, and per key +# the scope template it is minted under — `secrets: [{key, template}]`, or +# `keys` sharing one `template`. Read per key so a hook minting two keys is +# two facts rather than one. +blueprint_secrets = {} +for phase in bp_phases: + for hook in uses(phase, "orun.integrations/reconcile@v1"): + w = hook.get("with") or {} + for item in (w.get("secrets") or []): + blueprint_secrets[item.get("key")] = (w.get("provider"), item.get("template")) + for key in (w.get("keys") or []): + blueprint_secrets[key] = (w.get("provider"), w.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. + 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 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 — + # `epicSlug`, `productdomain`, `orunWorkspace`, `repoPrivate` 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`, `productdomain` 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:`, which is why a phase that is + # the second landing of one unit of work would name its predecessor's + # milestone rather than one of its own (`04-workers-restore` did, before + # the bootstrap folded it into `05-edge`). + # + # 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/phases.test.sh b/testing/phases.test.sh new file mode 100755 index 0000000..b6eda99 --- /dev/null +++ b/testing/phases.test.sh @@ -0,0 +1,568 @@ +#!/usr/bin/env bash +# The phases in `repo-blueprint.yaml` must be the phases the bootstrap runs, +# placing what they are meant to place, in the order their hooks must run, +# saying what they are, and naming only what the engine can resolve. +# +# TWO PHASES, ONE LANDING THAT DEPLOYS. `01-product` places every module the +# blueprint declares — root files, workflows, tooling, the Supabase root, the +# migrations, the app and the tests — and lands them as ONE pull request; the +# convergence after that merge provisions, migrates and deploys it all, the +# order carried by the components' enforced `dependsOn` (placement proves it +# on the product's own plan). `02-docs` places nothing: it records the deployment and +# restores what 01-product deferred. +# +# The partition is written down a second time below on purpose: a module that +# drifts out of 01-product, or a phase that grows back between the two, is a +# change to how a product is built and has to be argued in the diff that edits +# both places. The hook ORDER is written down too: every step of the identity +# chain depends on the one before it (rebrand reads `git ls-files`, the verify +# reads the restaged tree, the credentials are minted after the link and +# before the landing whose convergence uses them), and a reorder fails live. +# +# What the applies publish is not checked by a separate await when the +# convergence already proves it: a key that a component resolves as its job +# starts, failing without it, and that waits for its publisher on main, is +# there — from the place every later run looks — once the convergence is +# green. This file holds that for each key, and asks for an +# `orun.secrets/exists@v1` await for every key nothing reads. +# +# And the shape that keeps a bootstrap fast (orun >= v2.88.0): the run-level +# task set-up runs in the background, each phase finds its task just before +# its landing, each landing checks its commit here (`checks: local`), and the +# convergence watch reads every few seconds. +# +# Adapted from sourceplane/cirrus-baseline's testing/phases.test.sh: the +# narration rules and the hook-only rule are Cirrus's, unchanged. +# +# 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") + +PRODUCT = ["ai-deployment", "ai-operations", "db", "db-migrate", "db-tests", + "github-workflows", "rebrand-values", "root-agents", "root-gitignore", + "root-intent", "root-package-json", "root-pnpm-lock", "root-pnpm-workspace", + "root-readme", "root-turbo", "supabase", "tooling-eslint", "tooling-migrations", + "tooling-tsconfig", "tooling-wire", "vscode", "web", "web-tests"] +PARTITION = {"01-product": PRODUCT, "02-docs": []} +HOOK_ONLY = {"02-docs"} +# The phase that DEPLOYS, and so must give a re-run something to land. +DEPLOYS = {"01-product"} + +# No phase has a `pre` hook: the task is found in `post`, just before the +# landing, so that everything before it runs beside the background task +# set-up. +PRE = {"01-product": [], "02-docs": []} +# The post hooks, in the order they must run (the brief's chain): the +# re-run marker and the git index; the rebrand and the re-tenant; the three +# rewrites a product needs before it lands; the restage and the verify; the +# repository and its link; one brokered `secrets` reconcile per provider +# (checked below); the task, then the landing. +POST_ORDER = { + "01-product": ["retouch", "git-init", "stage", "rebrand", "orun-workspace", + "work-tree", "promotion", "dev-lanes", "restage", "rebrand-verify", + "repo", "link", "secrets-cloudflare", "secrets-supabase", "task", "land"], + "02-docs": ["promotion", "dev-lanes", "render", "task", "land"], +} +# The scripts behind the run: hooks that rewrite intent.yaml, with the mode +# each must be called in. +RUNS = { + ("01-product", "work-tree"): ("tooling/bootstrap/work-tree.mjs", "--strip"), + ("01-product", "promotion"): ("tooling/bootstrap/promotion.mjs", "--defer"), + ("01-product", "dev-lanes"): ("tooling/bootstrap/dev-lanes.mjs", "--defer"), + ("02-docs", "promotion"): ("tooling/bootstrap/promotion.mjs", "--restore"), + ("02-docs", "dev-lanes"): ("tooling/bootstrap/dev-lanes.mjs", "--restore"), + ("02-docs", "render"): ("hooks/render-deployment-docs.sh", None), +} +# 01-product watches its convergence and probes the app; between the two it +# awaits only the published keys nothing in the convergence reads (below — +# with none, the `orun.secrets/exists@` drops out). 02-docs awaits nothing: +# its render probes as it writes, and its landing redeploys nothing. +AWAIT_ORDER = {"01-product": ["orun.run/watch@", "orun.http/probe@"], + "02-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.") +if names != list(PARTITION): + bad(f"phases are {names}; the bootstrap runs {list(PARTITION)}") + +# ── the partition has not drifted ───────────────────────────────────────── +for name, want in PARTITION.items(): + if name not in by_name: + continue + now = sorted(by_name[name].get("modules") or []) + if now != sorted(want): + bad(f"phase {name} no longer places what it placed: gained " + f"{sorted(set(now) - set(want)) or '[]'}, lost {sorted(set(want) - set(now)) or '[]'}") +declared = {m["name"] for m in bp.get("modules") or []} +placed = {m for p in phases for m in (p.get("modules") or [])} +for m in sorted(declared - placed): + bad(f"module {m} is declared and no phase places it") +for m in sorted(declared - set(PRODUCT)): + bad(f"module {m} is declared and 01-product does not place it — every module lands in the one landing") +for name in HOOK_ONLY: + if by_name.get(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 ──────────────── +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 — require " + f"its predecessor instead") + if need not in by_name or names.index(need) >= names.index(p["name"]): + bad(f"phase {p['name']} requires {need}, which does not run before it") + +# ── 01-product asks for every connection it mints from, before it creates anything +probe = ((by_name.get("01-product") or {}).get("requires") or {}).get("probe") or [] +doctor = [h for h in probe if (h.get("uses") or "").startswith("orun.doctor/check@")] +want_providers = {"github", "cloudflare", "supabase"} +if not doctor or set((doctor[0].get("with") or {}).get("providers") or []) != want_providers: + bad(f"01-product must probe {sorted(want_providers)} with orun.doctor/check@v1 before it places") +elif (doctor[0].get("with") or {}).get("githubOwner") != "{{ .inputs.githuborg }}": + bad("01-product's doctor probe must wait for the GitHub App on the repository's owner") + +# ── 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 files " + f"still has to land them") + +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 [])] + +run_hooks = list((bp.get("hooks") or {}).get("preInstantiate") or []) + +# ── the hook chain, in order ────────────────────────────────────────────── +for name, want in PRE.items(): + got = [h.get("id") for h in ((by_name.get(name, {}).get("hooks") or {}).get("pre") or [])] + if got != want: + bad(f"phase {name}'s pre hooks are {got}; want {want} — a task found in `pre` waits " + f"for the background task set-up before the phase has done anything") +for name, want in POST_ORDER.items(): + p = by_name.get(name) + if not p: + continue + post = (p.get("hooks") or {}).get("post") or [] + ids = [h.get("id") for h in post] + if ids != want: + bad(f"phase {name}'s post hooks run {ids}; the chain is {want}") + # THE BROKERED KEYS, ONE `secrets` RECONCILE PER PROVIDER (orun >= v2.87.0): + # each key under its own scope template, the connections and the existing + # secrets read once per hook, the missing keys created side by side. A + # reconcile reads one connection, so two providers are two hooks; two + # hooks whose other parameters are the same are one hook written twice. + shared = {} + for h in post: + if (h.get("id") or "").startswith("secret") and not (h.get("uses") or "").startswith("orun.integrations/reconcile@"): + bad(f"phase {name} hook {h.get('id')} is not an orun.integrations/reconcile@v1") + if not (h.get("uses") or "").startswith("orun.integrations/reconcile@"): + continue + w = h.get("with") or {} + if "keys" in w or "template" in w or not w.get("secrets"): + bad(f"phase {name} hook {h.get('id')} does not use the `secrets: [{{key, template}}]` form — " + f"one template per hook reads the connections and the secrets once per key") + if h.get("id") != f"secrets-{w.get('provider')}": + bad(f"phase {name} hook {h.get('id')} mints from {w.get('provider')}; name it secrets-{w.get('provider')}") + same = tuple(sorted((k, str(v)) for k, v in w.items() if k != "secrets")) + if same in shared: + bad(f"phase {name} hooks {shared[same]} and {h.get('id')} take the same parameters {dict(same)} — " + f"merge them into one `secrets` list") + shared.setdefault(same, h.get("id")) + for (ph, hid), (script, mode) in RUNS.items(): + if ph != name: + continue + hook = next((h for h in post if h.get("id") == hid), None) + argv = " ".join((hook or {}).get("run") or []) + if script not in argv or (mode and mode not in argv): + bad(f"phase {name} hook {hid} must run {script} {mode or ''}".rstrip()) + +# ── what the infrastructure publishes is read in the convergence ────────── +# Each infra component's `secretOutputs` is what its apply lease-publishes to +# the project's stage and prod rungs. A key is PROVED by the convergence when +# a component that waits for the publisher on a merge to main (`mode: +# enforced`, advisory on a pull request) resolves it from that place as its +# job starts and fails without it, on both stage and prod: +# - a `secretEnv` reference fails the job when the document is missing; +# - an `optionalSecretEnv` reference does not — the job starts without it — +# so it proves the key on an environment only when the component's build +# renders that environment's document with tooling/wire/live.mjs +# (`--components <publisher> --env "${ORUN_ENVIRONMENT}"`), which exits 1 +# when the document is not there. That is how web reads WIRING_SUPABASE: +# optional, because stage's deploy may start before prod's apply has +# published. +# Such a key needs no await; a key nothing reads that way must be awaited +# with `orun.secrets/exists@v1` on stage and prod in 01-product — and a key +# the convergence already proves must not be, because that await is a +# platform round trip that can only agree. +comps = {} +for f in root.rglob("component.yaml"): + if "node_modules" in f.parts: + continue + d = yaml.safe_load(f.read_text()) or {} + comps[(d.get("metadata") or {}).get("name")] = (f.relative_to(root).as_posix(), d.get("spec") or {}) +def enforced_on_main(spec, target): + edge = next((d for d in spec.get("dependsOn") or [] if d.get("component") == target), None) + rules = (edge or {}).get("modeRules") or [] + return bool(edge) and edge.get("mode") == "enforced" and any( + r.get("mode") == "advisory" and (r.get("when") or {}).get("triggerRef") == "github-pull-request" + for r in rules) +def renders_live(spec, pub): + build = str((spec.get("parameters") or {}).get("buildCommand") or "") + m = re.search(r"tooling/wire/live\.mjs\b[^;&|]*?--components\s+([\w,-]+)[^;&|]*?--env\s+\"?\$\{ORUN_ENVIRONMENT\}", build) + return bool(m) and pub in m.group(1).split(",") +published = {} +for name, (rel, spec) in comps.items(): + if not rel.startswith("infra/"): + continue + for pair in str((spec.get("parameters") or {}).get("secretOutputs") or "").split(","): + if "=" in pair: + published[pair.split("=", 1)[0].strip()] = name +if not published: + bad("no infra component declares secretOutputs — this check has gone blind") +proved, readers_of = set(), {} +for key, pub in sorted(published.items()): + covered = set() + for name, (rel, spec) in comps.items(): + if name == pub: + continue + subscribed = {e.get("name") for e in ((spec.get("subscribe") or {}).get("environments") or [])} + refs = [(as_env, ref, False) for as_env, ref in (spec.get("secretEnv") or {}).items()] + refs += [(as_env, ref, True) for as_env, ref in (spec.get("optionalSecretEnv") or {}).items()] + for as_env, ref, optional in refs: + m = re.fullmatch(r"secret://[^/]+/[^/]+/([^/]+)/([A-Z0-9_]+)", str(ref)) + if not m or m.group(2) != key: + continue + readers_of.setdefault(key, set()).add(name) + if not enforced_on_main(spec, pub): + bad(f"{rel} resolves {key} and does not wait for {pub} on a merge to main — declare " + f"dependsOn {pub} with mode: enforced and a modeRules advisory on github-pull-request") + continue + env = m.group(1) + on = subscribed & {"stage", "prod"} + envs = on if "{{" in env else ({env} if env in on else set()) + if optional: + # Proves only the rung the job's own render demands, under the + # name live.mjs reads it by. + want_env = f"WIRING_{pub.upper().replace('-', '_')}_{env.upper()}" + if "{{" in env or as_env != want_env or not renders_live(spec, pub): + continue + covered |= envs + if covered >= {"stage", "prod"}: + proved.add(key) +awaits = ((by_name.get("01-product") or {}).get("hooks") or {}).get("await") or [] +exists = [h for h in awaits if (h.get("uses") or "").startswith("orun.secrets/exists@")] +awaited = {k for h in exists for k in ((h.get("with") or {}).get("keys") or [])} +if set(published) - proved - awaited: + bad(f"01-product neither reads nor awaits {sorted(set(published) - proved - awaited)} — nothing in " + f"the convergence resolves it on stage and prod, so await it with orun.secrets/exists@v1") +if awaited & proved: + bad(f"01-product awaits {sorted(awaited & proved)}, which the convergence already resolves " + f"({', '.join(sorted({r for k in awaited & proved for r in readers_of.get(k, ())}))}) — drop them") +if awaited - set(published): + bad(f"01-product awaits {sorted(awaited - set(published))}, which no infra component publishes") +for h in exists: + w = h.get("with") or {} + if sorted(w.get("environments") or []) != ["prod", "stage"]: + bad(f"01-product awaits the published secrets on {w.get('environments')}, not stage and prod") + if w.get("project") != "{{ .inputs.reponame }}": + bad("01-product awaits the published secrets in another project than the product's") +# A key nothing reads is awaited between the watch and the probe. +if set(published) - proved: + AWAIT_ORDER["01-product"] = ["orun.run/watch@", "orun.secrets/exists@", "orun.http/probe@"] +for name, want in AWAIT_ORDER.items(): + awaits = ((by_name.get(name) or {}).get("hooks") or {}).get("await") or [] + got = [h.get("uses") or "" for h in awaits] + if len(got) != len(want) or not all(g.startswith(w) for g, w in zip(got, want)): + bad(f"phase {name}'s await hooks are {got}; they must be {want} (in that order)") +for name in names: + for h in ((by_name[name].get("hooks") or {}).get("await") or []): + if (h.get("uses") or "").startswith("orun.http/probe@"): + urls = (h.get("with") or {}).get("urls") or [] + for env in ("stage", "prod"): + base = f"https://{{{{ .inputs.reponame }}}}-web-{env}.{{{{ .inputs.subdomain }}}}.workers.dev" + for want in (base, base + "/api/health"): + if want not in urls: + bad(f"phase {name}'s probe does not ask {want}") + +# ── every phase lands, and every landing is bound to its task ───────────── +for p in phases: + ids = [h.get("id") for h in hooks_of(p)] + lands = [h for h in hooks_of(p) if (h.get("uses") or "").startswith("orun.pr/land@")] + if len(lands) != 1: + bad(f"phase {p['name']} has {len(lands)} landing(s); a phase is ONE pull request") + continue + w = lands[0].get("with") or {} + if w.get("task") != "{{ .phase.hooks.task.outputs.key }}": + bad(f"phase {p['name']} lands without binding the PR to its task key") + if "task" not in ids or ids.index("task") > ids.index(lands[0].get("id")): + bad(f"phase {p['name']} must ensure its task before it lands") + if p["name"] in DEPLOYS: + if not any("retouch.mjs" in " ".join(h.get("run") or []) for h in hooks_of(p)): + bad(f"phase {p['name']} deploys and has no retouch hook — a re-run after a " + f"failed convergence would land an empty diff and redeploy nothing") + awaits = (p.get("hooks") or {}).get("await") or [] + watch = [h for h in awaits if (h.get("uses") or "").startswith("orun.run/watch@")] + if not watch or (watch[0].get("with") or {}).get("sha") != "{{ .phase.hooks.land.outputs.mergeSha }}": + bad(f"phase {p['name']} deploys and does not watch the convergence of the " + f"commit it merged (orun.run/watch@v1 with sha: mergeSha)") + +# ── THE FAST SHAPE (orun >= v2.88.0) ────────────────────────────────────── +# The run-level list is the task set-up, all of it in the background: the +# first phase's provider check, placement, rebrand, repository and secrets +# run while it opens the epic, the milestones and the tasks. +for h in run_hooks: + if not h.get("background"): + bad(f"hooks.preInstantiate {h.get('id')} is not `background: true` — the first phase " + f"waits for it before doing anything, though nothing before its landing reads it") +# No phase reaches the task plane in `pre`: that waits for the background at +# once, before the phase has placed a file — the old order. +for p in phases: + for h in ((p.get("hooks") or {}).get("pre") or []): + if (h.get("uses") or "").startswith(("orun.task/", "orun.pr/")): + bad(f"phase {p['name']} pre hook {h.get('id')} uses {h['uses']} — find the task in " + f"`post`, just before the landing") +# Every landing checks its commit here and merges, instead of waiting ~25 s +# for a runner to plan the tree this box just wrote. +for p in phases: + for h in hooks_of(p): + if (h.get("uses") or "").startswith("orun.pr/land@") and (h.get("with") or {}).get("checks") != "local": + bad(f"phase {p['name']} lands with checks {(h.get('with') or {}).get('checks', 'ci')!r}, " + f"not 'local' — it waits for a runner to plan a tree that is here") +# The convergence watch reads every few seconds, not the action's default 40. +for p in phases: + for h in ((p.get("hooks") or {}).get("await") or []): + if (h.get("uses") or "").startswith("orun.run/watch@"): + every = (h.get("with") or {}).get("pollSeconds") + if not isinstance(every, int) or every > 10: + bad(f"phase {p['name']} watches its convergence every {every or 40} s; at most 10 — " + f"the build goes on that much after the run is green") +# The shipped lockfile is installed frozen by the lanes and by the baseline's +# e2e tier; a hook re-resolving it is a minute of network for nothing. +for p in phases: + for h in hooks_of(p): + if "--lockfile-only" in (h.get("run") or []): + bad(f"phase {p['name']} hook {h.get('id')} re-resolves the lockfile the baseline ships") + +# ── every phase's task is one the run-level list opens, in the same order ─ +def task_names(hooks): + return [(h.get("with") or {}).get("name") for h in hooks + if (h.get("uses") or "").startswith("orun.task/ensure@") + and (h.get("with") or {}).get("kind") == "task"] +opened = task_names(run_hooks) +per_phase = [n for p in phases for n in task_names(hooks_of(p))] +if opened != per_phase: + bad(f"the run-level list opens tasks {opened}; the phases ensure {per_phase} — " + f"a task is found by its title, so the two must be the same words") +milestones = [(h.get("with") or {}).get("name") for h in run_hooks + if (h.get("with") or {}).get("kind") == "milestone"] +if milestones != names: + bad(f"the run-level list opens milestones {milestones}; the phases are {names}") +for h in run_hooks + [x for p in phases for x in hooks_of(p)]: + if (h.get("with") or {}).get("prefix") not in (None, "BASE"): + bad(f"hook {h.get('id')} files its task under prefix {h['with']['prefix']}, not BASE") + +# ── every contract a hook names exists, beside the blueprint ────────────── +for h in run_hooks + [x for p in phases for x in hooks_of(p)]: + rel = (h.get("with") or {}).get("contract") + if rel and not (root / rel).exists(): + bad(f"hook {h.get('id')} names contract {rel}, which does not exist") + if rel and not rel.startswith(".baseline/tasks/"): + bad(f"hook {h.get('id')} names contract {rel} outside .baseline/tasks/ — " + f"`tasks/` is this repository's own work tree, where an unkeyed " + f"contract is an error") +for p in phases: + for h in hooks_of(p): + argv = " ".join(h.get("run") or []) + for ref in re.findall(r"\{\{ \.baseline\.dir \}\}/(\S+?)(?:\"|'|\s|$)", argv + " "): + if not (root / ref).exists(): + bad(f"phase {p['name']} hook {h.get('id')} runs {ref}, which this " + f"repository does not have") + +# ── every phase has a documentation page, and every page a phase ────────── +docs_dir = root / "docs" / "phases" +pages = {f.stem for f in docs_dir.glob("*.md")} - {"README"} +for n in names: + if n not in pages: + bad(f"phase {n} has no page at docs/phases/{n}.md") +for page in sorted(pages - set(names)): + bad(f"docs/phases/{page}.md documents a phase repo-blueprint.yaml does not declare") + +# ── narration: authored here, printed from state (Cirrus's rules) ───────── +META_AT = { + "start": {"files", "expectedMinutes"}, + "await": {"files", "expectedMinutes"}, + "failed": {"files", "expectedMinutes"}, + "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()) + +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): + return re.sub(r"\{\{.*?\}\}", "", line, flags=re.S) + +def refs(line): + 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): + 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 the " + f"caption. Describe the world, not the run.") + for ref in refs(line): + parts = ref.split(".") + head = parts[0] + if head == "phase": + if len(parts) != 2 or parts[1] not in PHASE_KEYS: + bad(f"{where} names .{ref}; a phase carries {sorted(PHASE_KEYS)}") + elif head == "inputs": + if len(parts) != 2 or parts[1] not in input_keys: + bad(f"{where} names .{ref}, which is not a declared input") + elif head == "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 {sorted(allowed)}") + elif head == "hooks": + if len(parts) < 2 or parts[1] not in hook_ids: + bad(f"{where} names .{ref}; this phase has no such hook") + else: + bad(f"{where} names .{ref}; narration may reference phase, inputs, meta and hooks") + +# The run-level hooks are reported under no phase, and read only their own +# outputs. +run_ids = {h.get("id") for h in run_hooks} +for h in run_hooks: + if h.get("narrate"): + check_line(f"hooks.preInstantiate {h.get('id')} narrate", h["narrate"], "start", run_ids) + +# `await` is the one slot a phase leaves to the engine: with no authored +# line, a waiting event reads "<title>: <what it waits on>" in the engine's +# own words (an older engine says "<phase> is waiting."). An authored one is +# refused below. +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) + if not line: + if slot != "await": + bad(f"phase {p['name']} declares no narrate.{slot}") + continue + check_line(f"phase {p['name']} narrate.{slot}", line, slot, ids) + 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 — a " + f"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) + +# ── what the build panel reads (orun-cloud saas-build-panel BV4) ───────── +# The console shows each hook's `narrate:` verbatim as the build's progress +# and a phase's waiting line as what it waits on. So: no phase authors an +# `await` line — a wait is also a `requires.probe` asking for a connection, +# and only the engine knows what it waits on (the line it generates is +# "<title>: <reason>"; the reasons are whole clauses, so no authored frame +# around `.meta.waitingOn` reads true); every step a reader should see +# says what it left behind; every landing names its pull request for the +# reader (`label`); and a hook-only phase files no second set of addresses — +# it has no re-probe (its render probes as it writes; the fast shape above), +# and one that came back would have to be `quiet`. `label`, `pin` and +# `quiet` are orun >= v2.86 keys, below the bootstrap floor (v2.88.0) — +# their shapes are checked here. +NARRATED = {"01-product": ["repo", "link", "secrets-*", "land"], + "02-docs": ["render", "land"]} +for p in phases: + if (p.get("narrate") or {}).get("await"): + bad(f"phase {p['name']} authors narrate.await — leave it to the engine, which " + f"says what the phase waits on (\"<title>: <reason>\"), a connection included") + for h in hooks_of(p): + if "label" in h and not (isinstance(h["label"], str) and h["label"].strip()): + bad(f"phase {p['name']} hook {h.get('id')} label must be a non-empty string") + for key in ("pin", "quiet"): + if key in h and not isinstance(h[key], bool): + bad(f"phase {p['name']} hook {h.get('id')} {key} must be true or false") + if (h.get("uses") or "").startswith("orun.pr/land@") and not h.get("label"): + bad(f"phase {p['name']} landing {h.get('id')} has no label — the panel names " + f"each pull request by it") +for name, want in NARRATED.items(): + post = ((by_name.get(name) or {}).get("hooks") or {}).get("post") or [] + for tok in want: + hooks = [h for h in post if (h.get("id") == tok or + (tok.endswith("*") and (h.get("id") or "").startswith(tok[:-1])))] + if not hooks: + bad(f"phase {name} has no {tok} hook to narrate") + for h in hooks: + if not h.get("narrate"): + bad(f"phase {name} hook {h.get('id')} declares no narrate — the panel " + f"shows nothing for it") +for name in HOOK_ONLY: + for h in ((by_name.get(name) or {}).get("hooks") or {}).get("await") or []: + if (h.get("uses") or "").startswith("orun.http/probe@") and h.get("quiet") is not True: + bad(f"phase {name} re-probes with {h.get('id')} and is not quiet — the " + f"addresses would be filed a second time") + +# ── what a baseline of this shape never grows back ──────────────────────── +if (root / "flows").exists(): + bad("flows/ exists — the bootstrap is the blueprint; every mechanism is a typed orun action") + +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_n = 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")) +narrated += sum(1 for h in run_hooks if h.get("narrate")) +print(f" {len(phases)} phases, {placed_n} modules (all in 01-product), {len(HOOK_ONLY)} hook-only — in execution order") +print(f" the hook chain in order; the convergence resolves {sorted(proved)} on stage and prod, " + f"each from a job that waits for its publisher" + (f"; 01-product awaits {sorted(awaited)}, which nothing reads" if awaited else "")) +print(f" the fast shape: the task set-up in the background, no `pre` hook, every landing checks: local, the watch at ≤ 10 s") +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 100644 index 0000000..8a62a15 --- /dev/null +++ b/testing/placement.test.sh @@ -0,0 +1,482 @@ +#!/usr/bin/env bash +# TIER 1 — the tree is placed, branded, and made to answer. +# +# A real bootstrap is `orun new --run-hooks --resume` against a workspace: it +# places each phase, runs that phase's hooks, lands a pull request and watches +# the convergence. Everything in that sentence except the platform can run +# here, offline, and this file runs it: +# +# 1. the whole blueprint placed in one go — orun runs `validate` and +# `plan --dry-run` inside the produced tree and says so; asserted, because +# a future orun that stopped running them would weaken this tier in silence; +# 2. THE OFFLINE BOOTSTRAP (testing/lib/bootstrap.sh) — both phases placed in +# order, each finished by the blueprint's OWN `run:` hooks (the retouch +# marker, rebrand, re-tenant, work-tree strip, the deferrals and their +# restore, the deployment record), each landing a commit; +# 3. the product it ends with: branded with no residue, carrying nothing of +# the factory and naming none of it, re-tenanted, its gates restored, its +# record rendered, its wrangler config committed; +# 4. what the product's own CI does with the 01-product merge: `orun plan +# --trigger github-push-main` over exactly that commit. Per environment: +# supabase → db-migrate → web, every edge ENFORCED, read off the plan's +# own dependency graph; stage and prod side by side; nothing on dev; +# every brokered key the plan resolves minted by the blueprint, and every +# key the infrastructure publishes read; the Supabase project's Auth Site +# URL the very Worker the deploy names and smoke-tests. The same commit +# planned as a pull request: every one of those edges advisory; +# 5. after 02-docs: prod waits on stage again and dev verifies main again; +# 6. a `--resume` over the finished product places nothing and un-brands +# nothing. +# +# testing/e2e.test.sh goes on from here: it installs, migrates, builds and +# serves the product against a local Supabase stand-in, and chats on it. +# +# Needs: orun, node, pnpm, python3 (+PyYAML), git. No credential. The +# deployment-record probes reach the network if they can, and pass without it. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" +# shellcheck source=lib/bootstrap.sh +source "$here/lib/bootstrap.sh" + +for bin in orun node pnpm python3 git; do + command -v "$bin" >/dev/null || { echo "placement.test.sh needs $bin on PATH" >&2; exit 1; } +done + +scratch="$(mktemp -d)" +trap 'rm -rf "$scratch"' EXIT +fails=0 +fail() { echo " ✕ $*" >&2; fails=$((fails + 1)); } +values="$here/fixtures/acme.json" +repo="$(python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['reponame'])" "$values")" + +sets=() +while IFS=$'\t' read -r k v; do sets+=( --set "$k=$v" ); done < <( + python3 - "$values" <<'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 +) + +# ── 1. the whole blueprint, one placement ────────────────────────────────── +echo "── placing the whole blueprint at once (offline, no credential)" +whole="$scratch/whole" +mkdir -p "$whole" +if ! orun new --blueprint "$root/repo-blueprint.yaml" --out "$whole" "${sets[@]}" > "$scratch/whole.log" 2>&1; then + echo "FAIL: the placement did not run" >&2; tail -20 "$scratch/whole.log" >&2; exit 1 +fi +# The line's wording moved between orun releases (v2.58: `repo gate: validate + +# plan --dry-run passed`; v2.79: `Verified intent valid · N components …`). +grep -Eq "repo gate: validate \+ plan --dry-run passed|Verified +intent valid" "$scratch/whole.log" \ + || fail "the placement did not report the repo-scale gate (orun validate + plan --dry-run inside the tree)" +n="$(find "$whole" -type f -not -path '*/.orun/*' | wc -l | tr -d ' ')" +[ "$n" -ge 100 ] || fail "only $n files placed — that is not a product" +[ "$fails" -eq 0 ] && echo " $n files placed into an empty directory; the repo-scale gate ran" + +# ── 2. the offline bootstrap ─────────────────────────────────────────────── +echo "── the offline bootstrap: both phases, their own hooks, a landing each" +tree="$scratch/$repo" # named as the repository is: orun names the project after it +bootstrap_offline "$root" "$tree" "$values" "$scratch/logs" > "$scratch/bootstrap.log" 2>&1 || { + echo "FAIL: the offline bootstrap stopped" >&2; tail -40 "$scratch/bootstrap.log" >&2; exit 1; } +grep -E '^── ' "$scratch/bootstrap.log" | sed 's/^/ /' +commits="$(git -C "$tree" rev-list --count HEAD)" +[ "$commits" = 2 ] || fail "the bootstrap landed $commits commits, not one per phase (2)" + +# ── 3. the product it ends with ──────────────────────────────────────────── +echo "── the product it produced" +(cd "$tree" && node "$root/tooling/rebrand/rebrand.mjs" --verify --values .rebrand/values.json) > "$scratch/verify.log" 2>&1 \ + || { fail "rebrand --verify found the baseline's identity in the product:"; sed 's/^/ /' "$scratch/verify.log" >&2; } + +python3 - "$tree" "$values" "$root" <<'PY' || fails=$((fails + 1)) +import json, pathlib, re, subprocess, sys +import yaml +tree, values, root = pathlib.Path(sys.argv[1]), json.load(open(sys.argv[2])), pathlib.Path(sys.argv[3]) +problems = [] +def bad(m): problems.append(m) +repo, org, name, sub, ws = (values[k] for k in ("reponame", "githuborg", "productname", "subdomain", "orunWorkspace")) + +tracked = subprocess.run(["git", "ls-files"], cwd=tree, capture_output=True, text=True, check=True).stdout.split() + +# Nothing of the factory, nothing local, exactly the two context pages. +NEVER = (".baseline/", "specs/", "tasks/", "testing/", "hooks/", "docs/phases/", + "tooling/rebrand/", "tooling/bootstrap/", ".github/workflows/baseline.yml", + ".github/workflows/tag.yml", "BOOTSTRAP.md", "repo-blueprint.yaml", "blueprint.yaml") +for p in tracked: + if any(p == n or p.startswith(n) for n in NEVER): + bad(f"{p} is in the product — it is the factory") + if re.search(r"(^|/)(\.env(\.local)?|\.dev\.vars|node_modules|\.orun|\.next|\.open-next|\.terraform)(/|$)", p): + bad(f"{p} is in the product — a local or built file") +ai = {p for p in tracked if p.startswith("ai/")} +if ai != {"ai/context/deployment.md", "ai/context/operations.md"}: + bad(f"ai/ in the product is {sorted(ai)}") + +# …and no tracked file names one of the factory's paths. +FACTORY_PATH = re.compile(r"repo-blueprint|(?<![\w./-])(?:testing|specs|tasks|\.baseline|docs/phases)/" + r"|BOOTSTRAP\.md|tooling/(?:rebrand|bootstrap)\b") +for p in tracked: + try: + text = (tree / p).read_text() + except (UnicodeDecodeError, IsADirectoryError): + continue + for n, line in enumerate(text.splitlines(), 1): + if FACTORY_PATH.search(line): + bad(f"{p}:{n} names the factory: {line.strip()[:80]}") + +# The identity, where the product carries it. +site = (tree / "apps/web/lib/site.ts").read_text() +if f"SITE_NAME = {json.dumps(name)}" not in site: + bad(f"apps/web/lib/site.ts does not name the product {name!r}") +comp = yaml.safe_load((tree / "apps/web/component.yaml").read_text())["spec"] +params = comp["parameters"] +if params["workerName"] != f"{repo}-web": + bad(f"workerName is {params['workerName']}, not {repo}-web") +if params["workersDevSubdomain"] != sub: + bad(f"workersDevSubdomain is {params['workersDevSubdomain']}, not {sub}") +if json.loads((tree / "package.json").read_text())["name"] != repo: + bad("package.json is not named for the product") +for comp_path in ("apps/web", "infra/terraform/supabase", "infra/db-migrate"): + doc = yaml.safe_load((tree / comp_path / "component.yaml").read_text())["spec"] + refs = {**(doc.get("secretEnv") or {}), **(doc.get("optionalSecretEnv") or {})} + if not refs: + bad(f"{comp_path} reads no secret at all — this check has gone blind") + for k, ref in refs.items(): + if not ref.startswith(f"secret://{ws}/{repo}/"): + bad(f"{comp_path} {k} resolves from {ref} — not the product's workspace and project") +# The Supabase project's Auth Site URL is built from the same subdomain the +# Worker answers on. +sb = yaml.safe_load((tree / "infra/terraform/supabase/component.yaml").read_text())["spec"]["parameters"] +if sb.get("workersDevSubdomain") != sub: + bad(f"the supabase root builds Auth's Site URL on {sb.get('workersDevSubdomain')}.workers.dev, not {sub}") + +# The upstream example's own link and licence survive the rename. +UPSTREAM = "github.com/supabase/supabase/tree/master/examples/slack-clone/nextjs-slack-clone" +if UPSTREAM not in (tree / "README.md").read_text(): + bad("README.md's link to the upstream example was renamed") +lic = (tree / "apps/web/LICENSE").read_text() +if "Apache License" not in lic or "Version 2.0" not in lic: + bad("apps/web/LICENSE is not upstream's Apache-2.0 licence") +# The migrations ship byte for byte: db-migrate refuses a changed file, and +# the rebrand must never have touched one. +for p in tracked: + if p.startswith("packages/db/src/migrations/") and p.endswith(".sql"): + if (tree / p).read_bytes() != (root / p).read_bytes(): + bad(f"{p} differs from the baseline's — an applied migration is immutable") + +# The wrangler config is committed, and is the fixture render of the +# (rebranded) template — the composition checks it exists before the build. +if "apps/web/wrangler.jsonc" not in tracked: + bad("apps/web/wrangler.jsonc is not committed — verify-app-structure would fail in every lane") +else: + rendered = tree / "wrangler.check.jsonc" + subprocess.run(["node", "tooling/wire/render.mjs", "--template", "apps/web/wrangler.template.jsonc", + "--out", str(rendered), "--map", "apps/web/wiring.fixture.json", "--env", "stage"], + cwd=tree, check=True, capture_output=True) + if rendered.read_text() != (tree / "apps/web/wrangler.jsonc").read_text(): + bad("apps/web/wrangler.jsonc is not the fixture render of its template") + if f'"name": "{repo}-web"' not in rendered.read_text(): + bad("the committed wrangler config does not carry the product's Worker name") + rendered.unlink() + +# The intent: re-tenanted, no work tree, both gates back. +intent_text = (tree / "intent.yaml").read_text() +intent = yaml.safe_load(intent_text) +if intent["metadata"]["name"] != repo: + bad(f"intent metadata.name is {intent['metadata']['name']}") +if intent["execution"]["state"]["workspace"] != ws: + bad(f"intent workspace is {intent['execution']['state']['workspace']}, not the product's") +if "work" in intent: + bad("intent.yaml still declares the baseline's work tree") +if "promotion" not in intent["environments"]["prod"] or "@promotion-deferred" in intent_text: + bad("prod's promotion gate was not restored by 02-docs") +if "github-push-main" not in intent["environments"]["dev"]["activation"]["triggerRefs"] or "@dev-lanes-deferred" in intent_text: + bad("dev's push activation was not restored by 02-docs") +for env in ("stage", "prod"): + want = f"https://{repo}-web-{env}.{sub}.workers.dev" + if intent["environments"][env].get("url") != want: + bad(f"environments.{env}.url is {intent['environments'][env].get('url')}, not {want}") + if intent["environments"][env]["parameterDefaults"]["terraform"]["repo"] != repo: + bad(f"environments.{env} names the Supabase project after another repo") +for page in (intent.get("repo") or {}).get("docs", {}).get("pages", []): + if not (tree / page["path"]).exists(): + bad(f"intent repo.docs names {page['path']}, which the product does not have") + +# The landings, as the phases made them: a redeploy marker on every +# component 01-product's contract names, the record rendered by 02-docs. +contract = yaml.safe_load((root / ".baseline/tasks/01-product.TaskContract.yaml").read_text()) +for comp_name in contract["spec"]["affects"]: + hits = [p for p in tracked if p.endswith("component.yaml") + and (yaml.safe_load((tree / p).read_text()) or {}).get("metadata", {}).get("name") == comp_name] + if len(hits) != 1 or not re.search(r"^# orun: redeploy 01-product \S+$", (tree / hits[0]).read_text(), re.M): + bad(f"component {comp_name} carries no 01-product redeploy marker") +dep = (tree / "ai/context/deployment.md").read_text() +if "GENERATED by the `02-docs` phase" not in dep or f"https://{repo}-web-prod.{sub}.workers.dev" not in dep \ + or "/api/health" not in dep or "## Sign-up and roles" not in dep: + bad("ai/context/deployment.md was not rendered for the product") +readme = (tree / "README.md").read_text() +if not readme.startswith(f"# {repo}\n") or "This product is **live**" not in readme: + bad("README.md is not the product's, or its live-deployment section was not rendered") +# The coding agent's first page: at the root, branded, and the README points at it. +agents = (tree / "AGENTS.md").read_text() if (tree / "AGENTS.md").is_file() else "" +if "AGENTS.md" not in tracked or not agents.startswith(f"# {repo} "): + bad("AGENTS.md is not the product's, branded with its name") +if "(AGENTS.md)" not in readme: + bad("README.md does not point a coding agent at AGENTS.md") +for page in ("ai/context/operations.md", "ai/context/deployment.md"): + if page not in agents: + bad(f"AGENTS.md does not send an agent to {page}") + +# Provenance prose, over the BRANDED files. +PROV = re.compile(r"\bfork(ed)? (of|from)\b|\bbaseline (repo|repository|commit|tag)\b|repo-blueprint|BOOTSTRAP\.md", re.I) +for rel in ("README.md", "AGENTS.md", "ai/context/operations.md", "ai/context/deployment.md"): + for n, line in enumerate((tree / rel).read_text().splitlines(), 1): + if PROV.search(line): + bad(f"{rel}:{n} speaks of the factory: {line.strip()[:70]}") + +if problems: + for p in problems: + print(f" ✕ {p}", file=sys.stderr) + sys.exit(1) +print(f" {len(tracked)} tracked files; branded, re-tenanted, naming nothing of the factory, gates restored, record rendered") +PY + +# ── 4. the product's own CI, over the 01-product merge ───────────────────── +echo "── orun plan in the product, for the push that merged 01-product" +s01="$(git -C "$tree" rev-parse HEAD~1)" +# A clone, so the bootstrap's own tree is never moved: at the 01-product +# commit (promotion and dev's push lanes still deferred), with an empty branch +# beside it to plan a pull request against. Named as the repository is. +mkdir -p "$scratch/at-01" +git clone -q "$tree" "$scratch/at-01/$repo" +at01="$scratch/at-01/$repo" +git -C "$at01" checkout -q --orphan empty +git -C "$at01" rm -rqf . +git -C "$at01" -c user.email=t@example.invalid -c user.name=t commit -qm empty --allow-empty +git -C "$at01" checkout -q "$s01" +(cd "$at01" && orun validate --intent intent.yaml) > "$scratch/validate.log" 2>&1 \ + || { fail "orun validate refused the product's intent at 01-product"; tail -10 "$scratch/validate.log" >&2; } +# The merge is the repository's first content: every file is new, so the +# push's `--changed` set is every component — the full plan. +(cd "$at01" && orun plan --intent intent.yaml --trigger github-push-main --output "$scratch/plan-main.json") > "$scratch/plan-main.log" 2>&1 \ + || { fail "orun plan (push to main) failed in the product at 01-product"; tail -15 "$scratch/plan-main.log" >&2; } +(cd "$at01" && orun plan --intent intent.yaml --trigger github-pull-request --base empty --head HEAD \ + --output "$scratch/plan-pr.json") > "$scratch/plan-pr.log" 2>&1 \ + || { fail "orun plan (pull request) failed in the product at 01-product"; tail -15 "$scratch/plan-pr.log" >&2; } + +# The PRODUCT's CI plans with its own lane pin (ci.yml), not with the orun +# that places the blueprint: per-edge `modeRules` — advisory on a pull +# request — are read by that pin, and an orun older than it (v2.58.11, the +# bootstrap's floor before v2.88.0) plans them enforced everywhere. So the +# pull-request half below holds only when this orun is at least the +# product's pin — which the floor now is; e2e.test.sh asserts it again. +lane_pin="$(sed -n 's/^ *version: *v\([0-9.]*\) *$/\1/p' "$tree/.github/workflows/ci.yml" | head -1)" +this_orun="$(orun --version | sed -n 's/.*version v\{0,1\}\([0-9.]*\).*/\1/p' | head -1)" + +python3 - "$scratch/plan-main.json" "$scratch/plan-pr.json" "$values" "$root" "$at01" "$this_orun" "$lane_pin" <<'PLAN' || fails=$((fails + 1)) +import json, pathlib, sys +import yaml +plan, pr = json.load(open(sys.argv[1])), json.load(open(sys.argv[2])) +values, root, tree = json.load(open(sys.argv[3])), pathlib.Path(sys.argv[4]), pathlib.Path(sys.argv[5]) +this_orun, lane_pin = (tuple(int(x) for x in v.split(".")) for v in sys.argv[6:8]) +repo, sub, ws = values["reponame"], values["subdomain"], values["orunWorkspace"] +problems = [] +def bad(m): problems.append(m) +jobs = {(j["component"], j["environment"]): j for j in plan["jobs"]} +ids = {j["id"]: j for j in plan["jobs"]} + +CHAIN = ["supabase", "db-migrate", "web"] +PROFILE = {"supabase": "terraform.apply", "db-migrate": "db-migrate.apply", + "web": "cloudflare-workers-assets-turbo.deploy"} +want = {(c, e) for c in PROFILE for e in ("stage", "prod")} +if set(jobs) != want: + bad(f"the 01-product merge plans {sorted(jobs)}; it must plan {sorted(want)} — and nothing on dev") +for (comp, env), j in jobs.items(): + if comp in PROFILE and j["profile"] != PROFILE[comp]: + bad(f"{comp}@{env} plans {j['profile']}, not {PROFILE[comp]}") + if j.get("dependencyMode") != "enforced": + bad(f"{j['id']} plans dependencyMode {j.get('dependencyMode')}, not enforced") + for dep in j.get("dependsOn") or []: + if ids[dep]["environment"] != j["environment"]: + bad(f"{j['id']} waits on {dep} — during the bootstrap stage and prod run side by side") + +# THE ORDER, read off the plan's own graph: each link of the chain is an +# ENFORCED edge (`dependsOn`, not `advisoryDependsOn`), and the depth of each +# job — the longest chain of enforced edges into it — puts the three on three +# different levels, in order. web reads supabase's wiring and db-migrate's +# schema, so it waits on both directly. +depth = {} +def level(jid): + if jid not in depth: + depth[jid] = 1 + max((level(d) for d in ids[jid].get("dependsOn") or []), default=-1) + return depth[jid] +for env in ("stage", "prod"): + by = {c: jobs.get((c, env)) for c in CHAIN} + if not all(by.values()): + continue + for a, b in zip(CHAIN, CHAIN[1:]): + if by[a]["id"] not in (by[b].get("dependsOn") or []): + bad(f"{b}@{env} does not wait on {a}@{env} — the order is {' → '.join(CHAIN)}") + if by["supabase"]["id"] not in (by["web"].get("dependsOn") or []): + bad(f"web@{env} reads supabase's wiring and does not wait on it") + order = sorted(CHAIN, key=lambda c: level(by[c]["id"])) + levels = [level(by[c]["id"]) for c in order] + if order != CHAIN or len(set(levels)) != len(levels): + bad(f"{env} converges {order} at levels {levels}; it must be {' → '.join(CHAIN)}, one after another") + else: + print(f" {env}, enforced: " + " → ".join(order)) + +# …and on a pull request every one of those edges is ADVISORY: nothing is +# applied or deployed there, so nothing waits. +prj = {(j["component"], j["environment"]): j for j in pr["jobs"]} +pr_edges = this_orun >= lane_pin +for env in ("stage", "prod"): + for a, b in zip(CHAIN, CHAIN[1:]) if pr_edges else (): + jb, ja = prj.get((b, env)), prj.get((a, env)) + if not ja or not jb: + bad(f"the pull-request plan has no {a}@{env} or {b}@{env}") + continue + if ja["id"] in (jb.get("dependsOn") or []): + bad(f"on a pull request {b}@{env} still waits on {a}@{env} — the edge must be advisory there") + if ja["id"] not in (jb.get("advisoryDependsOn") or []): + bad(f"on a pull request {b}@{env} does not name {a}@{env} as advisory") + for comp, prof in (("supabase", "plan-only"), ("db-migrate", "plan"), ("web", "verify")): + j = prj.get((comp, env)) + if j and not j["profile"].endswith("." + prof): + bad(f"on a pull request {comp}@{env} plans {j['profile']}, which may mutate") +if pr_edges: + print(" pull request: the same edges, advisory; plan-only, plan and verify — nothing applied") +else: + print(f" pull request: plan-only, plan and verify — nothing applied (the edges' advisory mode is " + f"read by the product's lane pin v{'.'.join(map(str, lane_pin))}; this orun is " + f"v{'.'.join(map(str, this_orun))} — not checked here)") + +# Every brokered key the plan resolves is one the blueprint mints, and every +# other key it resolves is one an apply publishes — nothing else. Derived +# from the product's own plan (component secretEnv and optionalSecretEnv AND +# the compositions' bindings), the blueprint's reconcile hooks and the +# components' secretOutputs. Every key the apply publishes is read: the +# three database credentials by db-migrate, the wiring document by web. +bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text()) +# Either form a reconcile takes: `secrets: [{key, template}]`, or `keys`. +minted = {k for p in bp["phases"] for slot in (p.get("hooks") or {}).values() for h in slot + if (h.get("uses") or "").startswith("orun.integrations/reconcile@") + for k in [s["key"] for s in h["with"].get("secrets") or []] + list(h["with"].get("keys") or [])} +published = set() +for comp in tree.glob("infra/**/component.yaml"): + so = str(((yaml.safe_load(comp.read_text()) or {}).get("spec") or {}).get("parameters", {}).get("secretOutputs") or "") + published |= {pair.split("=", 1)[0] for pair in so.split(",") if "=" in pair} +resolved = set() +for (comp, env), j in jobs.items(): + for r in j.get("secretRefs") or []: + ref = r["ref"] + resolved.add(ref.rsplit("/", 1)[1]) + # A wiring document is OPTIONAL to resolve (stage's deploy may start + # before prod's apply has published), and the deploy's render is + # what refuses a missing one. + if r["asEnv"].startswith("WIRING_") and not r.get("optional"): + bad(f"{comp}@{env} resolves {r['asEnv']} as required — prod's may not exist when stage's deploy starts") + if not ref.startswith(f"secret://{ws}/"): + bad(f"{comp}@{env} resolves {r['asEnv']} from {ref} — not the product's workspace") + if f"/{repo}/" not in ref and f"project:{repo}/" not in ref: + bad(f"{comp}@{env} resolves {r['asEnv']} from {ref} — not the product's project") +if resolved - published != minted: + bad(f"the plan resolves brokered keys {sorted(resolved - published)}; the blueprint mints {sorted(minted)}") +if not published: + bad("no infra component publishes anything — this check has gone blind") +if published - resolved: + bad(f"the infrastructure publishes {sorted(published - resolved)} and nothing reads it") +for env in ("stage", "prod"): + mj = jobs.get(("db-migrate", env)) + got = {r["ref"].rsplit("/", 1)[1]: r for r in (mj or {}).get("secretRefs") or []} + for key in ("SUPABASE_ACCESS_TOKEN", "SUPABASE_PROJECT_REF", "SUPABASE_DB_PASSWORD", "SUPABASE_DB_URL"): + r = got.get(key) + if not r or r.get("optional") or not r["ref"].endswith(f"/{env}/{key}"): + bad(f"db-migrate@{env} does not resolve its own environment's {key}, fail-closed") +print(f" the plan resolves exactly the {len(minted)} keys the blueprint mints, and reads " + f"all {len(published)} the apply publishes") + +# The deploy itself: the structure check, the live wiring render, the +# Worker's name, the smoke — and ONE origin for the product: the Supabase +# project's Auth names exactly that Worker +# (or the environment's SITE_URL). main.tf builds the Site URL from +# TF_VAR_repo, TF_VAR_environment and TF_VAR_workersDevSubdomain, which the +# apply's own step exports, unless SITE_URL is set. The chat has no absolute +# link of its own to bake. +main_tf = (tree / "infra/terraform/supabase/terraform/main.tf").read_text() +if 'worker_origin = "https://${var.repo}-web-${var.environment}.${var.workersDevSubdomain}.workers.dev"' not in main_tf \ + or "app_origin = coalesce(trimsuffix(data.external.site_url.result.url, \"/\"), local.worker_origin)" not in main_tf \ + or "$${SITE_URL:-}" not in main_tf: + bad("main.tf no longer builds Auth's Site URL as SITE_URL, else https://<repo>-web-<env>.<subdomain>.workers.dev") +for env in ("stage", "prod"): + sj = jobs.get(("supabase", env)) + exported = "\n".join(s.get("run") or "" for s in (sj or {}).get("steps") or []) + for var, want in (("repo", repo), ("workersDevSubdomain", sub), ("authEmailConfirmation", "false")): + if f"printf 'TF_VAR_{var}=%s\\n' '{want}'" not in exported: + bad(f"supabase@{env} does not export TF_VAR_{var}={want}") + if f"printf 'TF_VAR_environment=%s\\n' \"{env}\"" not in exported: + bad(f"supabase@{env} does not export TF_VAR_environment={env}") + j = jobs.get(("web", env)) + if not j: + continue + own = [r for r in j.get("secretRefs") or [] if r["asEnv"] == f"WIRING_SUPABASE_{env.upper()}"] + if not own or not own[0]["ref"].endswith(f"/{env}/WIRING_SUPABASE"): + bad(f"web@{env} does not read its own environment's WIRING_SUPABASE") + steps = {s["id"]: s.get("run") or "" for s in j["steps"]} + for need in ("verify-app-structure", "build-app", "deploy", "smoke"): + if need not in steps: + bad(f"web@{env} has no {need} step") + if 'test -f "wrangler.jsonc"' not in steps.get("verify-app-structure", ""): + bad(f"web@{env} checks another config before the build: {steps.get('verify-app-structure','').strip()}") + if "tooling/wire/live.mjs" not in steps.get("build-app", "") or "--components supabase" not in steps.get("build-app", ""): + bad(f"web@{env} does not render its wrangler config from the Supabase wiring before it builds") + if 'if [ "${ORUN_ENVIRONMENT}" != dev ]' not in steps.get("build-app", ""): + bad(f"web@{env} renders its wiring on dev too, where nothing is published") + if f'EFFECTIVE_WORKER_NAME="{repo}-web-{env}"' not in steps.get("deploy", ""): + bad(f"web@{env} deploys a Worker not named {repo}-web-{env}") + if "/api/health" not in steps.get("smoke", "") or f'export WORKERS_DEV_SUBDOMAIN="{sub}"' not in steps.get("smoke", ""): + bad(f"web@{env}'s smoke does not check the product's own /api/health") + +if problems: + for p in problems: + print(f" ✕ {p}", file=sys.stderr) + sys.exit(1) +print(" stage and prod side by side; nothing on dev; the Worker, its wiring render and its smoke the product's own") +PLAN + +# ── 5. after the record: the gates are back ──────────────────────────────── +echo "── orun plan in the finished product: prod waits on stage, dev verifies main" +(cd "$tree" && orun plan --intent intent.yaml --trigger github-push-main --output "$scratch/plan-after.json") > "$scratch/plan-after.log" 2>&1 \ + || { fail "orun plan failed in the finished product"; tail -15 "$scratch/plan-after.log" >&2; } +python3 - "$scratch/plan-after.json" <<'AFTER' || fails=$((fails + 1)) +import json, sys +plan = json.load(open(sys.argv[1])) +jobs = {(j["component"], j["environment"]): j for j in plan["jobs"]} +problems = [] +for comp in ("supabase", "db-migrate", "web"): + prod, stage = jobs.get((comp, "prod")), jobs.get((comp, "stage")) + if not prod or not stage or stage["id"] not in (prod.get("dependsOn") or []): + problems.append(f"{comp}@prod does not wait on {comp}@stage — the promotion gate is not back") +dev = sorted(c for (c, e) in jobs if e == "dev") +if dev != ["db", "db-tests", "web", "web-tests"]: + problems.append(f"dev verifies {dev} on a push to main; it must verify db, db-tests, web and web-tests") +for p in problems: + print(f" ✕ {p}", file=sys.stderr) +if problems: + sys.exit(1) +print(" prod waits on stage for every component; dev verifies db, db-tests, web and web-tests") +AFTER + +# ── 6. a resume over the finished product ───────────────────────────────── +echo "── --resume over the finished product" +before="$(git -C "$tree" status --porcelain; git -C "$tree" rev-parse HEAD)" +orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" --resume "${sets[@]}" > "$scratch/resume.log" 2>&1 \ + || { fail "--resume did not run"; tail -10 "$scratch/resume.log" >&2; } +after="$(git -C "$tree" status --porcelain; git -C "$tree" rev-parse HEAD)" +[ "$before" = "$after" ] || { fail "--resume changed the finished product:"; git -C "$tree" status --short | head -10 >&2; } +grep -q "SITE_NAME = \"Sam's Chat & Co\"" "$tree/apps/web/lib/site.ts" \ + || fail "--resume reverted the product's identity" +[ "$fails" -eq 0 ] && echo " nothing placed again, nothing un-branded" + +[ "$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..231afe7 --- /dev/null +++ b/testing/rebrand.test.sh @@ -0,0 +1,187 @@ +#!/usr/bin/env bash +# THE REBRAND WRITES EACH VALUE ONCE, AND WHAT IT WROTE STAYS WRITTEN. +# +# Drives the real tooling/rebrand/rebrand.mjs over one-file trees and compares +# the file. Each case is a shape this baseline's identity actually takes in the +# tree — the name seam, the worker name, the Worker's own origin (the one the +# Supabase project's Auth sends its links to), the placeholder domain, a +# secret ref, the `repo` the Supabase project is named after — and each runs +# through as many passes as a bootstrap might make, so a value written once must survive every later pass +# unchanged. What must NOT be renamed: the upstream example's own link, a +# migration (its checksum is in the manifest and in every project it was +# applied to), and what merely spells `supabase` — a wiring token names the +# component, not this baseline. +# +# The identity is PINNED (fixtures/baseline-identity.supabase-slack-clone.json) rather +# than read from .baseline/identity.json: what this tests is the engine, and +# its fixtures spell the identity out literally. +# +# Needs: node, git. No network. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +rebrand="$here/../tooling/rebrand/rebrand.mjs" +identity="$here/fixtures/baseline-identity.supabase-slack-clone.json" + +fail=0 +# check NAME VALUES-JSON FILE CONTENT WANT [PASSES] +check() { + local name="$1" values="$2" file="$3" content="$4" want="$5" passes="${6:-1}" + local tmp got out i + tmp="$(mktemp -d)" + git -C "$tmp" init -q + mkdir -p "$tmp/$(dirname "$file")" "$tmp/.rebrand" + printf '%s\n' "$content" > "$tmp/$file" + printf '%s\n' "$values" > "$tmp/.rebrand/values.json" + for ((i = 1; i <= passes; i++)); do + git -C "$tmp" add -A + if ! out="$(cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --values .rebrand/values.json --allow-dirty 2>&1)"; then + echo " ✕ $name: rebrand pass $i failed:" >&2 + printf '%s\n' "$out" | sed 's/^/ /' >&2 + fail=1 + rm -rf "$tmp" + return + fi + done + got="$(cat "$tmp/$file")" + rm -rf "$tmp" + if [ "$got" = "$want" ]; then + echo " ok $name" + else + echo " ✕ $name:" >&2 + echo " got: $got" >&2 + echo " want: $want" >&2 + fail=1 + fi +} + +acme='{"reponame":"acme-chat","productname":"Acme Chat","productdomain":"acme.dev","githuborg":"acme-inc","subdomain":"acme","orunWorkspace":"ws_79BDXAZQ"}' + +echo "── rebrand: the product's own identity" +check "the name seam takes the product's name" \ + "$acme" apps/web/lib/site.ts 'export const SITE_NAME = "Slack Clone"' \ + 'export const SITE_NAME = "Acme Chat"' +check "…and stays a valid string for a name with an apostrophe and an ampersand" \ + '{"reponame":"sams-chat","productname":"Sam'"'"'s Chat & Co","productdomain":"sam.dev"}' \ + apps/web/lib/site.ts 'export const SITE_NAME = "Slack Clone"' \ + 'export const SITE_NAME = "Sam'"'"'s Chat & Co"' +check "the display name elsewhere is content, and is left alone" \ + "$acme" apps/web/app/x.tsx '<p>Welcome to the Slack Clone.</p>' \ + '<p>Welcome to the Slack Clone.</p>' +check "the worker name is re-prefixed, the environment suffix kept" \ + "$acme" apps/web/component.yaml 'workerName: supabase-slack-clone-web' \ + 'workerName: acme-chat-web' +check "the Worker's own origin: worker name and subdomain" \ + "$acme" intent.yaml ' url: https://supabase-slack-clone-web-stage.your-workers-subdomain.workers.dev' \ + ' url: https://acme-chat-web-stage.acme.workers.dev' +check "the subdomain the deploy's smoke reaches the Worker on" \ + "$acme" apps/web/component.yaml ' workersDevSubdomain: your-workers-subdomain' \ + ' workersDevSubdomain: acme' +check "the subdomain the Supabase project's Auth Site URL is built from" \ + "$acme" infra/terraform/supabase/component.yaml ' workersDevSubdomain: your-workers-subdomain' \ + ' workersDevSubdomain: acme' +check "the placeholder domain is the product's domain, not a renamed slug" \ + "$acme" intent.yaml ' BASE_DOMAIN: supabase-slack-clone.example.com' \ + ' BASE_DOMAIN: acme.dev' +check "no domain given: the reserved placeholder, for an owner to replace later" \ + '{"reponame":"acme-chat","productname":"Acme Chat","githuborg":"acme-inc","subdomain":"acme"}' \ + intent.yaml ' BASE_DOMAIN: supabase-slack-clone.example.com' \ + ' BASE_DOMAIN: acme-chat.example.com' +check "an empty domain is no domain" \ + '{"reponame":"acme-chat","productname":"Acme Chat","productdomain":""}' \ + intent.yaml ' BASE_DOMAIN: supabase-slack-clone.example.com' \ + ' BASE_DOMAIN: acme-chat.example.com' +check "the repo slug" \ + "$acme" package.json ' "name": "supabase-slack-clone",' \ + ' "name": "acme-chat",' +check "the repo Terraform names the Supabase project after" \ + "$acme" intent.yaml ' repo: supabase-slack-clone' \ + ' repo: acme-chat' +check "…and the Terraform variable's default" \ + "$acme" infra/terraform/supabase/terraform/main.tf ' default = "supabase-slack-clone"' \ + ' default = "acme-chat"' +check "a secret ref names the product's workspace and project" \ + "$acme" apps/web/component.yaml \ + ' WIRING_SUPABASE_STAGE: "secret://supabase-slack-clone/supabase-slack-clone/stage/WIRING_SUPABASE"' \ + ' WIRING_SUPABASE_STAGE: "secret://ws_79BDXAZQ/acme-chat/stage/WIRING_SUPABASE"' +check "this repository's source link names the product's owner and repository" \ + "$acme" README.md 'See https://github.com/sourceplane/supabase-slack-clone.' \ + 'See https://github.com/acme-inc/acme-chat.' +check "a migration is never rewritten (its checksum is in the manifest and in every project it was applied to)" \ + "$acme" packages/db/src/migrations/040_x/up.sql '-- supabase-slack-clone: a comment the checksum covers' \ + '-- supabase-slack-clone: a comment the checksum covers' +check "org-owned identity is not renamed" \ + "$acme" intent.yaml 'apiVersion: sourceplane.io/v1 # mail ops@sourceplane.ai' \ + 'apiVersion: sourceplane.io/v1 # mail ops@sourceplane.ai' + +echo "── rebrand: what is not this baseline's" +check "a wiring token names the component, not the baseline" \ + "$acme" apps/web/wrangler.template.jsonc \ + ' "NEXT_PUBLIC_SUPABASE_URL": "@@wiring(supabase/__ENV__:supabase_url)@@",' \ + ' "NEXT_PUBLIC_SUPABASE_URL": "@@wiring(supabase/__ENV__:supabase_url)@@",' +check "the upstream example's home is upstream's" \ + "$acme" README.md '[Slack clone](https://github.com/supabase/supabase/tree/master/examples/slack-clone/nextjs-slack-clone)' \ + '[Slack clone](https://github.com/supabase/supabase/tree/master/examples/slack-clone/nextjs-slack-clone)' + +echo "── rebrand: a written value is not rewritten, in any later pass" +contains='{"reponame":"supabase-slack-clone-2","productname":"Slack Clone 2","productdomain":"supabase-slack-clone.example.com.au","githuborg":"sourceplane","subdomain":"your-workers-subdomain-2"}' +check "a repo slug containing the baseline's slug survives three passes" \ + "$contains" package.json ' "name": "supabase-slack-clone",' \ + ' "name": "supabase-slack-clone-2",' 3 +check "a worker name built on it survives three passes" \ + "$contains" apps/web/component.yaml 'workerName: supabase-slack-clone-web' \ + 'workerName: supabase-slack-clone-2-web' 3 +check "a domain containing the baseline's domain survives three passes" \ + "$contains" intent.yaml 'BASE_DOMAIN: supabase-slack-clone.example.com' \ + 'BASE_DOMAIN: supabase-slack-clone.example.com.au' 3 +check "a subdomain containing the placeholder survives three passes" \ + "$contains" infra/terraform/supabase/component.yaml 'workersDevSubdomain: your-workers-subdomain' \ + 'workersDevSubdomain: your-workers-subdomain-2' 3 +check "a name containing the baseline's name survives three passes" \ + "$contains" apps/web/lib/site.ts 'export const SITE_NAME = "Slack Clone"' \ + 'export const SITE_NAME = "Slack Clone 2"' 3 + +# --verify runs after every rebrand. Without the product's values it cannot +# tell the product's own identity from a leftover; with them it can. A real +# leftover must fail it either way. +verify() { # NAME VALUES FILE CONTENT WANT(pass|fail) [--values] + local name="$1" values="$2" file="$3" content="$4" want="$5" withvalues="${6:-}" tmp got + tmp="$(mktemp -d)" + git -C "$tmp" init -q + mkdir -p "$tmp/$(dirname "$file")" "$tmp/.rebrand" + printf '%s\n' "$content" > "$tmp/$file" + printf '%s\n' "$values" > "$tmp/.rebrand/values.json" + git -C "$tmp" add -A + if (cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --verify ${withvalues:+--values .rebrand/values.json} >/dev/null 2>&1); then got=pass; else got=fail; fi + rm -rf "$tmp" + 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" +verify "given the values, a slug containing the baseline's passes" \ + "$contains" package.json '"name": "supabase-slack-clone-2"' pass --values +verify "without them it cannot know, and fails" \ + "$contains" package.json '"name": "supabase-slack-clone-2"' fail +verify "given the values, a real leftover still fails" \ + "$acme" package.json '"name": "supabase-slack-clone"' fail --values +verify "a leftover worker name fails" \ + "$acme" apps/web/component.yaml 'workerName: supabase-slack-clone-web' fail --values +verify "a leftover code identifier fails (no rule renames it — so nothing may spell it)" \ + "$acme" apps/web/app/x.ts 'export class SupabaseSlackClone {}' fail --values +verify "the upstream example's links are not residue" \ + "$acme" apps/web/README.md 'the [example](https://github.com/supabase/supabase/tree/master/examples/slack-clone/nextjs-slack-clone)' pass --values +verify "a clean product passes" \ + "$acme" package.json '"name": "acme-chat"' pass --values + +echo "── rebrand: a residue it cannot rename fails the rebrand itself" +tmp="$(mktemp -d)"; git -C "$tmp" init -q; mkdir -p "$tmp/.rebrand" "$tmp/apps/web" +printf '%s\n' "$acme" > "$tmp/.rebrand/values.json" +printf 'const x = "SUPABASE_SLACK_CLONE_TOKEN"\n' > "$tmp/apps/web/x.ts" +git -C "$tmp" add -A +if (cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --values .rebrand/values.json --allow-dirty >/dev/null 2>&1); then + echo " ✕ an unrenamable env-var prefix passed the rebrand" >&2; fail=1 +else + echo " ok an unrenamable env-var prefix fails the rebrand, naming the file" +fi +rm -rf "$tmp" + +[ "$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..1ef5d69 --- /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 .baseline/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 (.baseline/tasks/) 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 "only $hooks retouch hook(s) in repo-blueprint.yaml — 01-product lands the deployable product and needs one" + +[ "$fail" -eq 0 ] || exit 1 +echo "retouch.test.sh: ok" diff --git a/tooling/bootstrap/dev-lanes.mjs b/tooling/bootstrap/dev-lanes.mjs new file mode 100755 index 0000000..4684043 --- /dev/null +++ b/tooling/bootstrap/dev-lanes.mjs @@ -0,0 +1,114 @@ +#!/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. The product's +// landing is a Next.js build per environment; a third, on the dev rung (with +// the two test packages beside it), re-proves what the baseline's own CI +// already proved and competes with stage and prod for the runner pool. (Measured on the Cirrus baseline, +// where this tool comes from: dev took eight of eighteen lanes and stage and +// prod got five each.) +// +// So 01-product defers the trigger and 02-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-product, before the first landing +// node tooling/bootstrap/dev-lanes.mjs --restore # 02-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 +// 02-docs leaves the marker in intent.yaml, and `--restore` (or a re-run of +// 02-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/promotion.mjs b/tooling/bootstrap/promotion.mjs new file mode 100644 index 0000000..ec8f4f5 --- /dev/null +++ b/tooling/bootstrap/promotion.mjs @@ -0,0 +1,123 @@ +#!/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. +// +// So 01-product defers the gate and 02-docs, the last landing, puts it back: +// +// node tooling/bootstrap/promotion.mjs --defer # 01-product, before the first landing +// node tooling/bootstrap/promotion.mjs --restore # 02-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 02-docs +// leaves the marker in intent.yaml, and `--restore` (or a re-run of 02-docs) +// is the whole fix. docs/phases/02-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 100644 index 0000000..c31e99a --- /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 …` lines, duplicated by hand); 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 01-product --affects .baseline/tasks/01-product.TaskContract.yaml +// node retouch.mjs --phase 01-product --components web,db-migrate +// +// 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/web` and `tests/web` both carry one, and only the +// first is named `web`. + +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/bootstrap/work-tree.mjs b/tooling/bootstrap/work-tree.mjs new file mode 100644 index 0000000..ad48ba6 --- /dev/null +++ b/tooling/bootstrap/work-tree.mjs @@ -0,0 +1,73 @@ +#!/usr/bin/env node +// A product carries no work tree of the baseline's (zero-dependency). +// +// This repository's intent.yaml declares where ITS work lives: +// +// work: +// epics: specs/epics +// tasks: tasks +// sync: on-merge +// +// and `orun plan` on main reconciles that tree into the workspace's work +// plane. A product built from this baseline has neither directory — `specs/` and +// `tasks/` are the factory's, and the leak gate keeps them out — and its +// bootstrap work is opened on the platform by the build itself. Left in, the +// block would point the product's every plan at two directories that do not +// exist. +// +// So 01-product removes it from the product's copy, before the first landing: +// +// node tooling/bootstrap/work-tree.mjs --strip # 01-product +// node tooling/bootstrap/work-tree.mjs --check # prints declared | absent +// +// The block removed is the top-level `work:` key with everything indented +// under it, and the comment lines directly above it that belong to it. It is +// not put back: a product that wants a work tree declares its own. Idempotent. +import * as fs from "node:fs"; + +const FILE = process.argv.includes("--file") + ? process.argv[process.argv.indexOf("--file") + 1] + : "intent.yaml"; + +function usage() { + console.error("usage: work-tree.mjs --strip | --check [--file intent.yaml]"); + process.exit(2); +} + +function findWork(lines) { + const start = lines.findIndex((l) => /^work:\s*(#.*)?$/.test(l)); + if (start < 0) return null; + let end = start + 1; + while (end < lines.length && (lines[end].trim() === "" || /^\s/.test(lines[end]))) end++; + // Trailing blank lines belong to the gap before the next key, not the block. + while (end > start + 1 && lines[end - 1].trim() === "") end--; + // Its own comment: the contiguous `#` lines directly above it. + let from = start; + while (from > 0 && /^#/.test(lines[from - 1])) from--; + return { from, end }; +} + +function strip() { + const text = fs.readFileSync(FILE, "utf8"); + const lines = text.split("\n"); + const found = findWork(lines); + if (!found) { + console.log(`work-tree --strip: ${FILE} declares no work tree — nothing to do`); + return; + } + let { from, end } = found; + // Drop one of the blank lines that separated it from its neighbours. + if (end < lines.length && lines[end].trim() === "" && from > 0 && lines[from - 1].trim() === "") end++; + fs.writeFileSync(FILE, [...lines.slice(0, from), ...lines.slice(end)].join("\n")); + console.log(`work-tree --strip: removed the baseline's work tree from ${FILE}`); +} + +function check() { + const lines = fs.readFileSync(FILE, "utf8").split("\n"); + console.log(findWork(lines) ? "declared" : "absent"); +} + +const mode = process.argv[2]; +if (mode === "--strip") strip(); +else if (mode === "--check") check(); +else usage(); diff --git a/tooling/catalog/gen-component-docs.py b/tooling/catalog/gen-component-docs.py new file mode 100644 index 0000000..743782b --- /dev/null +++ b/tooling/catalog/gen-component-docs.py @@ -0,0 +1,550 @@ +#!/usr/bin/env python3 +"""Generate each component's docs (overview / architecture / runbook). + + python3 tooling/catalog/gen-component-docs.py # write + python3 tooling/catalog/gen-component-docs.py --check # fail on drift (CI) + +Every `component.yaml` attaches its `docs/` folder in `spec.docs` (overview, +architecture, runbook), which is what the Orun workspace's Docs library shows +and what the catalog's docs and runbook checks read; a folder nothing declares +is never attached (testing/coverage.test.sh holds the rule). These pages are +generated, not hand-written, because almost +everything in them is already declared somewhere CI validates: the component's +manifest (type, description, dependencies, environments, the secrets a lane +resolves, the smoke), its Worker config (bindings, triggers, the wiring the +deploy fills in), its Terraform (resources and outputs), its migrations and its +package scripts. A hand-written copy of those facts drifts the first time one +changes; a generated one cannot, because `--check` fails the pull request that +changes the fact without the page. + +What is NOT derivable (why a component exists, what a failure means for this +product in particular) belongs in the component's `description` and in the +product's own docs, not here. + +The pages ship with the component into every product built from this tree, so +they say nothing about where they came from: no factory paths, no generator +path, no provenance. Zero dependencies beyond PyYAML. +""" + +from __future__ import annotations + +import json +import pathlib +import re +import sys + +try: + import yaml +except ImportError: # pragma: no cover - the contract job installs it + sys.exit("gen-component-docs needs PyYAML (pip install pyyaml)") + +ROOT = pathlib.Path(__file__).resolve().parents[2] +ROOTS = ("apps", "packages", "infra", "tests") +SKIP_DIRS = {"node_modules", "dist", ".turbo", "docs", ".next", ".open-next", + ".wrangler", ".svelte-kit", ".nuxt", ".output", ".astro", "coverage"} + +# Paths a shipped page must never name: products are not placed with them. +FACTORY = re.compile( + r"repo-blueprint|BOOTSTRAP\.md|(?<![\w.-])(testing|specs|tasks|docs/phases|hooks)/" + r"|\.baseline/|tooling/(rebrand|bootstrap|catalog)/") + + +# ── reading what is declared ───────────────────────────────────────────── + +def strip_jsonc(text: str) -> str: + """JSONC → JSON: drop comments outside strings, then trailing commas.""" + out, i, n, in_str = [], 0, len(text), False + while i < n: + c = text[i] + if in_str: + out.append(c) + if c == "\\" and i + 1 < n: + out.append(text[i + 1]) + i += 2 + continue + if c == '"': + in_str = False + i += 1 + continue + if c == '"': + in_str = True + out.append(c) + i += 1 + elif text.startswith("//", i): + j = text.find("\n", i) + i = n if j < 0 else j + elif text.startswith("/*", i): + j = text.find("*/", i + 2) + i = n if j < 0 else j + 2 + else: + out.append(c) + i += 1 + return re.sub(r",(\s*[}\]])", r"\1", "".join(out)) + + +def read_json(path: pathlib.Path) -> dict | None: + try: + return json.loads(strip_jsonc(path.read_text(encoding="utf-8"))) + except (OSError, ValueError): + return None + + +def rel(p: pathlib.Path) -> str: + return p.relative_to(ROOT).as_posix() + + +def discover() -> list[dict]: + found = [] + for root in ROOTS: + base = ROOT / root + if not base.is_dir(): + continue + stack = [base] + while stack: + d = stack.pop() + for entry in sorted(d.iterdir()): + if entry.is_dir(): + if entry.name in SKIP_DIRS or entry.name.startswith("."): + continue + if (entry / "main.tf").exists() and not (entry / "component.yaml").exists(): + continue + if len(entry.relative_to(base).parts) <= 3: + stack.append(entry) + elif entry.name == "component.yaml": + found.append(read_component(entry)) + comps = [c for c in found if c["name"] and c["type"]] + return sorted(comps, key=lambda c: c["name"]) + + +def read_component(file: pathlib.Path) -> dict: + doc = yaml.safe_load(file.read_text(encoding="utf-8")) or {} + meta, spec = doc.get("metadata") or {}, doc.get("spec") or {} + params = spec.get("parameters") or {} + deps = [d.get("component") for d in (spec.get("dependsOn") or []) if isinstance(d, dict)] + envs = [] + # Secrets may be declared for the whole component or per environment + # (`subscribe.environments[].secretEnv`); a page lists both. + req_env = set((spec.get("secretEnv") or {}).keys()) + opt_env = set((spec.get("optionalSecretEnv") or {}).keys()) + for e in ((spec.get("subscribe") or {}).get("environments") or []): + req_env |= set((e.get("secretEnv") or {}).keys()) + opt_env |= set((e.get("optionalSecretEnv") or {}).keys()) + rules = [(r.get("profile"), ((r.get("when") or {}).get("triggerRef"))) + for r in (e.get("profileRules") or [])] + envs.append({"name": e.get("name"), "profile": e.get("profile"), "rules": rules}) + return { + "dir": file.parent, + "path": rel(file.parent), + "name": meta.get("name"), + "description": (meta.get("description") or "").strip(), + "type": spec.get("type"), + "deps": [d for d in deps if d], + "secret_env": sorted(req_env), + "optional_env": sorted(opt_env - req_env), + "envs": envs, + "params": params, + "migrations_path": spec.get("path") if spec.get("type") == "db-migrate" else None, + } + + +def package_of(c: dict) -> dict | None: + return read_json(c["dir"] / "package.json") + + +def worker_config(c: dict) -> tuple[str | None, dict | None]: + """The config a deploy uses: the template when wiring renders one.""" + names = ["wrangler.template.jsonc", c["params"].get("wranglerConfig") or "", + "wrangler.jsonc", "wrangler.json"] + for name in names: + if name and (c["dir"] / name).is_file(): + return name, read_json(c["dir"] / name) + return None, None + + +WIRING = re.compile(r"@@wiring\(([^/)]+)/__ENV__:([^)]+)\)@@") + + +def wired(value) -> str | None: + m = WIRING.search(str(value)) if value is not None else None + return f"`{m.group(2)}` from `{m.group(1)}`" if m else None + + +def bindings(cfg: dict) -> list[tuple[str, str, str]]: + rows = [] + for kv in cfg.get("kv_namespaces") or []: + rows.append((kv.get("binding"), "Workers KV namespace", wired(kv.get("id")) or "declared in the config")) + for b in cfg.get("r2_buckets") or []: + rows.append((b.get("binding"), "R2 bucket", wired(b.get("bucket_name")) or f"`{b.get('bucket_name')}`")) + for d in cfg.get("d1_databases") or []: + rows.append((d.get("binding"), "D1 database", wired(d.get("database_id")) or "declared in the config")) + for h in cfg.get("hyperdrive") or []: + rows.append((h.get("binding"), "Hyperdrive (pooled Postgres)", wired(h.get("id")) or "declared in the config")) + if isinstance(cfg.get("ai"), dict) and cfg["ai"].get("binding"): + rows.append((cfg["ai"]["binding"], "Workers AI", "account-level; no resource to provision")) + for d in ((cfg.get("durable_objects") or {}).get("bindings") or []): + rows.append((d.get("name"), "Durable Object", f"class `{d.get('class_name')}`")) + for s in cfg.get("services") or []: + rows.append((s.get("binding"), "Service binding", f"Worker `{s.get('service')}`")) + for q in ((cfg.get("queues") or {}).get("producers") or []): + rows.append((q.get("binding"), "Queue producer", f"queue `{q.get('queue')}`")) + for r in cfg.get("ratelimits") or []: + simple = r.get("simple") or {} + rows.append((r.get("name"), "Rate limiter", + f"{simple.get('limit')} requests / {simple.get('period')}s per location")) + assets = cfg.get("assets") or {} + if assets.get("binding"): + rows.append((assets["binding"], "Static assets", f"`{assets.get('directory')}`")) + return [r for r in rows if r[0]] + + +def tf_facts(c: dict) -> dict: + tf_dir = c["dir"] / (c["params"].get("terraformDir") or "terraform") + resources, outputs, variables, backend = [], [], [], None + for f in sorted(tf_dir.glob("*.tf")) if tf_dir.is_dir() else []: + text = f.read_text(encoding="utf-8") + resources += [f"{t}.{n}" for t, n in re.findall(r'^resource\s+"([^"]+)"\s+"([^"]+)"', text, re.M)] + outputs += re.findall(r'^output\s+"([^"]+)"', text, re.M) + variables += re.findall(r'^variable\s+"([^"]+)"', text, re.M) + m = re.search(r'backend\s+"([^"]+)"', text) + backend = backend or (m.group(1) if m else None) + imports = (tf_dir / "adopt.tf").is_file() if tf_dir.is_dir() else False + return {"dir": rel(tf_dir) if tf_dir.is_dir() else None, "resources": resources, + "outputs": outputs, "variables": variables, "backend": backend, "adopt": imports} + + +def published(c: dict) -> list[tuple[str, str]]: + spec = c["params"].get("secretOutputs") or "" + pairs = [] + for part in str(spec).split(","): + if "=" in part: + k, v = part.split("=", 1) + pairs.append((k.strip(), v.strip())) + return pairs + + +def test_files(c: dict) -> list[str]: + out = [] + for p in sorted(c["dir"].rglob("*")): + if any(part in SKIP_DIRS for part in p.relative_to(c["dir"]).parts): + continue + if p.is_file() and re.search(r"\.(test|spec)\.(ts|tsx|js|mjs|cjs)$", p.name): + out.append(p.name) + return out + + +def migrations(c: dict) -> list[str]: + path = c["migrations_path"] + if not path: + return [] + d = ROOT / path + if not d.is_dir(): + return [] + return sorted(p.name for p in d.iterdir() if p.is_dir() or p.suffix == ".sql") + + +# ── markdown ───────────────────────────────────────────────────────────── + +def md_table(header: list[str], rows: list[list[str]]) -> list[str]: + """A table laid out the way prettier lays it out, so a repo whose lint is + `prettier --check` accepts the page as written.""" + cols = len(header) + width = [max(3, len(header[i]), *(len(r[i]) for r in rows)) for i in range(cols)] + def line(cells): + return "| " + " | ".join(c.ljust(width[i]) for i, c in enumerate(cells)) + " |" + return [line(header), "| " + " | ".join("-" * w for w in width) + " |", *(line(r) for r in rows)] + + +# ── phrasing ───────────────────────────────────────────────────────────── + +KIND = { + "cloudflare-worker-turbo": "A Cloudflare Worker, deployed per environment by its CI lane.", + "cloudflare-workers-assets-turbo": "A Cloudflare Worker with Static Assets (server rendering plus " + "static files), deployed per environment by its CI lane.", + "terraform": "Terraform-managed infrastructure, planned and applied per environment by its CI lane.", + "db-migrate": "Applies this repository's ordered database migrations per environment: " + "plan on pull requests, apply on merge to `main`.", + "turbo-package": "A workspace package built by the turbo pipeline. It deploys nothing itself: " + "its lane type-checks, lints, tests and builds it.", +} + +TRIGGER = {"github-push-main": "a push to `main`", "github-pull-request": "a pull request"} + + +def env_line(e: dict) -> str: + s = f"`{e['name']}`: `{e['profile']}`" + for profile, ref in e["rules"]: + s += f", `{profile}` on {TRIGGER.get(ref, f'`{ref}`')}" + return s + + +def is_tests(c: dict) -> bool: + return c["name"].endswith("-tests") or c["path"].startswith("tests/") + + +def subject_of(c: dict, by_name: dict) -> str | None: + if c["name"].endswith("-tests"): + s = c["name"][: -len("-tests")] + return s if s in by_name else None + return None + + +def names_list(c: dict, keep) -> list[str]: + """Secret names a lane resolves, required first; an optional one (from + `optionalSecretEnv`) is resolved when it exists and skipped when not.""" + req = [f"- `{k}`" for k in c["secret_env"] if keep(k)] + opt = [f"- `{k}` (optional)" for k in c["optional_env"] if keep(k)] + return req + opt + + +def bullet_list(names: list[str], by_name: dict) -> list[str]: + if not names: + return ["- (none)"] + out = [] + for n in names: + d = by_name.get(n) + out.append(f"- **{n}** — {d['description']}" if d and d["description"] else f"- **{n}**") + return out + + +# ── pages ──────────────────────────────────────────────────────────────── + +def overview(c: dict, by_name: dict, dependents: list[str]) -> str: + pkg = package_of(c) + kind = KIND.get(c["type"], f"A `{c['type']}` component.") + subject = subject_of(c, by_name) + if is_tests(c): + kind = (f"The test suite for **{subject}**. " if subject else "A test suite. ") + \ + "It deploys nothing: its lane installs, builds and runs the tests." + lines = [f"# {c['name']}", ""] + if c["description"]: + lines += [c["description"], ""] + facts = [["Type", f"`{c['type']}`"], ["Source", f"`{c['path']}`"]] + if pkg and pkg.get("name"): + facts.append(["Package", f"`{pkg['name']}`"]) + if c["envs"]: + facts.append(["Environments", " · ".join(env_line(e) for e in c["envs"])]) + lines += [kind, "", *md_table(["", ""], facts)] + lines += ["", "## Depends on", "", *bullet_list(c["deps"], by_name), + "", "## Depended on by", "", *bullet_list(dependents, by_name), ""] + return "\n".join(lines) + + +def architecture(c: dict, by_name: dict) -> str: + lines = [f"# {c['name']} — architecture", ""] + t = c["type"] + + if t == "terraform": + f = tf_facts(c) + lines += [f"A `terraform` root at `{f['dir'] or c['path']}`.", ""] + if f["backend"] == "http": + lines += ["- **State** lives in the Orun Cloud HTTP state backend — no local state and", + " no state bucket to manage."] + lines += ["- **Credentials are brokered per run** from the workspace's provider", + " connections and resolved by name; none is stored in this repository."] + if f["adopt"]: + lines += ["- **Adoption** (`adopt.tf`): when state is empty but the resource already", + " exists, plan-time import adopts it instead of failing."] + lines.append("") + if f["resources"]: + lines += ["## Resources", "", *[f"- `{r}`" for r in f["resources"]], ""] + pub = published(c) + if pub: + lines += ["## Published outputs", "", + "Written as job-output secrets on each environment after an apply; deploy", + "lanes downstream resolve them by name.", "", + *md_table(["Secret", "Terraform output"], [[f"`{k}`", f"`{v}`"] for k, v in pub]), ""] + elif f["outputs"]: + lines += ["## Outputs", "", *[f"- `{o}`" for o in f["outputs"]], ""] + if c["secret_env"] or c["optional_env"]: + lines += ["## Resolved at run time (names only)", "", *names_list(c, lambda k: True), ""] + return "\n".join(lines) + + if t == "db-migrate": + migs = migrations(c) + lines += [f"Applies the migrations under `{c['migrations_path']}` in order, recording each one", + "it applies so a run only ever applies what is new. An already-applied migration", + "is never edited: a change is a new, later migration.", ""] + if migs: + lines += ["## Migrations", "", *[f"- `{m}`" for m in migs], ""] + if c["secret_env"] or c["optional_env"]: + lines += ["## Resolved at run time (names only)", "", *names_list(c, lambda k: True), ""] + return "\n".join(lines) + + pkg = package_of(c) + if t.startswith("cloudflare-"): + cfg_name, cfg = worker_config(c) + lines += [f"Built by the turbo pipeline from `{c['path']}` and deployed with wrangler.", ""] + if cfg: + facts = [["Worker config", f"`{c['path']}/{cfg_name}`"]] + if cfg.get("main"): + facts.append(["Entry", f"`{cfg['main']}`"]) + if cfg.get("compatibility_date"): + facts.append(["Compatibility date", f"`{cfg['compatibility_date']}`"]) + if cfg.get("compatibility_flags"): + facts.append(["Compatibility flags", ", ".join(f"`{x}`" for x in cfg["compatibility_flags"])]) + lines += [*md_table(["", ""], facts), ""] + rows = bindings(cfg) + lines += ["## Bindings", ""] + if rows: + lines += [*md_table(["Binding", "Kind", "Source"], [[f"`{b}`", k, s] for b, k, s in rows]), ""] + if any("from `" in s for _, _, s in rows): + lines += ["Identifiers marked _from_ a component are filled in at deploy time from", + "that component's published outputs for the environment being deployed.", ""] + else: + lines += ["None: the Worker binds no storage or service.", ""] + crons = (cfg.get("triggers") or {}).get("crons") or [] + if crons: + lines += ["## Scheduled triggers", "", *[f"- `{x}`" for x in crons], ""] + env_names = sorted((cfg.get("env") or {}).keys()) + var_names = sorted((cfg.get("vars") or {}).keys()) + if var_names: + lines += ["## Variables", "", ", ".join(f"`{v}`" for v in var_names) + + (f" — overridden per environment ({', '.join(f'`{e}`' for e in env_names)})." + if env_names else "."), ""] + wiring = names_list(c, lambda k: k.startswith("WIRING_")) + others = names_list(c, lambda k: not k.startswith("WIRING_")) + if wiring: + lines += ["## Wiring", "", + "Resolved at deploy time from secrets the infrastructure lanes publish (names only):", + "", *wiring, ""] + if others: + lines += ["## Secrets resolved by the lane (names only)", "", *others, ""] + return "\n".join(lines) + + # turbo-package + if is_tests(c): + files = test_files(c) + lines += [f"A test package at `{c['path']}`. Its lane runs the suite before it builds.", ""] + if files: + lines += [f"## Suites ({len(files)})", "", *[f"- `{f}`" for f in files], ""] + return "\n".join(lines) + lines += [f"A workspace package at `{c['path']}`, consumed by the components that depend", + "on it. It has no deployed surface of its own.", ""] + if pkg and pkg.get("exports"): + ex = pkg["exports"] + keys = sorted(ex.keys()) if isinstance(ex, dict) else ["."] + lines += ["## Exports", "", *[f"- `{k}`" for k in keys], ""] + return "\n".join(lines) + + +def runbook(c: dict, by_name: dict) -> str: + t = c["type"] + pkg = package_of(c) + lines = [f"# {c['name']} — runbook", "", "## How it runs", ""] + deploys = [e["name"] for e in c["envs"] + if any(ref == "github-push-main" for _, ref in e["rules"])] + if deploys and t in ("terraform", "db-migrate"): + lines += [f"Pull requests plan it; a merge to `main` applies it to " + f"{', '.join(f'`{e}`' for e in deploys)}."] + elif deploys: + lines += [f"Pull requests verify it; a merge to `main` deploys it to " + f"{', '.join(f'`{e}`' for e in deploys)}."] + else: + lines += ["Its lane runs on every pull request that changes it; it has no deployed surface."] + lines += ["CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`;", + "the plan orders a component after everything it depends on.", ""] + + if pkg and pkg.get("scripts"): + name = pkg.get("name") + wanted = [s for s in ("dev", "build", "test", "typecheck", "lint", "preview") if s in pkg["scripts"]] + if name and wanted: + lines += ["## Local commands", "", "```bash", + *[f"pnpm --filter {name} {s}" for s in wanted], "```", ""] + + smoke = c["params"].get("smokeCommand") + if smoke and "No smoke" not in str(smoke): + lines += ["## Verify", "", "After a deploy the lane runs this smoke against the environment it", + "deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL:", "", + "```bash", str(smoke).strip(), "```", ""] + + lines += ["## Rollback", "", + "Revert the commit on `main`. The next convergence applies the previous desired", + "state; nothing was changed out of band, so there is nothing else to undo.", "", + "## Common failures", ""] + if t == "terraform": + lines += ["- **Provider authentication fails**: the workspace's provider connection is", + " missing or revoked. Reconnect it in the console; credentials are brokered", + " from it per run.", + "- **\"Already exists\" on a first apply**: state is empty but the resource is", + " not." + (" `adopt.tf` imports it at plan time; if it still fails, the resource" + " was renamed outside Terraform." if tf_facts(c)["adopt"] else + " Import it, or delete the stray resource, then re-run."), ""] + elif t == "db-migrate": + lines += ["- **An applied migration's file changed**: the run stops rather than guess.", + " Restore the file and write the change as a new migration.", + "- **The database is unreachable**: the infrastructure lane it depends on has", + " not applied for this environment; that lane runs first in a convergence.", ""] + elif t.startswith("cloudflare-"): + _, cfg = worker_config(c) + takes_wiring = any(k.startswith("WIRING_") for k in c["secret_env"] + c["optional_env"]) or \ + bool(cfg and WIRING.search(json.dumps(cfg))) + if takes_wiring: + lines += ["- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream", + " has not applied for this environment yet. Within one convergence the plan", + " runs it first; on its own, re-run that lane."] + lines += ["- **The smoke fails right after a first deploy**: a new workers.dev route can", + " answer 4xx for a few seconds and the lane retries. A failure that persists", + " is a regression in the deployed code.", ""] + else: + lines += ["- **A dependent fails to build after a change here**: run `pnpm typecheck`", + " across the workspace before merging.", ""] + return "\n".join(lines) + + +# ── main ───────────────────────────────────────────────────────────────── + +def main() -> int: + check = "--check" in sys.argv[1:] + comps = discover() + if not comps: + print("no component.yaml found", file=sys.stderr) + return 1 + by_name = {c["name"]: c for c in comps} + dependents: dict[str, list[str]] = {c["name"]: [] for c in comps} + for c in comps: + for d in c["deps"]: + dependents.setdefault(d, []).append(c["name"]) + + drifted, written, leaks = [], 0, [] + for c in comps: + pages = { + "overview.md": overview(c, by_name, sorted(dependents.get(c["name"], []))), + "architecture.md": architecture(c, by_name), + "runbook.md": runbook(c, by_name), + } + for fname, body in pages.items(): + target = c["dir"] / "docs" / fname + for n, line in enumerate(body.splitlines(), 1): + m = FACTORY.search(line) + if m: + leaks.append(f"{rel(target)}:{n} would name {m.group(0)!r}") + current = target.read_text(encoding="utf-8") if target.exists() else None + if current == body: + continue + if check: + drifted.append(rel(target)) + continue + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(body, encoding="utf-8") + written += 1 + + if leaks: + print("✗ a generated page would name a path products do not have:", file=sys.stderr) + for l in leaks: + print(f" {l}", file=sys.stderr) + return 1 + if check: + if drifted: + print(f"✗ {len(drifted)} component doc(s) differ from what the manifests say:", file=sys.stderr) + for f in drifted: + print(f" {f}", file=sys.stderr) + print("\nRun: python3 tooling/catalog/gen-component-docs.py", file=sys.stderr) + return 1 + print(f"✓ component docs match {len(comps)} component.yaml file(s)") + return 0 + print(f"✓ wrote {written} page(s) for {len(comps)} component(s)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tooling/rebrand/rebrand.mjs b/tooling/rebrand/rebrand.mjs new file mode 100644 index 0000000..ccd2fb4 --- /dev/null +++ b/tooling/rebrand/rebrand.mjs @@ -0,0 +1,491 @@ +#!/usr/bin/env node +// Rebrand renamer for the supabase-slack-clone baseline (zero-dependency). +// +// This repository is a baseline: a product is instantiated from it, branded, +// and deployed as somebody's own team chat. This script rewrites every +// *instance identity* literal in the product tree — repo slug (the intent, the +// secret project, the Supabase project names Terraform derives from it), the +// product's display name, the product domain, Cloudflare worker resource +// names (so an instance is account-safe even when it shares an account with +// another), the workers.dev subdomain placeholder (which the Supabase +// project's Auth Site URL is built from too) — to the values in a values +// file, and leaves *org-owned* identity alone (the orun state backend, the +// `sourceplane.io` manifest apiVersion, company mailboxes) and the UPSTREAM +// example's own identity too (where in supabase/supabase the code came from, +// which the READMEs and the licence credit name: not this product). +// +// The engine is Cirrus's (sourceplane/cirrus-baseline tooling/rebrand): the +// FROM side declared in `.baseline/identity.json`, every written value held +// opaque until the last rule has run, and a leftover sweep that fails on any +// identity a rule did not rename. The rules are this tree's. +// +// Usage (from the product root, on a git tree with the files staged): +// node tooling/rebrand/rebrand.mjs --values .rebrand/values.json [--dry-run] [--allow-dirty] +// node tooling/rebrand/rebrand.mjs --verify [--values .rebrand/values.json] +// +// Values file (see tooling/rebrand/values.example.json): +// { +// "reponame": "acme-chat", // required — repo slug +// "productname": "Acme Chat", // required — the product's display name +// "productdomain": "acme.dev", // optional — default <reponame>.example.com (set later) +// "githuborg": "acme-inc", // owner of the product repo (source link in docs) +// "brandSlug": "acme", // default: reponame — worker name prefix +// "subdomain": "acme", // default: your-workers-subdomain +// "orunWorkspace": "ws_XXXXXXXX", // the segment secret refs name +// "orunWorkspaceSlug": "acme-space" // optional: wins over orunWorkspace there +// } +// +// Modes: +// (default) apply the rename map in place, then run the leftover sweep +// --dry-run report per-rule match counts; change nothing +// --verify only run the leftover sweep (non-zero exit on residue) + +import { execFileSync } from "node:child_process"; +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"); + +let values = {}; +// --verify takes --values too, optionally: without them it cannot tell the +// product's own identity from a leftover of the baseline's. +const valuesPath = arg("values"); +if (!verifyOnly && !valuesPath) { + console.error("usage: rebrand.mjs --values <file> [--dry-run] | --verify [--values <file>]"); + process.exit(2); +} +if (valuesPath) { + values = JSON.parse(fs.readFileSync(valuesPath, "utf8")); + for (const required of ["reponame", "productname"]) { + if (typeof values[required] !== "string" || values[required].length === 0) { + console.error(`rebrand: values file is missing required field "${required}"`); + process.exit(2); + } + } +} + +// ── THE BASELINE'S OWN IDENTITY — the FROM side, declared ────── +// +// Read from `.baseline/identity.json` beside THIS SCRIPT, not the working +// directory: the rebrand runs with its cwd set to the PRODUCT being branded, +// and a product does not carry `.baseline/` (no module places it). The phase +// hooks invoke this as `node {{ .baseline.dir }}/tooling/rebrand/rebrand.mjs`, +// so the script's own path is the one thing that always points at the +// baseline. `--baseline-identity <file>` overrides it (the test suite pins one). +// +// slug the repo slug: intent name, worker prefix, secret project, +// the `repo` Terraform names the Supabase project after +// pascal the code-identifier form (swept for, never expected) +// productName the display name, as the SITE_NAME seam spells it +// domain the product domain (BASE_DOMAIN) +// subdomain the workers.dev subdomain this tree carries +// githubOwner the owner in this repository's source link +const BASELINE_IDENTITY_FILE = + arg("baseline-identity") ?? + path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".baseline", "identity.json"); +const BASELINE_DEFAULTS = { + slug: "supabase-slack-clone", + pascal: "SupabaseSlackClone", + productName: "Slack Clone", + domain: "supabase-slack-clone.example.com", + subdomain: "your-workers-subdomain", + githubOwner: "sourceplane", +}; +const baseline = (() => { + let declared = {}; + try { + declared = JSON.parse(fs.readFileSync(BASELINE_IDENTITY_FILE, "utf8")); + } catch { + declared = {}; // absent is fine: the defaults ARE this baseline's identity + } + const id = { ...BASELINE_DEFAULTS }; + for (const k of Object.keys(BASELINE_DEFAULTS)) { + if (declared[k] !== undefined) id[k] = declared[k]; + } + for (const [k, v] of Object.entries(id)) { + if (typeof v !== "string" || v.length === 0) { + console.error(`rebrand: ${BASELINE_IDENTITY_FILE} field "${k}" must be a non-empty string`); + process.exit(2); + } + } + if (/[^a-z0-9-]/.test(id.slug)) { + console.error(`rebrand: ${BASELINE_IDENTITY_FILE} "slug" must be a lowercase slug ([a-z0-9-])`); + process.exit(2); + } + return { ...id, envPrefix: id.slug.toUpperCase().replace(/-/g, "_") }; +})(); +// Regex-escape, for the rules that build a pattern out of the identity. +const rx = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +// All fields are unused under --verify; the fallbacks keep derivation total. +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 githuborg = (values.githuborg ?? "").trim() || baseline.githubOwner; +const brandSlug = (values.brandSlug ?? "").trim() || reponame; +const subdomain = (values.subdomain ?? "").trim() || "your-workers-subdomain"; +// A `secret://<workspace>/<project>/<env>/<KEY>` ref names the WORKSPACE first +// and the project (repo) second. The workspace segment is the product's +// workspace — an explicit slug if one was given, else the ws_… id itself +// (the platform's resolve accepts a slug, a public id or a ws_ ref) — and the +// repo name only as the last resort when no workspace was given at all. +const orunWorkspaceSlug = (() => { + const explicit = (values.orunWorkspaceSlug ?? "").trim(); + if (explicit) return explicit; + const ws = (values.orunWorkspace ?? "").trim(); + if (ws) return ws; + return reponame; +})(); + +if (!verifyOnly && /[^a-z0-9-]/.test(`${reponame}${brandSlug}`)) { + console.error("rebrand: reponame/brandSlug must be lowercase slugs ([a-z0-9-])"); + process.exit(2); +} +if (!verifyOnly && /[^A-Za-z0-9-]/.test(githuborg)) { + console.error("rebrand: githuborg must be a GitHub owner name ([A-Za-z0-9-])"); + 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, this +// tool and the identity it reads, and binary content. +const EXCLUDE_RE = new RegExp( + [ + "^tooling/rebrand/", + "^\\.rebrand/", + // The baseline's declared identity. Renaming its contents would make the + // product claim to be a baseline called by the product's own name. + "^\\.baseline/", + "^pnpm-lock\\.yaml$", + // Migrations are immutable once applied: db-migrate compares each file's + // sha256 to packages/db/src/manifest.ts and to the database's ledger, so + // a byte renamed here would stop every later deploy. (None names this + // baseline's identity; packages/db's tests hold their checksums.) + "^packages/db/src/migrations/", + "\\.(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 (a grounded sandbox checkout carries + // `baseline/` as one) and paths deleted from disk. Only regular files + // are sweepable. + try { + return fs.statSync(f).isFile(); + } catch { + return false; + } + }); +} + +// ── The upstream template's identity (never rewritten) ───────── +// +// This tree IS supabase/supabase's Next.js Slack clone example. Where the +// docs and the licence credit name it — its directory in supabase/supabase, +// whose name spells this baseline's slug (`supabase-slack-clone` is what the +// example's own package and deploy button call it) — they point at the +// example's real home. Protected from every rule and allowed by the leftover +// sweep, so a product's README keeps naming where its code came from instead +// of a repository that does not exist. +// +// ENCLOSING FIRST: the masks are taken in this order and put back in it, so a +// link that CONTAINS another must be masked whole before the one inside it is +// looked for. +const UPSTREAM = [ + /github\.com\/supabase\/supabase\/tree\/master\/examples\/slack-clone\/nextjs-slack-clone\b/g, // the example's home +]; + +// ── Protected literals (org-owned identity, never rewritten) ─── +// +// Masked before the rules run and restored after, so no rename can touch the +// org's shared infrastructure identity. +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 + ...UPSTREAM, +]; +const MASK = (i, j) => `\u0000REBRAND_PROTECTED_${i}_${j}\u0000`; + +// ── Substituted values are opaque ────────────────────────────── +// +// The rules run in sequence over one buffer. If each wrote its VALUE into it, +// every later rule could match that value again — a product whose domain +// contains the baseline's slug would have it renamed a second time by the +// repo-slug rule, and every phase of a bootstrap re-runs this over the whole +// tree. So a rule writes a TOKEN standing for its value, and every token is +// expanded once, after the last rule. A token is NUL, `H<n>`, NUL; its outer +// characters take the word/non-word class of the value's own edges, so a +// later rule's `\b` sees the boundary the value would have given it. +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) => (/\w/.test(c) ? "0" : "\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)]); +} + +// ── Worker resource names ────────────────────────────────────── +// +// Every Cloudflare worker ships prefixed with the slug (`<slug>-<base>`, the +// base being its `apps/<base>/` directory): the component's `workerName`, the +// environment URLs, the deploy smoke. Re-prefix it so an instance's workers +// never collide with another's in a shared account. +function workerBases(files) { + const bases = new Set(); + for (const file of files) { + const m = /^apps\/([^/]+)\//.exec(file); + if (m) bases.add(m[1]); + } + return [...bases]; +} + +// ── Rename map (ordered, most specific first) ────────────────── + +function literalPairs() { + return [ + // This repository's source link, wherever the docs give it. Before the + // repo-slug rule, which would otherwise rename only its tail and leave the + // link pointing at the baseline's owner. + [`github.com/${baseline.githubOwner}/${baseline.slug}`, `github.com/${githuborg}/${reponame}`, "source repository link"], + // The product domain wherever it is the product's (BASE_DOMAIN, docs). + // Before the repo-slug rule: the placeholder domain starts with the slug. + [baseline.domain, productdomain, "product domain"], + // The workers.dev subdomain (component parameters, build origin, intent + // environment URLs, docs). + [baseline.subdomain, subdomain, "workers.dev subdomain"], + ]; +} + +function regexPairs(files) { + const list = [ + // The display-name seam (apps/web/lib/site.ts), which every page's + // <title> and the sign-in page's heading read. JSON.stringify writes a + // valid TS string for any name the card's pattern admits (apostrophes and + // ampersands included). + { + re: new RegExp(`SITE_NAME = "${rx(baseline.productName)}"`, "g"), + replacement: () => `SITE_NAME = ${JSON.stringify(productname)}`, + label: "site name seam", + }, + // Secret refs: `secret://<workspace>/<project>/…`. MUST precede the + // repo-slug pass, which would otherwise rewrite only the project half. The + // workspace segment is ANY segment — a ws_… id or a slug. + { + re: new RegExp(`\\bsecret://[A-Za-z0-9_-]+/${rx(baseline.slug)}/`, "g"), + replacement: () => `secret://${orunWorkspaceSlug}/${reponame}/`, + label: "secret ref workspace/project", + }, + ]; + + const bases = workerBases(files); + if (bases.length > 0) { + // Longest-first so an alternation never matches a shorter prefix of a base. + const wb = bases.slice().sort((a, b) => b.length - a.length).map(rx).join("|"); + list.push({ + re: new RegExp(`\\b${rx(baseline.slug)}-(${wb})\\b`, "g"), + replacement: (_m, base) => `${brandSlug}-${base}`, + label: "worker CF name", + }); + } + + // Repo slug: intent metadata.name and per-env `repo:` params (the Supabase + // projects are named after it), the root package name, docs. Runs AFTER the + // worker pass so `<slug>-<base>` has already been consumed. + list.push({ + re: new RegExp(`\\b${rx(baseline.slug)}\\b`, "g"), + replacement: () => reponame, + label: "repo slug", + }); + return list; +} + +// ── Leftover sweep ───────────────────────────────────────────── +// +// After a rebrand (or under --verify) every remaining baseline-identity +// literal is residue: either org-owned (allowed, masked above) or a missed +// rename (reported, non-zero exit). The pascal form and the env-var prefix +// have no rule because nothing in this tree spells them; they are swept so +// that the first file that does fails here, naming itself, rather than +// shipping the baseline's name. +// +// The placeholder subdomain is residue only when the product changed it — a +// product that kept the placeholder has not deployed yet, and that is not a +// missed rename. Under --verify without values it is skipped for the same +// reason. +const subdomainChanged = !verifyOnly && subdomain !== baseline.subdomain; +const RESIDUE_RE = new RegExp( + (subdomainChanged ? `${rx(baseline.subdomain)}|` : "") + + [ + `\\b${rx(baseline.slug)}\\b`, + `${rx(baseline.slug)}-`, + rx(baseline.pascal), + `${rx(baseline.envPrefix)}_`, + rx(baseline.domain), + ].join("|"), + "g", +); +const ALLOWED_RESIDUE = [ + /https:\/\/orun-api\.sourceplane\.ai/, // orun state backend + /[A-Za-z0-9._%+-]+@sourceplane\.ai/, // company mailboxes + ...UPSTREAM, +]; + +function sweep(files, allowedLiterals = []) { + const residue = []; + for (const file of files) { + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch { + continue; + } + for (const line of text.split("\n")) { + let cleaned = ALLOWED_RESIDUE.reduce((l, re) => l.replace(new RegExp(re.source, "g"), ""), line); + // The rename's own TARGET values: a product legitimately named with the + // baseline's slug inside it is not residue. + for (const lit of allowedLiterals) { + if (lit) cleaned = cleaned.split(lit).join(""); + } + if (new RegExp(RESIDUE_RE.source).test(cleaned)) { + residue.push(`${file}: ${line.trim().slice(0, 120)}`); + } + } + } + return residue; +} + +// ── Main ─────────────────────────────────────────────────────── + +const files = trackedFiles(); +const literals = literalPairs(); +const regexes = regexPairs(files); + +// Every value a rule can write. A value some rule would match again is HELD +// wherever it already stands: every phase of a bootstrap re-runs this over the +// whole tree, so what an earlier phase wrote is input to the next pass and +// must come out of it unchanged. +const produced = [ + ...literals.map(([, to]) => to), + `SITE_NAME = ${JSON.stringify(productname)}`, + `secret://${orunWorkspaceSlug}/${reponame}/`, + reponame, + ...workerBases(files).map((base) => `${brandSlug}-${base}`), +].filter((v, i, all) => v && all.indexOf(v) === i); +const rematchable = (v) => + literals.some(([from]) => v.includes(from)) || regexes.some(({ re }) => new RegExp(re.source).test(v)); +// Longest first, so a held value is never split by a shorter one inside it. +const guarded = produced.filter(rematchable).sort((a, b) => b.length - a.length); +const allowedTargets = produced.filter((to) => new RegExp(RESIDUE_RE.source).test(to)); + +if (verifyOnly) { + const residue = sweep(files, valuesPath ? allowedTargets : []); + if (residue.length > 0) { + console.error(`rebrand --verify: ${residue.length} baseline-identity leftover(s):`); + for (const r of residue) console.error(` ${r}`); + process.exit(1); + } + console.log("rebrand --verify: no baseline-identity leftovers."); + process.exit(0); +} + +const counts = new Map(); +const touched = new Set(); +const count = (label, n = 1) => counts.set(label, (counts.get(label) ?? 0) + n); + +for (const file of files) { + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch { + continue; + } + if (text.includes("\0")) continue; // binary safety net + const original = text; + + const masks = []; + PROTECTED.forEach((re, i) => { + text = text.replace(re, (m) => { + const token = MASK(i, masks.length); + masks.push([token, m]); + return token; + }); + }); + + // What a previous pass already wrote stays as written. + 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)); + count(label, n); + } + for (const { re, replacement, label } of regexes) { + text = text.replace(re, (...m) => { + count(label); + return hold(replacement(...m)); + }); + } + + // Every rule has run; only now do the values it wrote appear. + text = release(text); + for (const [token, value] of masks) text = text.split(token).join(value); + + if (text !== original) { + touched.add(file); + if (!dryRun) fs.writeFileSync(file, text); + } +} + +console.log(`rebrand${dryRun ? " (dry-run)" : ""}: ${touched.size} file(s) affected`); +for (const [label, n] of counts) console.log(` ${String(n).padStart(5)} ${label}`); +if (dryRun) process.exit(0); + +const residue = sweep(trackedFiles(), allowedTargets); +if (residue.length > 0) { + console.error(`rebrand: ${residue.length} baseline-identity leftover(s) after rename:`); + for (const r of residue) console.error(` ${r}`); + process.exit(1); +} +console.log("rebrand: leftover sweep clean."); diff --git a/tooling/rebrand/values.example.json b/tooling/rebrand/values.example.json new file mode 100644 index 0000000..a51fad2 --- /dev/null +++ b/tooling/rebrand/values.example.json @@ -0,0 +1,8 @@ +{ + "reponame": "acme-chat", + "productname": "Acme Chat", + "productdomain": "acme.dev", + "githuborg": "acme-inc", + "subdomain": "acme", + "orunWorkspace": "ws_XXXXXXXX" +}