From cb9f1636415003473239dd8cfedb71067eede749 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 02:07:51 +0000 Subject: [PATCH] SU4: sveltekit-auth becomes an Orun baseline - blueprint.yaml is the console card: inputs, the two brokered Cloudflare secrets and the programme. It quotes 5 minutes, the sum of the phases' estimates (4 + 1). - repo-blueprint.yaml is the build, in sveltekit-boilerplate's one-landing shape. 01-product places, brands and lands the whole site, and one convergence builds it, gives each Worker its AUTH_SECRET and deploys stage and prod side by side. 03-docs records what went live. - The rename keeps Auth.js's own names, which contain the slug: the `SvelteKitAuth` import and call, and sveltekit-auth-example (UPSTREAM in tooling/rebrand/rebrand.mjs). The rebrand and placement tests prove it, along with the ISC licence and the credit. - The deployment record probes /, /signin and /auth/session, and names AUTH_SECRET and the provider keys without their values. - Context pack, generated component docs, BOOTSTRAP.md and docs/phases. - testing/e2e.test.sh builds the stage lane in its own tree: the secret step runs as a verify lane, and no planted value reaches the bundle. It then serves the Worker under `wrangler dev` three times: - with no AUTH_SECRET, the smoke refuses it; - with the secret from `pnpm secret:dev`, every page answers; - with GitHub's keys: the authorize URL with PKCE; a session sealed with the Worker's secret opens /protected; one sealed with another secret is refused; sign-out clears it. Every tier is green locally: contract, docs --check, catalog validate, --status, leak, placement and e2e. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_019PcpNVpFBcbeiX3EHdXfmn --- .baseline/identity.json | 9 + .baseline/product/README.md | 171 +++++ .baseline/tasks/01-product.TaskContract.yaml | 25 + .baseline/tasks/03-docs.TaskContract.yaml | 13 + .github/workflows/baseline.yml | 136 ++++ .github/workflows/tag.yml | 97 +++ BOOTSTRAP.md | 227 ++++++ README.md | 55 +- ai/context/current.md | 43 ++ ai/context/decisions.md | 20 + ai/context/deployment.md | 7 + ai/context/open-risks.md | 15 + ai/context/operations.md | 146 ++++ apps/web/docs/architecture.md | 39 ++ apps/web/docs/overview.md | 20 + apps/web/docs/runbook.md | 38 + blueprint.yaml | 156 +++++ docs/phases/01-product.md | 87 +++ docs/phases/03-docs.md | 39 ++ docs/phases/README.md | 118 ++++ hooks/render-deployment-docs.sh | 153 ++++ repo-blueprint.yaml | 663 ++++++++++++++++++ specs/epics/README.md | 2 +- .../sveltekit-auth/IMPLEMENTATION-STATUS.md | 8 +- specs/epics/sveltekit-auth/README.md | 2 +- specs/epics/sveltekit-auth/epic.yaml | 2 +- testing/bootstrap-defer.test.sh | 67 ++ testing/coverage.test.sh | 264 +++++++ testing/e2e.test.sh | 426 +++++++++++ testing/fixtures/acme.json | 22 + .../baseline-identity.sveltekit-auth.json | 9 + testing/leak.test.sh | 118 ++++ testing/lib/bootstrap.sh | 71 ++ testing/lib/run-hooks.py | 72 ++ testing/lib/stage-job.py | 84 +++ testing/manifest.test.sh | 446 ++++++++++++ testing/phases.test.sh | 338 +++++++++ testing/placement.test.sh | 287 ++++++++ testing/rebrand.test.sh | 190 +++++ 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/migrations/manifest.mjs | 42 ++ tooling/rebrand/rebrand.mjs | 485 +++++++++++++ tooling/rebrand/values.example.json | 8 + 48 files changed, 6521 insertions(+), 12 deletions(-) create mode 100644 .baseline/identity.json create mode 100644 .baseline/product/README.md create mode 100644 .baseline/tasks/01-product.TaskContract.yaml create mode 100644 .baseline/tasks/03-docs.TaskContract.yaml create mode 100644 .github/workflows/baseline.yml create mode 100644 .github/workflows/tag.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 apps/web/docs/architecture.md create mode 100644 apps/web/docs/overview.md create mode 100644 apps/web/docs/runbook.md create mode 100644 blueprint.yaml create mode 100644 docs/phases/01-product.md create mode 100644 docs/phases/03-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 100755 testing/e2e.test.sh create mode 100644 testing/fixtures/acme.json create mode 100644 testing/fixtures/baseline-identity.sveltekit-auth.json create mode 100755 testing/leak.test.sh create mode 100755 testing/lib/bootstrap.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 100755 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/migrations/manifest.mjs 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..6c9ca2d --- /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/src/site.ts (upstream's own heading, 'SvelteKit Auth Example'); `pascal` is also the name of Auth.js's `SvelteKitAuth`, which the engine protects where the app imports and calls it (UPSTREAM in rebrand.mjs); `domain` and `subdomain` are placeholders, because this baseline has never deployed under a name of its own; `githubOwner` is the owner in the repository's source links.", + "slug": "sveltekit-auth", + "pascal": "SvelteKitAuth", + "productName": "SvelteKit Auth Example", + "domain": "sveltekit-auth.example.com", + "subdomain": "your-workers-subdomain", + "githubOwner": "sourceplane" +} diff --git a/.baseline/product/README.md b/.baseline/product/README.md new file mode 100644 index 0000000..ca51f13 --- /dev/null +++ b/.baseline/product/README.md @@ -0,0 +1,171 @@ +# sveltekit-auth + +A SvelteKit site whose sign-in is [Auth.js](https://authjs.dev) — a home +page, a sign-in page, a page only a signed-in visitor can read, and a +sign-out — on **Cloudflare Workers + Static Assets** through SvelteKit's own +[`@sveltejs/adapter-cloudflare`](https://svelte.dev/docs/kit/adapter-cloudflare). +Sessions are Auth.js's encrypted JWT cookies: there is no database to run. + +It is Auth.js's SvelteKit example, ported to Cloudflare. +Upstream: https://github.com/nextauthjs/sveltekit-auth-example (ISC, +© 2022-2024 Balázs Orbán; the licence is `apps/web/LICENSE`). + +## Live deployment + + +Not recorded yet. The bootstrap's last phase writes the live URLs, the +workspace and the secrets the site uses into +[ai/context/deployment.md](ai/context/deployment.md); how the site deploys +and how to operate it is in +[ai/context/operations.md](ai/context/operations.md). + + +## What is here + +| Surface | Where | +|---|---| +| The site's name (the home page's heading, every page's ``) | `apps/web/src/site.ts` | +| `/` (home), `/signin`, `/protected`, `/signout` | `apps/web/src/routes` | +| Auth.js: the configuration, built per request from the Worker's secrets | `apps/web/src/auth.ts`, `apps/web/src/hooks.server.ts` | +| The 26 sign-in providers and the keys each needs | `apps/web/src/server/providers.ts` | +| The header (who is signed in, sign in and out) and the footer | `apps/web/src/components` | +| The deploy step that gives each Worker its secrets | `tooling/wire/worker-secrets.mjs` | +| Workers build and deploy contract | `apps/web/svelte.config.js`, `apps/web/wrangler.jsonc`, `apps/web/component.yaml` | +| Tests (the providers and their keys, the site's name, the secrets step) | `apps/web/src/**/*.test.ts` (vitest) | + +## Getting started + +```bash +pnpm install # runs `svelte-kit sync` +pnpm typecheck # svelte-check +pnpm lint # prettier --check +pnpm test # vitest +pnpm build # vite build → apps/web/.svelte-kit/cloudflare (_worker.js + the static output) +``` + +```bash +pnpm --filter @app/web secret:dev # writes a generated AUTH_SECRET into apps/web/.env (git-ignored) +pnpm --filter @app/web dev # http://localhost:3000 +pnpm --filter @app/web preview # wrangler dev over the built Worker, http://localhost:8787 +``` + +Both read `apps/web/.env`: copy `apps/web/.env.example`, the example's +own, for every key the site can take. Without an +AUTH_SECRET Auth.js refuses every request with a server-configuration +error, so run `secret:dev` once; a second run keeps the secret it wrote. + +Make the site yours in `apps/web/src/routes` (the pages) and +`apps/web/src/site.ts` (its name). A page reads the visitor's session from +`$page.data.session` (the root layout loads it with `event.locals.auth()`), +as `/protected` does. + +## Sign-in providers + +The site deploys with no provider connected, and `/signin` says so and +lists what each one needs. A provider is offered once **every** key it +takes is set; the others are never shown. For GitHub: + +1. Create an OAuth app (GitHub → Settings → Developer settings → OAuth + Apps). Its callback URL is the site's `/auth/callback/github`: + `https://sveltekit-auth-web-prod.<subdomain>.workers.dev/auth/callback/github` + for prod (one app per environment, or one per origin you serve). +2. Store its client id and secret as this repository's Orun secrets for + that environment (or on the console's Secrets page): + + ```bash + orun secrets set AUTH_GITHUB_ID --env prod # prompts for the value + orun secrets set AUTH_GITHUB_SECRET --env prod + ``` + + The build never sees them; the deploy hands them to the Worker as + Worker secrets (`wrangler secret bulk`, over stdin), so they are in no + bundle, no build cache and no log. +3. Redeploy (a merge, or **Deploy by hand** below). The deploy pushes the + keys to the Worker, and the GitHub button appears. + +The deploy pushes the keys of the providers upstream's `.env.example` +names, when they are set: + +| Provider | Keys | +|---|---| +| GitHub | `AUTH_GITHUB_ID`, `AUTH_GITHUB_SECRET` | +| Google | `AUTH_GOOGLE_ID`, `AUTH_GOOGLE_SECRET` | +| Discord | `AUTH_DISCORD_ID`, `AUTH_DISCORD_SECRET` | +| LinkedIn | `AUTH_LINKEDIN_ID`, `AUTH_LINKEDIN_SECRET` | +| Facebook | `AUTH_FACEBOOK_ID`, `AUTH_FACEBOOK_SECRET` | +| Twitter | `AUTH_TWITTER_ID`, `AUTH_TWITTER_SECRET` | +| Twitch | `AUTH_TWITCH_ID`, `AUTH_TWITCH_SECRET` | +| Pinterest | `AUTH_PINTEREST_ID`, `AUTH_PINTEREST_SECRET` | +| Auth0 | `AUTH_AUTH0_ID`, `AUTH_AUTH0_SECRET`, `AUTH_AUTH0_ISSUER` | + +The other seventeen of the example's providers (Apple, Azure AD B2C, BoxyHQ +SAML, Cognito, Coinbase, Dropbox, GitLab, HubSpot, Keycloak, Netlify, Okta, +Passage, Reddit, Slack, Spotify, WorkOS, Zoom) work the same way; their keys +are in `apps/web/src/server/providers.ts`. Set them in `apps/web/.env` locally. +To deploy one, add its keys to `optionalSecretEnv` in +`apps/web/component.yaml` and to the `--secret` list in that file's +`buildCommand`, or set them on the Worker directly +(`pnpm --filter @app/web exec wrangler secret put AUTH_GITLAB_ID --name sveltekit-auth-web-prod`): +a Worker keeps its secrets from one deploy to the next. + +## Sessions and AUTH_SECRET + +A session is Auth.js's default: a JWT, encrypted with `AUTH_SECRET`, in an +httpOnly `authjs.session-token` cookie (`__Secure-` prefixed over HTTPS). +Nothing about a visitor is stored anywhere else. The upstream example has +no database adapter, and none is added. + +Each environment's Worker gets its own AUTH_SECRET from its first deploy: +the deploy lane's build step (`tooling/wire/worker-secrets.mjs`) lists the +secrets the Worker carries, generates one only if it carries none, and +pushes it with `wrangler secret bulk` over stdin. Every later deploy keeps +it, so sessions survive deploys. It is never in the repository, a log or +the build. To set your own, store an Orun secret named `AUTH_SECRET` for +the environment (`orun secrets set AUTH_SECRET --env prod`); the next deploy +pushes it. Changing it signs everyone out, +since a session sealed with the old secret no longer opens. + +## How it deploys + +Merges to `main` converge through Orun: `.github/workflows/ci.yml` plans the +changed components and runs each lane against the workspace in +`intent.yaml`. The site deploys to `stage`, then to `prod` once stage has +converged on the same commit; `dev` only verifies. The Worker is +`sveltekit-auth-web-<env>` on your account's workers.dev subdomain. Each +deploy builds the site, gives the Worker its secrets, deploys it, and is +smoke-tested over HTTP: the home page must render and Auth.js's +`/auth/session` must answer `null`, which it does only once the Worker has +its AUTH_SECRET. A pull request runs the same pipeline's verify lanes: the +site built and dry-deployed for each environment, with nothing deployed and +no secret pushed. They do not lint or run the tests, so run +`pnpm typecheck`, `pnpm lint` and `pnpm test` before you push. + +The pipeline holds one credential, GitHub's own `GITHUB_TOKEN`. The +Cloudflare token and account id are brokered per run from the workspace's +Cloudflare connection; the providers' keys are the site's own secrets in +the workspace. Nothing provider-shaped is stored in the repository or in +GitHub. + +**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 storing a +provider's keys, say. A component with nothing to run in that environment +(a test suite in `prod`) is left out with a notice. + +## Custom domain + +The site answers on workers.dev from its first deploy. To serve it on your +own domain, add the domain to the Cloudflare account the site deploys into +and attach it to the Worker (dashboard → Workers & Pages → +`sveltekit-auth-web-prod` → Settings → Domains & Routes → Add → Custom +domain). Do the same for stage with a subdomain if you want one. + +Auth.js trusts the host a request arrives on (`trustHost: true`), so +sign-in works on the new origin with no change to the code: add the new +origin's `/auth/callback/<provider>` to each OAuth app. The repository +names the domain in one place, `BASE_DOMAIN` in `intent.yaml` (dev, stage +and prod), which the site was born with as the reserved placeholder +`sveltekit-auth.example.com`. Replace it with your domain in the same +change that records it. diff --git a/.baseline/tasks/01-product.TaskContract.yaml b/.baseline/tasks/01-product.TaskContract.yaml new file mode 100644 index 0000000..a6c0b87 --- /dev/null +++ b/.baseline/tasks/01-product.TaskContract.yaml @@ -0,0 +1,25 @@ +# 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 site in one landing. `affects` names COMPONENTS, by +# metadata.name: the phase's retouch hook reads this list to decide which +# component.yaml files get the redeploy marker, so the deploy set and the task +# plane's statement of the work are one list. The site is one component — its +# test runs inside it (vitest in apps/web), so there is no separate test +# package to redeploy. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The site's repository is born and linked, the whole site lands in one pull request, and one convergence builds it with @sveltejs/adapter-cloudflare, gives each environment's Worker its AUTH_SECRET and deploys it to stage and prod, its tests green + affects: + - web + doneWhen: + - repo pushed, main pinned as default, workspace linked (orun cloud link) + - main convergence green (build, deploy and smoke on stage and prod) + - the home page answers on both workers.dev URLs, and Auth.js's /auth/session answers there + gates: [] diff --git a/.baseline/tasks/03-docs.TaskContract.yaml b/.baseline/tasks/03-docs.TaskContract.yaml new file mode 100644 index 0000000..c8f2ba1 --- /dev/null +++ b/.baseline/tasks/03-docs.TaskContract.yaml @@ -0,0 +1,13 @@ +# Task contract template for the 03-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 site's repo + affects: + - ai/context/deployment.md + - ai/context/operations.md + - README.md + 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..420017c --- /dev/null +++ b/.github/workflows/baseline.yml @@ -0,0 +1,136 @@ +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, and that +# the site it produces installs, builds, deploys (dry) and serves. +# +# ─── WHY THIS IS NOT IN ci.yml ──────────────────────────────────────────── +# +# `repo-blueprint.yaml`'s `github-workflows` module copies the WHOLE `.github` +# directory into every site built from this repository. These jobs run +# `testing/*.sh`, and `testing/` is deliberately not placed — so in a site 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 site'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 site would carry) and the placement + # tier (the offline bootstrap: every phase placed and finished by the + # blueprint's own hooks, then the site's own `orun plan` for the 01-product + # merge). + 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-notes \ + --set "productname=Acme Notes" \ + --set githuborg=acme-inc + - name: the leak gate — what a site carries + run: bash testing/leak.test.sh + - name: placement — the offline bootstrap, and the site'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 SITE IT PRODUCES WORKS: the finished site installed, its + # fixtures rendered, type-checked, linted, tested and built, the stage + # lane's own build, output check and dry deploy, and the built Worker served + # and smoke-tested with the component's own smoke command. Pinned at the + # bootstrap floor (v2.88.0): the offline bootstrap reads the blueprint (its + # one `secrets` reconcile, its background task set-up, its landings checked + # in the box), and the floor is newer than the site's lane pin (v2.78.4), + # which is all the lane steps need. + site: + 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 site builds, deploys (dry) and serves + 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/.github/workflows/tag.yml b/.github/workflows/tag.yml new file mode 100644 index 0000000..c0383e3 --- /dev/null +++ b/.github/workflows/tag.yml @@ -0,0 +1,97 @@ +name: Baseline tag + +# CUTS A `baseline-vN` TAG FOR THIS REPOSITORY. +# +# A baseline tag is what the platform's registry resolves and what every +# product bootstrapped from this repository is built out of, so it is cut by a +# workflow rather than by hand: the version must look like a baseline tag, an +# existing tag is never moved, and the commit is resolved here, once. +# +# Whether a commit is fit to release is decided outside this repository, by +# whoever cuts the tag; nothing here asks for proof beyond a green `main`. + +on: + workflow_dispatch: + inputs: + version: + description: "The tag to cut, e.g. baseline-v2." + required: true + type: string + ref: + description: "Branch, tag or sha to cut it from. Defaults to main." + required: false + default: main + type: string + +concurrency: + group: baseline-tag + cancel-in-progress: false + +permissions: + contents: read + +jobs: + cut: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v6 + with: + # Full history: the ref being cut from may be any commit, and a + # shallow clone cannot resolve one it did not fetch. + fetch-depth: 0 + ref: ${{ inputs.ref }} + + - name: the version must look like a baseline tag + run: | + set -euo pipefail + # Refused here rather than by the API, because the API's error for a + # malformed ref says nothing about the convention it broke. + case "${{ inputs.version }}" in + baseline-v[0-9]*) ;; + *) echo "✕ '${{ inputs.version }}' is not a baseline-vN tag" >&2; exit 1 ;; + esac + + - name: resolve the commit + id: commit + run: | + set -euo pipefail + sha="$(git rev-parse HEAD)" + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "Cutting ${{ inputs.version }} from ${{ inputs.ref }} = $sha" + + - name: the tag must not already exist + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + code="$(curl -sS -o /dev/null -w '%{http_code}' \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/git/ref/tags/${{ inputs.version }}")" + if [ "$code" = "200" ]; then + echo "✕ ${{ inputs.version }} already exists. A baseline tag is never moved:" >&2 + echo " products resolve it, and repointing one changes what a build that" >&2 + echo " already shipped was made of. Cut the next number." >&2 + exit 1 + fi + # Anything other than 200 or 404 means the question was not answered, + # and "it probably does not exist" is not a thing to guess about a + # tag that is about to be created. + [ "$code" = "404" ] || { echo "✕ could not check for the tag (HTTP $code)" >&2; exit 1; } + + - name: cut the tag + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + curl -sS -X POST --fail-with-body \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/git/refs" \ + -d "$(printf '{"ref":"refs/tags/%s","sha":"%s"}' \ + "${{ inputs.version }}" "${{ steps.commit.outputs.sha }}")" + echo "" + echo "✓ ${{ inputs.version }} → ${{ steps.commit.outputs.sha }}" + echo " Next: move the registry row in orun-cloud's infra/baselines-registry/baselines.yaml." diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md new file mode 100644 index 0000000..129801e --- /dev/null +++ b/BOOTSTRAP.md @@ -0,0 +1,227 @@ +# BOOTSTRAP — a new site from this baseline, in phases + +How to go from **nothing** to a **SvelteKit site with Auth.js sign-in, live +on stage and prod, documented**, with ONE provider consent and nothing typed. + +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 five minutes** — an estimate summed from the +phases (4 + 1) until a bootstrap measures it. The shape is +sveltekit-boilerplate's: 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), one SvelteKit build per environment (seconds, not +minutes — the long poles are the installs, the runners and a first deploy's +workers.dev route), stage and prod deployed side by side, then a short docs +landing, checked the same way, that restores the promotion gate. This site +adds one step to each deploy lane — `wrangler secret list`, then one +`wrangler secret bulk` that gives the Worker its generated AUTH_SECRET (and +creates it, on the first deploy) — and a minute is budgeted for it. +sveltekit-boilerplate's estimate of the same shape (3 + 1) is unmeasured +too: the sibling site baselines measured 7m07s–8m43s from the console's +Build over three landings, and `01-product` dropped one landing and the +Checks waits (cirrus-baseline baseline-v22's shape). + +## 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, + landings that commit per phase, `githubOwner` on the doctor probe, a probe + deferred for a project not yet created, `from: workspace`, the deploy + credentials minted in one `secrets` reconcile, the task set-up run in the + background (`background: true`), and landings checked in the box before + they merge (`checks: local`)). The site's own `ci.yml` pins its lanes + separately (v2.78.4). +- A Cloudflare account (the free plan is enough for one Worker with static + assets) and its **Account API token** with Workers Scripts Write (the + console's Connect recipe lists the exact permission groups). It is the ONLY + provider credential this baseline needs. +- An Orun Cloud workspace for the site — `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. + +## 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/sveltekit-auth +cd sveltekit-auth + +orun new --blueprint repo-blueprint.yaml \ + --out ~/sites/acme-notes --run-hooks --resume \ + --set reponame=acme-notes --set productname="Acme Notes" \ + --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 token +is minted from. Only a hand-run build like this one passes it. + +**`--run-hooks` is the difference between placing files and bootstrapping a +site.** 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 site's identity. + +## 1b. Or phase by phase + +| phase | what it lands | verified by | +|---|---|---| +| `01-product` | the repository, created and linked; the brokered Cloudflare secrets; then the whole site in one PR — intent, CI, tooling, identity, `apps/web` (the site and its tests) | its commit validated and planned in the box (as the PR and as the merge), then merged; the convergence green (build, deploy, smoke) and both workers.dev URLs answering | +| `03-docs` | `ai/context/deployment.md` from probed facts; 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 ~/sites/acme-notes --run-hooks \ + --phase 01-product --values ~/acme-notes.values.yaml +# … then 03-docs +``` + +Every later phase 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 +site 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 site 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 site is PRODUCT-ONLY: the app (its tests inside it), its +CI, its tooling, its README 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, nor does `tooling/migrations` (the D1 manifest +check for a database the site does not have). That promise is a test: +`testing/leak.test.sh` derives what every phase would place and gates the +set, 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/sveltekit-auth +cd sveltekit-auth +orun new --blueprint repo-blueprint.yaml \ + --out /work/acme-notes --run-hooks --resume --progress json \ + --values /work/acme-notes.values.yaml +``` + +| requirement | detail | +|---|---| +| `GITHUB_TOKEN` | fine-grained PAT: **read** on this repository; on the SITE'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 site is live + +- **Write**: the pages are `apps/web/src/routes/`; the site's name is + `apps/web/src/site.ts`. Every merge to `main` redeploys. +- **Connect a sign-in provider**: the site deploys with none, and `/signin` + says so. Create an OAuth app (GitHub: callback + `https://<reponame>-web-<env>.<subdomain>.workers.dev/auth/callback/github`), + store its two keys as the site's secrets for that environment + (`orun secrets set AUTH_GITHUB_ID --env <env>`, then `AUTH_GITHUB_SECRET`, + or the console's Secrets page), and redeploy (a merge, or `ci.yml`'s Run workflow): + the deploy pushes them to the Worker and the button appears. The site's + README, "Sign-in providers", lists every provider's keys. +- **AUTH_SECRET** is generated on each environment's Worker by its first + deploy and kept by every later one; nobody types or sees it. Storing an + Orun secret named `AUTH_SECRET` replaces it on the next deploy, which + signs every visitor out (sessions sealed with the old one no longer + open). +- **Custom domain**: attach it to the Worker in Cloudflare, and replace the + placeholder `<reponame>.example.com` in `intent.yaml`'s `BASE_DOMAIN` with + it (the site's README, "Custom domain"); nothing else changes, because the + site builds no absolute links. 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 03-docs`; it is idempotent. + +## 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 +bash testing/e2e.test.sh # + network for pnpm: the site built, dry-deployed and served +``` + +The offline bootstrap (`testing/lib/bootstrap.sh`) places every phase in +order and finishes each with the blueprint's OWN `run:` hooks — read out of +`repo-blueprint.yaml`, not transcribed — so the rebrand, the re-tenant, the +deferrals and their restore, the retouch marker and the deployment record +all run exactly as a real bootstrap runs them. Only the +platform's typed actions (task, repo, link, land, watch, probe, reconcile) +are stood in for, a landing becoming a commit. + +## 5. Cutting a baseline tag (maintainers) + +Every site 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 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` 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 | +| `01-product` waits on the `providers` probe, then stops | Cloudflare is not connected. Connect it (console → Integrations), then re-run the phase — the probe is a wait, not a failure | +| Secret WRITE fails `not_found` while listings work | the API key's role is below admin; re-mint it with the admin role | +| Deploy lane: Authentication error (10000) | the connection's token lacks Workers Scripts Write; re-issue it, re-connect, re-run `01-product` | +| `land` stops: `the landing's own check failed — orun plan for …` | the site'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 site'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 | +| 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 site redeploys | +| The site'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 `03-docs`; prod no longer waits on stage | the gate is deferred, not dropped: run `03-docs`, or `node tooling/bootstrap/promotion.mjs --restore --file <site>/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 | +| `01-product` lanes fail in `build-app` resolving a dependency | the site's intent no longer pins stack-tectonic 0.19.0. 0.20.0's lane-scoped install links each job's node_modules out of its staged tree; this site's Vite build was tried there and builds, but a Next.js sibling's did not, and the pin keeps the install the e2e tier proves. `intent.yaml` says why | +| A deploy lane's smoke fails on `/auth/session` (500, `MissingSecret` in the Worker's log) | the Worker has no AUTH_SECRET because its `build-app` step did not push one; resume the convergence. If `build-app` says `refusing to mint a replacement`, `wrangler secret list` failed for another reason than a missing Worker (the token, the API): nothing was pushed, and no session was lost | +| `01-product`'s convergence reported green, then `verify` got 404 from both URLs | 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, and a site carries no other workflow (`testing/coverage.test.sh` holds the rule); read the CI run on main for the real result | diff --git a/README.md b/README.md index d7736f7..82e86a0 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,8 @@ Auth.js's [SvelteKit example](https://github.com/nextauthjs/sveltekit-auth-examp sign-out, over [`@auth/sveltekit`](https://authjs.dev/reference/sveltekit) with the example's 26 OAuth providers — running on **Cloudflare Workers + Static Assets** through SvelteKit's own -[`@sveltejs/adapter-cloudflare`](https://svelte.dev/docs/kit/adapter-cloudflare). -It is being packaged as an **Orun baseline** that takes a new site from +[`@sveltejs/adapter-cloudflare`](https://svelte.dev/docs/kit/adapter-cloudflare), +and packaged as an **Orun baseline**: one command takes a new site from nothing to live on stage and prod, in its own repository, under its own name, in ONE landing. @@ -14,12 +14,52 @@ Sessions are the example's: Auth.js's encrypted JWT cookie, so there is no database. Each provider is offered once its keys are stored as the site's secrets, so the site goes live with none connected and its sign-in page says what to connect; the AUTH_SECRET that seals the sessions is generated -on each environment's Worker by its first deploy, so nothing is typed. The -design, the milestones and the as-built status are in +on each environment's Worker by its first deploy, so nothing is typed. What +the baseline adds is everything needed to make a copy of it somebody +else's, built the way [cirrus-baseline](https://github.com/sourceplane/cirrus-baseline) +is. The design, the milestones and the as-built status are in [`specs/epics/sveltekit-auth`](specs/epics/sveltekit-auth/README.md). ISC, © 2022-2024 Balázs Orbán (`apps/web/LICENSE`). -## What is here +## Instantiating a site + +```bash +git clone --depth 1 --branch <baseline-tag> https://github.com/sourceplane/sveltekit-auth +cd sveltekit-auth +orun new --blueprint repo-blueprint.yaml --out ~/sites/acme-accounts --run-hooks --resume \ + --set reponame=acme-accounts --set productname="Acme Accounts" \ + --set githuborg=acme-inc --set subdomain=<workers-dev-subdomain> +``` + +Or, once the platform's registry lists it, from the Orun console (Baselines → +`sveltekit-auth` → Build). Two phases: **`01-product`** creates the +repository and lands the whole site as ONE pull request — intent, CI, +tooling, the site and its tests — and one convergence builds it, gives each +environment's Worker its AUTH_SECRET and deploys it to stage and prod; +**`03-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 new repository receives the **site only** — the app and its tests, its +CI, its tooling, a README of its own and its operating contract — renamed +throughout to the site's name, repository and Cloudflare Worker, with +Auth.js's own names (`SvelteKitAuth`, `sveltekit-auth-example`) and the +example's licence left as they are. 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, and the bootstrap's task contracts | `.baseline/` | +| The rename engine | `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 site's README and context pack | `.baseline/product/README.md`, `ai/context/` | +| The baseline's tests: contract, leak, offline bootstrap, end to end | `testing/`, `.github/workflows/baseline.yml` | +| Cutting a `baseline-vN` tag | `.github/workflows/tag.yml` | + +## What is here (the site) | Surface | Where | |---|---| @@ -76,7 +116,7 @@ optional Orun secrets per environment (`orun secrets set AUTH_GITHUB_ID --env stage`), pushed to the Worker by its next deploy; the OAuth app's callback URL is `<origin>/auth/callback/<provider>`. The component carries secret refs for the nine providers upstream's `.env.example` names; the -keys of every other provider are in `apps/web/src/server/providers.ts`. +site's README ("Sign-in providers") says how to deploy the others. ## How it maps to Vercel @@ -89,9 +129,12 @@ keys of every other provider are in `apps/web/src/server/providers.ts`. | `$env/dynamic/private` from the platform's env | the Worker's bindings (`platform.env`), read per request; `.env` locally, as upstream, for `vite dev` and `wrangler dev` alike | | sessions: Auth.js's JWT cookie | the same; no database | | Deploy on push | Orun deploys `<repo>-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`), smoke-tested | +| "Deploy with Vercel" (clone the example) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, deployed | ## CI | Workflow | What it runs | Ships to a site | |---|---|---| | `ci.yml` | the Orun pipeline, and the only workflow a site carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the site built and dry-deployed per environment, no secret pushed; they do not typecheck, lint or run the tests), except the bootstrap's own landings (`orun/BASE-*`), where `plan` alone is the check; a merge 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 with the site's own plan, the site installed, type-checked, linted, tested, built and dry-deployed in the lane's tree and served — with no secret (the smoke refuses it), with one (every page), and with GitHub's keys (the authorize URL, a session, sign-out) (`testing/e2e.test.sh`, before every tag) | no | +| `tag.yml` | cuts a `baseline-vN` tag (manual) | no | diff --git a/ai/context/current.md b/ai/context/current.md new file mode 100644 index 0000000..c957ae3 --- /dev/null +++ b/ai/context/current.md @@ -0,0 +1,43 @@ +# sveltekit-auth — 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 site built from it; the +two pages that do are [operations.md](operations.md) and +[deployment.md](deployment.md). + +## What it is + +Auth.js's SvelteKit example (nextauthjs/sveltekit-auth-example, ISC) — a +home page, a sign-in page, a protected page and a sign-out over +`@auth/sveltekit`, with the example's 26 OAuth providers, each offered once +its keys are stored — on SvelteKit 2 and Svelte 5, deployed as one +Cloudflare Worker + Static Assets through SvelteKit's own Cloudflare +adapter. Sessions are Auth.js's encrypted JWT cookies; there is no database. +The AUTH_SECRET is generated on each environment's Worker by its first +deploy. Packaged as an Orun baseline: `orun new --blueprint +repo-blueprint.yaml` builds a new site in its own repository and takes it to +live on stage and prod in one landing (`01-product`), then records what went +live (`03-docs`). + +## Release + +| | | +|---|---| +| Latest tag | `baseline-v1` (SU0, SU1, SU3, SU4: the auth app on Workers, its secret generated by the deploy, providers optional, the one-landing baseline) | +| Proven live | No. Everything short of the platform is proven offline in Baseline CI: the stage lane's build and dry deploy in the lane's own tree, then the built Worker under `wrangler dev` with no secret (the smoke refuses it), with one (every page), and with GitHub's keys (the authorize URL, a session sealed with the Worker's secret, sign-out). A live bootstrap from a tag is still to come (risk SU-A). The card's 5 minutes is an estimate | + +## Where to read + +| Question | Page | +|---|---| +| What shipped, and every departure from upstream | `specs/epics/sveltekit-auth/IMPLEMENTATION-STATUS.md` | +| Why it is built this way | [decisions.md](decisions.md), then `specs/epics/sveltekit-auth/design.md` | +| What could still go wrong | [open-risks.md](open-risks.md), then `specs/epics/sveltekit-auth/risks-and-open-questions.md` | +| How to instantiate it | `BOOTSTRAP.md`, `docs/phases/` | +| What the component is | `apps/web/docs/` (generated; `python3 tooling/catalog/gen-component-docs.py`) | + +## Next + +1. Bootstrap one site from `baseline-v1` against a workspace, connect a + GitHub OAuth app, sign in on stage, and record the timings in place of + the estimate (closes SU-A). diff --git a/ai/context/decisions.md b/ai/context/decisions.md new file mode 100644 index 0000000..0c4b8b5 --- /dev/null +++ b/ai/context/decisions.md @@ -0,0 +1,20 @@ +# sveltekit-auth — decisions + +The choices that shape this repository, one line each, with where the full +reasoning lives. Superseded decisions stay listed, marked, so the history +reads in order. + +| # | Decision | Why | Source | +|---|---|---|---| +| 1 | The app is nextauthjs/sveltekit-auth-example, kept close: its pages, header, footer, actions, `trustHost: true` and its 26 providers with their options | The example is what Auth.js maintains; the closer it stays, the cheaper an upgrade | design.md, "How it maps" | +| 2 | `@sveltejs/adapter-cloudflare` (one Worker + Static Assets), `nodejs_compat` | SvelteKit's own adapter, as sveltekit-boilerplate; no OpenNext | risk SU-G | +| 3 | `@auth/sveltekit` 1.11.3, SvelteKit 2.60.1, Svelte 5.55.7, Vite 6.4.2, exact; `cookie@0 → 0.7.0` carried from upstream's overrides | An unpinned `latest` would change the site under it; Auth.js peers SvelteKit `^2` | risk SU-C | +| 4 | No database: sessions are Auth.js's JWT cookies, so no D1, no db-migrate, no data rung (SU2) | The example has no adapter and persists nothing server-side | design.md, "Out of scope" | +| 5 | Each provider is registered only when every key it takes is set; with none, `/signin` says what to connect | A fresh site goes live with no provider; a button that fails is worse than none | IMPLEMENTATION-STATUS 3, 5 | +| 6 | The configuration is built per request from the Worker's bindings first, then SvelteKit's dynamic env | A provider's keys take effect with the deploy that pushes them; `wrangler dev` and `vite dev` read the same local `.env` | IMPLEMENTATION-STATUS 4 | +| 7 | AUTH_SECRET is generated once per environment on the Worker by the deploy lane (`tooling/wire/worker-secrets.mjs`: list, mint only if absent, push with `secret bulk` over stdin); a stored Orun secret wins; a failed list stops the deploy | Nothing is typed or committed, stage and prod differ, sessions survive deploys, and a live secret is never replaced by accident | design.md, "The secret flow"; risk SU-B | +| 8 | The provider keys are optional Orun secrets, kept out of the build (`env -u`) and pushed to the Worker as Worker secrets — for the nine providers upstream's `.env.example` names | They are read at request time; no bundle, build cache or log holds them; nine refs keep the component readable | risk SU-E | +| 9 | The smoke requires `</html>` on `/` and `null` from `/auth/session` | Read-only, and only a Worker with its AUTH_SECRET answers it | IMPLEMENTATION-STATUS 10 | +| 10 | The site's name is one seam, `src/site.ts`; the rename protects Auth.js's `SvelteKitAuth` import and call and the example's repository name, which contain the slug | A site keeps Auth.js's API and its credit | design.md, "The rename" | +| 11 | One landing (`01-product`) then the record (`03-docs`) | sveltekit-boilerplate's shape: one Worker, nothing to order | `docs/phases/` | +| 12 | Component docs are generated from the manifests and checked in CI | A hand-written copy 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..bdab7a2 --- /dev/null +++ b/ai/context/deployment.md @@ -0,0 +1,7 @@ +# sveltekit-auth — live deployment manifest + +> Not rendered yet. The bootstrap's `03-docs` phase probes every live URL and +> regenerates this file from what answered — the workspace, the URLs and +> their status, and the secrets the site uses, by name. Until then, nothing here +> claims the site 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..ba4fe33 --- /dev/null +++ b/ai/context/open-risks.md @@ -0,0 +1,15 @@ +# sveltekit-auth — open risks + +What is not yet proven or not yet decided. The full write-up of every risk, +including the accepted ones, is +`specs/epics/sveltekit-auth/risks-and-open-questions.md`; this page lists +only what is still live, so it should be short. + +| ID | Risk | State | What closes it | +|---|---|---|---| +| SU-A | No live bootstrap yet: the brokered token's reach over Worker secrets, `secret bulk` creating the Worker on a first deploy, a real `wrangler deploy` and the probes are unproven | OPEN | One bootstrap from `baseline-v1` against a workspace, signing in with a GitHub OAuth app on stage | + +Accepted, and worth knowing before you change them: SU-B (a failed secret +list stops the deploy rather than mint a replacement), SU-C (`@auth/sveltekit` +pinned exactly), SU-D (JWT sessions cannot be revoked), SU-E (nine providers +have secret refs), SU-F (upstream's dicebear avatar), SU-G (`nodejs_compat`). diff --git a/ai/context/operations.md b/ai/context/operations.md new file mode 100644 index 0000000..e456b5d --- /dev/null +++ b/ai/context/operations.md @@ -0,0 +1,146 @@ +# sveltekit-auth — operating contract (for humans and agents) + +This is the standing guide to how this site is deployed and operated. +Instance facts (live URLs, workspace, the secrets it uses) live in +[deployment.md](deployment.md), rendered from probed reality by the +bootstrap's `03-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 site without any +other source. + +## What this system is + +A SvelteKit site with Auth.js sign-in, on Cloudflare alone, expressed as an +Orun component-native desired-state repo. + +- **`apps/web`** — the site: SvelteKit 2 built by `@sveltejs/adapter-cloudflare` + into one Worker (`.svelte-kit/cloudflare/_worker.js`) plus Static Assets + (the same directory, for the hashed `_app` chunks and the static files). + The Worker renders every page, because each reads the visitor's session: + `/`, `/signin`, `/protected` and `/signout`, Auth.js's own `/auth/*` + routes (`src/hooks.server.ts` → `src/auth.ts`), and SvelteKit's error + page for every other path. Sessions are Auth.js's encrypted JWT in an + httpOnly cookie (`authjs.session-token`, `__Secure-` over HTTPS), sealed + with the Worker's `AUTH_SECRET`; there is no database. The Auth.js + configuration is built per request from the Worker's secrets: each + provider in `src/server/providers.ts` is offered only when every key it + takes is set, and with none set `/signin` says what to connect. The + site's tests (vitest) live in `apps/web` and run with `pnpm test` — by + hand, before a push: `ci.yml`'s lanes do not lint or run them. +- **`tooling/wire/worker-secrets.mjs`** — the deploy lane's secret step (in + `apps/web/component.yaml`'s `buildCommand`): it gives each environment's + Worker its AUTH_SECRET (generated once, then kept) and whichever + providers' keys are stored, with `wrangler secret bulk` over stdin. + `pnpm --filter @app/web secret:dev` runs it against `apps/web/.env` instead. +- **`tooling/*`** — shared TypeScript and ESLint configuration, and the + deploy-time wrangler renderer for workers that take wiring. + +Environments: **`stage`** and **`prod`** are deployed; **`dev` is +verify-only by design** — lanes build and dry-deploy, 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. `apps/web` builds once per environment (`vite build`, every `AUTH_*` + value unset for it; the adapter writes the Worker and the assets where + `wrangler.jsonc`'s `main` and `assets.directory` say). Then + `worker-secrets.mjs` lists the secrets `sveltekit-auth-web-<env>` + carries, generates an AUTH_SECRET only if it carries none (the first + deploy, which also creates the Worker), and pushes it with the stored + providers' keys in one `wrangler secret bulk`. If the list fails for any + reason but "the Worker does not exist", it stops rather than mint a + replacement. Then `wrangler deploy` ships the Worker and a smoke test + fetches `/` (it must render) and `/auth/session` (it must answer `null`, + which Auth.js does only with an AUTH_SECRET). +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 "site + converged"; probe the URLs instead. +- A change to `intent.yaml`'s `environments` maps to no component and + redeploys nothing on its own. Land it with a change under `apps/web`. +- A session lives only in the visitor's cookie: nothing server-side can + list or revoke one. Signing out clears it; changing the Worker's + AUTH_SECRET invalidates every session at once (everyone is signed out). +- A provider's keys reach the Worker only when it deploys. After storing + or changing one, redeploy (Deploy by hand, below); deleting an Orun + secret does not remove it from the Worker (`wrangler secret delete` + does). + +## Secrets model + +- **Brokered provider secrets**: `CLOUDFLARE_API_TOKEN` (Workers deploy + scope: the deploy and the Worker's secrets) and `CLOUDFLARE_ACCOUNT_ID` — + pointers minted per run from the workspace's Cloudflare connection. No + long-lived values at rest; nothing to rotate by hand. +- **`AUTH_SECRET`** — a Worker secret on `sveltekit-auth-web-stage` and + `-prod`, each its own, generated by that Worker's first deploy and kept + by every later one. Never in the repository, a log or the bundle. An + Orun secret `AUTH_SECRET` for the environment (optional) replaces it on + the next deploy. +- **The providers' keys** — optional Orun secrets for each environment, + `AUTH_<PROVIDER>_ID` / `_SECRET` (Auth0 adds `_ISSUER`), for the nine + providers `apps/web/component.yaml`'s `optionalSecretEnv` lists; each + deploy pushes the ones that are set to the Worker. +- Inspect by NAME only: `orun secrets list --org <ws> --project` and + `--env stage|prod`, and a Worker's with `wrangler secret list --name + sveltekit-auth-web-<env>`. No tooling in this repository prints a secret + value, and no document in `ai/context/` may contain one. + +## Verifying the system + +```bash +# the site on each environment (also recorded, probed, in deployment.md) +curl -s -o /dev/null -w '%{http_code}\n' https://sveltekit-auth-web-stage.your-workers-subdomain.workers.dev/ +curl -s https://sveltekit-auth-web-prod.your-workers-subdomain.workers.dev/auth/session # null: Auth.js has its secret + +# workspace readiness (integrations + repository link) +orun integrations list --org <ws> --json && orun cloud check --org <ws> +``` + +## Common operations + +| task | how | +|---|---| +| change a page | edit `apps/web/src/routes/…`, merge | +| rename the site | edit `SITE_NAME` in `apps/web/src/site.ts`, merge | +| connect a sign-in provider | create its OAuth app (callback `<origin>/auth/callback/<provider>`), `orun secrets set AUTH_<PROVIDER>_ID --env <env>` and `…_SECRET`, then deploy by hand; the button appears on `/signin` | +| a provider not in `optionalSecretEnv` | add its keys there and to the `--secret` list in `buildCommand` (both in `apps/web/component.yaml`), or set them on the Worker with `wrangler secret put` — a Worker keeps its secrets between deploys | +| rotate AUTH_SECRET | `orun secrets set AUTH_SECRET --env <env>` with a new value, then deploy by hand; every visitor is signed out | +| 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 | +| redeploy without a change | edit the last line of `apps/web/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"), add `<domain>/auth/callback/<provider>` to each OAuth app, then replace the placeholder `sveltekit-auth.example.com` in `intent.yaml`'s `BASE_DOMAIN` (dev, stage and prod) with it; Auth.js trusts the host it is served on | +| add a runtime secret | `orun secrets set <KEY> --org <ws> --env <env>` | +| headless credentials | `ORUN_TOKEN` (workspace-scoped) + `GITHUB_TOKEN` | + +The deployment record is the bootstrap's `03-docs` phase. Re-running it (the +Orun console's Retry on that phase, or `orun new … --phase 03-docs`) +re-probes the URLs and re-renders [deployment.md](deployment.md); it is +idempotent. + +## Evolution + +Structural changes (a second Worker, an API, a data store — a database +adapter for Auth.js, say, to keep users and sessions server-side) follow the same +contract that deployed the site: add a component under `apps/`, `infra/` or +`packages/` with a `component.yaml`, land it as a pull request, and the +convergence run applies it. diff --git a/apps/web/docs/architecture.md b/apps/web/docs/architecture.md new file mode 100644 index 0000000..8134195 --- /dev/null +++ b/apps/web/docs/architecture.md @@ -0,0 +1,39 @@ +# web — architecture + +Built by the turbo pipeline from `apps/web` and deployed with wrangler. + +| | | +| ------------------- | ----------------------------------- | +| Worker config | `apps/web/wrangler.jsonc` | +| Entry | `.svelte-kit/cloudflare/_worker.js` | +| Compatibility date | `2026-10-01` | +| Compatibility flags | `nodejs_compat` | + +## Bindings + +| Binding | Kind | Source | +| -------- | ------------- | ------------------------ | +| `ASSETS` | Static assets | `.svelte-kit/cloudflare` | + +## Secrets resolved by the lane (names only) + +- `AUTH_AUTH0_ID` (optional) +- `AUTH_AUTH0_ISSUER` (optional) +- `AUTH_AUTH0_SECRET` (optional) +- `AUTH_DISCORD_ID` (optional) +- `AUTH_DISCORD_SECRET` (optional) +- `AUTH_FACEBOOK_ID` (optional) +- `AUTH_FACEBOOK_SECRET` (optional) +- `AUTH_GITHUB_ID` (optional) +- `AUTH_GITHUB_SECRET` (optional) +- `AUTH_GOOGLE_ID` (optional) +- `AUTH_GOOGLE_SECRET` (optional) +- `AUTH_LINKEDIN_ID` (optional) +- `AUTH_LINKEDIN_SECRET` (optional) +- `AUTH_PINTEREST_ID` (optional) +- `AUTH_PINTEREST_SECRET` (optional) +- `AUTH_SECRET` (optional) +- `AUTH_TWITCH_ID` (optional) +- `AUTH_TWITCH_SECRET` (optional) +- `AUTH_TWITTER_ID` (optional) +- `AUTH_TWITTER_SECRET` (optional) diff --git a/apps/web/docs/overview.md b/apps/web/docs/overview.md new file mode 100644 index 0000000..b50ccdf --- /dev/null +++ b/apps/web/docs/overview.md @@ -0,0 +1,20 @@ +# web + +The Auth.js sign-in example (SvelteKit on Cloudflare Workers + Static Assets via @sveltejs/adapter-cloudflare, per environment) + +A Cloudflare Worker with Static Assets (server rendering plus static files), deployed per environment by its CI lane. + +| | | +| ------------ | ------------------------------------------------------------------------------------------------------------------ | +| Type | `cloudflare-workers-assets-turbo` | +| Source | `apps/web` | +| Package | `@app/web` | +| Environments | `dev`: `verify` · `stage`: `verify`, `deploy` on a push to `main` · `prod`: `verify`, `deploy` on a push to `main` | + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/apps/web/docs/runbook.md b/apps/web/docs/runbook.md new file mode 100644 index 0000000..359296d --- /dev/null +++ b/apps/web/docs/runbook.md @@ -0,0 +1,38 @@ +# web — runbook + +## How it runs + +Pull requests verify it; a merge to `main` deploys it to `stage`, `prod`. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Local commands + +```bash +pnpm --filter @app/web dev +pnpm --filter @app/web build +pnpm --filter @app/web test +pnpm --filter @app/web typecheck +pnpm --filter @app/web lint +pnpm --filter @app/web preview +``` + +## Verify + +After a deploy the lane runs this smoke against the environment it +deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL: + +```bash +html=$(curl -sfL "${DEPLOYED_URL}/") && echo "${html}" | grep -q '</html>' && session=$(curl -sf "${DEPLOYED_URL}/auth/session") && [ "${session}" = "null" ] +``` + +## 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 + +- **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. diff --git a/blueprint.yaml b/blueprint.yaml new file mode 100644 index 0000000..0df7e87 --- /dev/null +++ b/blueprint.yaml @@ -0,0 +1,156 @@ +# The sveltekit-auth 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: sveltekit-auth + displayName: SvelteKit Auth — Auth.js sign-in for SvelteKit on Cloudflare Workers + description: > + Auth.js's SvelteKit example as a product of its own: a SvelteKit site + whose sign-in is Auth.js — a home page, a sign-in page, a protected page + only a signed-in visitor can read and a sign-out — with the example's 26 + OAuth providers wired in, each offered once its keys are stored as the + site's secrets, built by SvelteKit's own Cloudflare adapter into one + Worker with Static Assets, and CI that deploys it to stage and prod on + merge. No database: sessions are Auth.js's encrypted JWT cookies, sealed + with an AUTH_SECRET each environment's first deploy generates on its + Worker and every later deploy keeps. Nothing to type. One provider, one + consent, one token, one landing. Live in about five minutes. + tags: [auth, authjs, oauth, sveltekit, svelte, cloudflare, starter] +spec: + source: + repo: sourceplane/sveltekit-auth + # No `tag`. The registry pins it; this file is fetched at it. + + # ── What the operator reads first ──────────────────────────────────────── + overview: + lede: > + Sign-in for a SvelteKit site, on Cloudflare alone: Auth.js in the + Worker, its sessions in an encrypted cookie, no database to run. It + deploys with nothing connected and its sign-in page says what to + connect; store an OAuth app's keys and that provider's button appears. + architecture: + - layer: Edge + items: [web] + - layer: Identity + items: ["Auth.js (@auth/sveltekit), JWT sessions", "GitHub, Google and 24 more providers (connected after the build)"] + - layer: Pages + items: [home, sign-in, protected, sign-out] + - layer: Delivery + items: [GitHub Actions, "@sveltejs/adapter-cloudflare"] + outcome: + - Live on stage and prod, in one landing + - The auth secret generated on each environment's Worker — nothing typed + - Every merge redeploys, smoke-tested + - Its own CI from the first phase + + requires: + # Cloudflare is the only provider connection a bootstrap needs. GitHub + # arrives as the App installation plus the repo link, not as a + # connection row. + integrations: [github, cloudflare] + 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 site 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 site'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: Site name + pattern: "^[A-Za-z0-9][A-Za-z0-9 .,'&-]{1,48}$" + help: The name visitors see — the home page's heading and every page's title. + example: Acme Notes + - key: githuborg + label: GitHub organisation + pattern: "^[A-Za-z0-9][A-Za-z0-9-]*$" + help: The GitHub org or user the site'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 site deploys into. + example: acme + # READ FROM THE CLOUDFLARE CONNECTION, not asked. The subdomain belongs + # to the account the same way its id does, and there is exactly one + # right answer — a typed one could only be wrong, and wrong showed up + # after deploy, in the deploy's smoke, 01-product's probes and the + # verify URL 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 token 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` + # hook mints these, brokered, during 01-product. ────────────────────────── + # Transcribed from that hook's own `secrets:` list (each key and its + # `template:`), 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. + secrets: + - key: CLOUDFLARE_API_TOKEN + provider: cloudflare + template: workers-deploy + why: Deploys the site's Worker and its static assets, and sets its AUTH_SECRET + - key: CLOUDFLARE_ACCOUNT_ID + provider: cloudflare + template: account-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: sveltekit-auth-baselining # = repo-blueprint.yaml's `epicSlug` default + epicName: "Auth baselining — {productname}" + milestones: + - name: 01-product + - name: 03-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 (4 + 1): sveltekit-boilerplate's + # shape, plus a minute for each environment's secret check and push + # before its deploy. An estimate until a live build measures it. + expectedMinutes: 5 + tokenChannel: ORUN_TOKEN_FILE # how a runner hands over its refreshed token + verify: + urls: + - "https://{reponame}-web-{env}.{subdomain}.workers.dev" + envs: [stage, prod] diff --git a/docs/phases/01-product.md b/docs/phases/01-product.md new file mode 100644 index 0000000..09d3a26 --- /dev/null +++ b/docs/phases/01-product.md @@ -0,0 +1,87 @@ +# 01-product — the site, built in one landing + +**Places** the whole tree: the root manifests (`intent.yaml`, `package.json`, +the pnpm workspace and lockfile, `turbo.json`), +`.github/workflows` (`ci.yml` — the baseline's own `baseline.yml` and +`tag.yml` are ignored), the shared TypeScript/ESLint +config, the wrangler renderer and `tooling/wire/worker-secrets.mjs` (the +step that gives each environment's Worker its secrets), the site's README +and its two context pages, the identity file `.rebrand/values.json`, +`.gitkeep` files for the four discovery roots, and `apps/web` — the +SvelteKit site with Auth.js, its Cloudflare adapter build, its deploy +contract, its tests (vitest, run inside the app), the upstream example's ISC +`LICENSE` and its `.env.example`, every key a local run can take. + +**Requires** both connections live — GitHub (the App installation on +`githuborg`) and Cloudflare — probed, waited for up to ten minutes each, so a +consent can be clicked while it waits. The platform sees a pull request only +through the installation on the account that owns the repository, so the +probe runs before anything is created. + +## 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` | the redeploy marker on `apps/web/component.yaml` (`.baseline/tasks/01-product.TaskContract.yaml`'s `affects`) | +| `git-init`, `git-stage` | the rebrand enumerates with `git ls-files`, so the tree is a staged repo first | +| `rebrand` | renames the baseline's identity to the site's over the whole tree (`tooling/rebrand/rebrand.mjs`) | +| `orun-workspace` | writes the site's workspace into `intent.yaml` (`ws_SET_ME` if there is none — loud, not silent) | +| `work-tree` | removes the baseline's own `work:` block from `intent.yaml` — `specs/` and `tasks/` do not ship | +| `promotion` | defers prod's wait on stage until `03-docs` (both environments deploy side by side) | +| `dev-lanes` | keeps dev's verify lanes off main's convergences until `03-docs` | +| `git-restage`, `rebrand-verify` | refuses the landing if any baseline identity is left | +| `repo` | `orun.repo/ensure@v1` — creates `githuborg/reponame` (private unless `repoPrivate=false`) | +| `link` | `orun cloud link` (best effort) then `orun cloud check` — an unlinked repo stops here | +| `secrets` | `orun.integrations/reconcile@v1`, both keys in one hook, created side by side: `CLOUDFLARE_API_TOKEN` from the `workers-deploy` template (Workers Scripts: the site's deploy, and its Worker's secrets); `CLOUDFLARE_ACCOUNT_ID`, the connection fact. Nothing is asked for AUTH_SECRET: the deploy lane generates it on the Worker | +| `task` | finds the phase's task (opened by the run-level list) 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 | +| `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` on both workers.dev URLs | + +## What the convergence does + +`orun plan --changed` plans `web` on stage and prod (deploy) and — dev's push +activation being deferred — nothing on dev. Each deploy lane installs the +workspace inside its own job tree, builds with `vite build` (the adapter +writes `.svelte-kit/cloudflare/_worker.js` and the static output where +`wrangler.jsonc`'s `main` and `assets.directory` say; every `AUTH_*` value +is unset for the build, so none can be bundled), then runs +`tooling/wire/worker-secrets.mjs` for `<reponame>-web-<env>`: it lists the +secrets the Worker carries (`wrangler secret list`), generates an +AUTH_SECRET only if it carries none — on the first deploy, when the Worker +does not exist yet — and pushes it, with whichever providers' keys are +stored as the site's secrets, in one `wrangler secret bulk` over stdin (a +first push creates the Worker). Then it checks the build output, deploys +with `wrangler deploy`, and smoke-tests it: the home page must render, and +Auth.js's `/auth/session` must answer `null` — which it does only once the +Worker has its AUTH_SECRET. Stage and prod deploy side by side (this phase +deferred the promotion gate), each with its own secret. + +## Verified + +The repository exists and is linked to the workspace, the convergence run for +the merge commit is green, and +`https://<reponame>-web-{stage,prod}.<subdomain>.workers.dev` answer. + +## Troubleshooting + +| symptom | cause → fix | +|---|---| +| parks on `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` | +| parks on the `providers` probe for cloudflare | Cloudflare is not connected to the workspace. Connect it (console → Integrations → Cloudflare, paste the Account API token) | +| `link` fails: `… is not linked to workspace` | the credential cannot write links and the platform has not linked the repo. Allow-list it (console → Settings → Git repos) and re-run the phase | +| `land`: `the landing's own check failed — orun plan for …` | the placed tree does not plan; the next line is orun's error. Nothing was pushed. Fix it and re-run the phase | +| `rebrand-verify` lists leftovers | a file carries an identity form no rule renames. Add a rule to `tooling/rebrand/rebrand.mjs` (and a case to `testing/rebrand.test.sh`) | +| `intent.yaml` says `workspace: ws_SET_ME` | `orunWorkspace` was empty and the build ran outside a workspace. Set it and re-run | +| deploy lane: `secret resolution failed … CLOUDFLARE_API_TOKEN` | the reconcile did not run or minted against a revoked connection. Re-connect and re-run the phase; the reconcile re-mints only what is missing | +| deploy lane: Authentication error (10000) | the connection's token lacks Workers Scripts Write. Re-issue it with the permission groups the console's Connect recipe lists | +| smoke fails right after the FIRST deploy | workers.dev route propagation; the composition retries the first deploy and the smoke with backoff (stack-tectonic ≥ 0.19.0). A convergence resume clears what is left | +| `build-app`: `worker-secrets: could not list the secrets … refusing to mint a replacement` | `wrangler secret list` failed for a reason other than "the Worker does not exist" (a revoked token, an API error). Nothing was pushed, so the Worker keeps the AUTH_SECRET it had and no session is lost. Fix the credential and resume the convergence | +| smoke fails on `/auth/session` (a 500, `MissingSecret` in the Worker's log) | the Worker has no AUTH_SECRET: its secret push did not run. Resume the convergence; `build-app` generates one when the Worker carries none | +| `build-app` fails resolving a dependency, or `wrangler` is not found | the job's install did not run inside its tree. The site's `intent.yaml` pins stack-tectonic 0.19.0, where it does; a bump changes the install's layout — `intent.yaml`'s comment says why it is pinned | +| 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 site's tree says which | diff --git a/docs/phases/03-docs.md b/docs/phases/03-docs.md new file mode 100644 index 0000000..80dc1e9 --- /dev/null +++ b/docs/phases/03-docs.md @@ -0,0 +1,39 @@ +# 03-docs — the deployment, recorded + +**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 `/`, `/signin` and Auth.js's `/auth/session` on both environments and regenerates `ai/context/deployment.md` — the identity, the probed URLs, the secrets the deployment uses by name — 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. 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 | + +## Re-running it + +Idempotent, and the way to refresh the record after a redeploy: every +generated section is re-rendered from scratch. + +```bash +orun new --blueprint repo-blueprint.yaml --out <site-checkout> \ + --run-hooks --phase 03-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 <site>/intent.yaml +node tooling/bootstrap/dev-lanes.mjs --restore --file <site>/intent.yaml +``` diff --git a/docs/phases/README.md b/docs/phases/README.md new file mode 100644 index 0000000..c5f9f68 --- /dev/null +++ b/docs/phases/README.md @@ -0,0 +1,118 @@ +# The phases — one blueprint, two selections + +`repo-blueprint.yaml` declares two phases that take a site from **nothing** +to **live on stage and prod, documented**: one landing builds the whole site, +one records it. Run them one at a time with +`--phase <name>`, or the whole sequence 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. + +The site phase follows the contract every deploying phase does: + +> **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 over HTTP.** + +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 +site's repository is wherever `--out` points. + +## Execution order + +The phase number is the EXECUTION order, and each phase's `requires.phases` +states it in the document: the engine refuses a phase whose predecessor is not +placed, and names it. + +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 site carries no other workflow: +the baseline's own CI (Tier 2) installs, renders the fixtures, type-checks, +lints, tests and builds this tree before a tag is cut, and every later pull +request in the site runs `ci.yml`'s verify lanes (built and dry-deployed per +environment; they do not lint or run the tests). + +| phase | lands | verified by | +|---|---|---| +| [`01-product`](01-product.md) | **the GitHub repo created**, then the WHOLE site in one PR: intent, CI, tooling, identity, `apps/web` (the site and its tests) — one convergence deploys it to stage and prod side by side | repo workspace-linked, convergence green (build, deploy, smoke) + both URLs answer | +| [`03-docs`](03-docs.md) | the live-deployment record; the promotion gate and dev lanes put back | committed manifest matches probed reality | + +There is no custom-domain phase. Attaching a domain to a Worker needs zone +permissions the platform's brokered `workers-deploy` token does not carry, so +it is an owner's step after the bootstrap — the site's README, "Custom +domain", says how. Nothing else in the repository changes with it — the site +builds no absolute links — beyond `BASE_DOMAIN` in `intent.yaml`, which holds +the placeholder until then. + +## Inputs + +`01-product` takes the site's identity once and writes it into the repo +(`.rebrand/values.json`); every later phase 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 site 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 + site's README, "Custom domain"). Pass it only for a site 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 the deploy's smoke + fetches. 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 `sveltekit-auth-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/sites/acme-notes --run-hooks --phase 01-product \ + --values ~/acme-notes.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`). + +## What 01-product does after it places + +Placement writes the baseline's files as they are here. Before the phase +lands, its `post` hooks make them the site's: + +1. `retouch` — one `# orun: redeploy <phase> <stamp>` line + at the end of each component.yaml its task contract names, so a re-run + after a failed convergence still has a diff to land and redeploys exactly + those components. +2. `rebrand` → `rebrand --verify` — the identity rename over the whole tree, + then a sweep that fails on any of this baseline's identity left behind. + +The baseline's complete lockfile ships as it is: it carries no identity, and +the lanes install it with `--frozen-lockfile`, as the baseline's own CI does +on this exact tree before a tag. + +## When a phase fails + +- **Before it lands** (a probe that timed out, a rebrand residue, a refused + link, a tree the landing's own `orun plan` refuses): 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 + component redeploys. diff --git a/hooks/render-deployment-docs.sh b/hooks/render-deployment-docs.sh new file mode 100755 index 0000000..819bb78 --- /dev/null +++ b/hooks/render-deployment-docs.sh @@ -0,0 +1,153 @@ +#!/usr/bin/env bash +# Render the site's LIVE-DEPLOYMENT documentation from verified state. +# Called by phase 03-docs as a `run:` hook (and safe to run by hand, from the +# site's checkout). Idempotent: the generated file and the README section are +# fully re-rendered on every run, so re-running after a redeploy or a custom +# domain 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, +# 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 <!-- 03-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 scaffolded site?" >&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; } + +# The Worker's workers.dev URL per environment. The site builds no absolute +# links, so a custom domain attached in Cloudflare serves the same Worker with +# nothing in the repository naming it; the record probes what the repository +# can name. +stage_dev="https://${brand}-web-stage.${sub}.workers.dev" +prod_dev="https://${brand}-web-prod.${sub}.workers.dev" + +# Every page is rendered by the Worker (Auth.js reads the session on each). +# /auth/session is Auth.js's own route: it answers only once the Worker has +# its AUTH_SECRET, so it is the probe that says sign-in can work. +rows="" +for pair in "stage|$stage_dev" "prod|$prod_dev"; do + env="${pair%%|*}"; url="${pair#*|}" + rows+="| site (${env}) | ${url} | $(badge "$(probe "$url/")") |"$'\n' + rows+="| sign-in (${env}) | ${url}/signin | $(badge "$(probe "$url/signin")") |"$'\n' + rows+="| Auth.js session (${env}) | ${url}/auth/session | $(badge "$(probe "$url/auth/session")") |"$'\n' +done + +now="$(date -u +%Y-%m-%dT%H:%M:%SZ)" + +# Heal the static operating contract when the site 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 \`03-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} +The \`dev\` environment is verify-only by design — no deployed URL. A custom +domain attached to a Worker in Cloudflare serves the same site (README, +"Custom domain"). + +## Secrets (names only) + +| secret | where | what it is | +|---|---|---| +| \`CLOUDFLARE_API_TOKEN\` | the workspace | BROKERED from its Cloudflare connection (\`workers-deploy\`): deploys the Worker and its static assets, and sets its secrets | +| \`CLOUDFLARE_ACCOUNT_ID\` | the workspace | the connection's account id — a fact, not a credential | +| \`AUTH_SECRET\` | each Worker (\`${brand}-web-stage\`, \`${brand}-web-prod\`) | seals Auth.js's session cookies; generated on the Worker by its first deploy and kept by every later one. A workspace secret of the same name (\`secret://…/${repo}/<env>/AUTH_SECRET\`) replaces it on the next deploy | +| \`AUTH_<PROVIDER>_ID\`, \`AUTH_<PROVIDER>_SECRET\` | the workspace, optional | an OAuth app's keys (\`secret://…/${repo}/<env>/AUTH_GITHUB_ID\` and so on); each deploy pushes the ones that are set to its Worker, and that provider's sign-in appears | + +Brokered secrets are minted per run, so no long-lived Cloudflare credential +is at rest. AUTH_SECRET is never in the repository, a log or this file. 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 = "<!-- 03-docs:begin -->", "<!-- 03-docs:end -->" +body = f"""{begin} +This site is **live**. Verified URLs, identity and the secrets it uses are +recorded in [ai/context/deployment.md](ai/context/deployment.md) (re-rendered +by the `03-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..b7810c5 --- /dev/null +++ b/repo-blueprint.yaml @@ -0,0 +1,663 @@ +apiVersion: orun.dev/v1 +kind: Blueprint +metadata: + name: sveltekit-auth + description: >- + Auth.js's SvelteKit example as a Blueprint of itself — instantiate a new + SvelteKit site repository whose sign-in is Auth.js (a home page, a sign-in + page offering every OAuth provider whose keys are stored, a protected page + and a sign-out, sessions in Auth.js's encrypted JWT cookie, no database), + built by @sveltejs/adapter-cloudflare onto Cloudflare Workers + Static + Assets with an AUTH_SECRET generated on each environment's Worker, and + take it from nothing to live on stage and prod in one landing, then record + it. Run one at a time with `--phase <name>` or the whole sequence 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-notes) — intent metadata.name, the Worker name prefix, the secret project. + productname: + type: string + required: true + description: The site's display name (e.g. "Acme Notes") — the home page's heading and every page's title. + productdomain: + type: string + default: "" + description: >- + The site's own domain, once it has one (e.g. acme.dev). NOT ASKED: the + site 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 + in intent.yaml, for dev, stage and prod), so setting it later is + replacing that one string — the site's README, "Custom domain", says + how. 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 site's repository is created under — and the owner in + the source link the site's nav carries. 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 site deploys + into — its URLs, the smoke, 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 site's remote state. 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: sveltekit-auth-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 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/.env.local` 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 + - .svelte-kit + - .wrangler + - node_modules + - .orun + - plan.json + - "**/*.tsbuildinfo" + # `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` is not among them, and ships. + - "**/.env" + - "**/.env.local" + - "**/.env.*.local" + - "**/.dev.vars" + - "**/.dev.vars.*" + # THE FACTORY'S OWN LANES. `github-workflows` copies the whole of `.github`, + # so without these two entries every site built from this baseline would + # carry them — `baseline.yml` runs `testing/*.sh`, which no module places, + # and `tag.yml` cuts baseline tags a site 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) can ship by accident. testing/leak.test.sh holds that line. +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 SITE's README, not this repository's: this one is about the baseline + # (how to instantiate it, how it is tested), and a site's owner has no use + # for any of that. + - name: root-readme + mode: copy + source: baseline + from: .baseline/product/README.md + to: README.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 site genuinely owns: its operating contract, and + # the deployment manifest 03-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 + + # ── the empty discovery roots, declared ────────────────────────────────── + # orun's repo-scale gate — and later `orun plan` in the site's own CI — + # discovers apps/, infra/, packages/ and tests/, and a missing root is a + # hard failure. The site fills apps/ in the same landing; the other three + # stay empty (the site's test runs inside apps/web). A file the tree needs + # in order to be valid is what a module is for. + - name: discovery-roots + mode: template + files: + "apps/.gitkeep": "" + "infra/.gitkeep": "" + "packages/.gitkeep": "" + "tests/.gitkeep": "" + + # ── shared tooling ─────────────────────────────────────────────────────── + # The workspace's shared packages: the TypeScript and ESLint configuration + # (both pnpm workspace projects, so the lockfile names them), the + # deploy-time wrangler renderer, and worker-secrets.mjs, which the deploy + # lane's build runs to give each environment's Worker its AUTH_SECRET and + # whichever providers' keys are stored. The factory's tooling (rebrand, bootstrap) + # stays here, and so does `tooling/migrations`: it checks the D1 migration + # manifest of a `packages/db` this site does not have, and nothing a site + # runs reads it. + - 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 + + # ── the site ───────────────────────────────────────────────────────────── + # One component: the app carries its own tests (vitest, in apps/web), the + # upstream example's ISC licence, and its `.env.example`, every key a + # local run can take. There is no separate test package to place, and no + # database: sessions are Auth.js's JWT cookies. + - name: web + mode: copy + source: baseline + from: apps/web + to: apps/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. The MILESTONE keeps the phase's name: it is the identity the engine's +# phase events, the plane's evidence and the console's rows all meet on, and +# the card's `programme.milestones` names the same list. +hooks: + preInstantiate: + - id: epic + uses: orun.task/ensure@v1 + background: true + with: + kind: epic + slug: "{{ .inputs.epicSlug }}" + name: "Auth baselining — {{ .inputs.productname }}" + description: >- + Everything the SvelteKit Auth baseline builds for + {{ .inputs.productname }} in {{ .inputs.githuborg }}/{{ .inputs.reponame }}: + the repository, its CI and the site live on stage and prod in one + landing, then 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 }} and linked to the workspace + - the site built and deployed on stage and prod, its smoke green + - the home page answers on both workers.dev URLs, and Auth.js reads sessions there + - id: m03 + uses: orun.task/ensure@v1 + background: true + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 03-docs + exitCriteria: + - ai/context/deployment.md on main matches the probed live URLs + - prod waits on stage again + - id: t01 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 01-product + name: "Build the site in one landing" + brief: >- + Create {{ .inputs.githuborg }}/{{ .inputs.reponame }} and land the + whole site as one pull request — intent, CI, tooling, the identity, + the site and its tests, branded as {{ .inputs.productname }} — then + see the convergence build it with @sveltejs/adapter-cloudflare, give + each environment's Worker its AUTH_SECRET and deploy it to stage and + prod, smoke-tested over HTTP. + prefix: BASE + contract: .baseline/tasks/01-product.TaskContract.yaml + - id: t03 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 03-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, not from what the + blueprint intended. + prefix: BASE + contract: .baseline/tasks/03-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. A dependency may never point forward +# across a phase boundary; orun refuses the blueprint if one does. +# +# ONE LANDING BUILDS THE SITE (cirrus-baseline baseline-v22's shape). A landing +# has a fixed cost however small it is — place, open a PR, wait for its +# checks, merge, wait for the convergence to start — and the bootstrap used to +# pay it three times: the scaffold, the site, the record. Nothing in the +# scaffold/site split was order the plan could not carry itself: the site's +# build reads the tooling from the same tree, and the convergence on main is +# what deploys it either way. So 01-product places the whole tree, brands it +# and lands it as one pull request, and its convergence deploys the site to +# stage and prod. 03-docs stays a landing of its own because it records what +# went live and puts back the two bootstrap deferrals. The numbering keeps its +# gap so the names stay the identities the task plane and `--phase` use. +# +# One phase places NO modules: `03-docs` is hooks only. It is a phase because +# it is a separately landable unit with its own task and its own PR. +phases: + - name: 01-product + title: The site, built in one landing + description: The whole tree — manifests, tooling, CI, the identity and the site — branded, landed as one pull request, and deployed to stage and prod by one convergence. + # An estimate, not a measurement of this shape: sveltekit-boilerplate's 3 + # (the task set-up in the background, the landing checked here instead of + # by a runner's `plan`, the watch reading every 5 s), plus a minute for + # each environment's secret check and push (`wrangler secret list`, then + # `secret bulk`, which on a first deploy creates the Worker) before its + # deploy. The rest is the merge's convergence: the site's Vite build, + # deploy and smoke, stage and prod side by side. + expectedMinutes: 4 + narrate: + start: "Creating the repository and landing the whole site in one pull request — intent, CI, tooling, and the Auth.js sign-in, protected and sign-out pages. Then one convergence builds it with SvelteKit's Cloudflare adapter, gives each environment's Worker its own AUTH_SECRET and deploys it to stage and prod side by side. Usually about {{ .meta.expectedMinutes }} minutes." + await: "The site is building and deploying on both environments. A first deploy waits on its workers.dev route; nothing is stuck." + done: "{{ .inputs.reponame }} is live on stage and prod — {{ .meta.files }} files on main, branded as {{ .inputs.productname }}. That took {{ .meta.elapsed }}." + failed: "The site did not come up. The failing lane above names the step — the build and its secrets, the deploy or the smoke — and a provider error is in its log." + modules: [ai-deployment, ai-operations, discovery-roots, github-workflows, rebrand-values, root-gitignore, root-intent, root-package-json, root-pnpm-lock, root-pnpm-workspace, root-readme, root-turbo, tooling-eslint, tooling-tsconfig, tooling-wire, vscode, web] + # 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. + # And the Cloudflare connection, which the deploy credentials below are + # minted from — asked for here too, since this phase is the one that + # deploys. `requires.probe` asks reality what a lock file cannot: are both + # connections live right now? + requires: + probe: + - id: providers + uses: orun.doctor/check@v1 + with: + providers: [github, cloudflare] + githubOwner: "{{ .inputs.githuborg }}" + waitSeconds: 600 + pollSeconds: 20 + hooks: + post: + # A RE-RUN PHASE MUST HAVE SOMETHING TO LAND. A convergence can fail + # AFTER its PR merged, and the merge has already put every file this + # phase places on main; orun derives phase state from the tree, so a + # forced re-run lands an EMPTY diff while the site's CI plans + # `--changed`. So the phase rewrites ONE trailing marker line in each + # component.yaml its contract names — `# orun: redeploy <phase> + # <stamp>` — and the landing has a diff. The marker is a deploy + # trigger, not state: nothing reads it back. + - id: retouch + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/retouch.mjs", "--phase", "{{ .phase.name }}", "--affects", "{{ .baseline.dir }}/.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. The whole tree is here, so the one rebrand brands all of it. + - id: git-init + run: ["git", "init", "-q"] + - id: git-stage + run: ["git", "add", "-A"] + - id: rebrand + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--values", ".rebrand/values.json", "--allow-dirty"] + # Re-tenant the site. rebrand.mjs treats the orun state backend as + # org-owned and leaves it alone, so intent.yaml would keep THIS + # repository's `workspace:` — the site'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 site 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 site 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 deploy; during a + # bootstrap both are empty and the landing is watched to green, so it + # protects nothing and doubles the convergence. Deferred here, + # restored by 03-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 SvelteKit build on every merge proves 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: git-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: "The repository exists at {{ .inputs.githuborg }}/{{ .inputs.reponame }}." + with: + owner: "{{ .inputs.githuborg }}" + name: "{{ .inputs.reponame }}" + private: "{{ .inputs.repoPrivate }}" + # THE REPOSITORY MUST BE THE WORKSPACE'S before anything lands in it, + # or the site'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 + 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 deploy credentials, brokered, in ONE hook (orun >= v2.87.0): + # `secrets` mints each key under its own scope template from the one + # connection the build is bound to, reading the connections and the + # existing secrets once and creating the missing keys side by side. + # `workers-deploy` is the site's deploy (Workers Scripts); the account + # id is a connection fact. The deploy lane binds both keys (the + # workers-assets composition's `secretBindings`). Keys that already + # exist are kept. After the link, before the landing whose convergence + # uses them. + - id: secrets + uses: orun.integrations/reconcile@v1 + with: + provider: cloudflare + secrets: + - { key: CLOUDFLARE_API_TOKEN, template: workers-deploy } + - { key: CLOUDFLARE_ACCOUNT_ID, template: account-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 site in one landing" + prefix: BASE + contract: .baseline/tasks/01-product.TaskContract.yaml + # THE SITE 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 the site's build, deploy and + # smoke on main moments later, for real, and that convergence is what + # `await` watches to green. + - id: land + uses: orun.pr/land@v1 + narrate: "The site is merged into main." + with: + task: "{{ .phase.hooks.task.outputs.key }}" + epic: "{{ .inputs.epicSlug }}" + branchSlug: "{{ .phase.name }}" + title: "feat: {{ .inputs.productname }}, the whole site from the SvelteKit Auth example" + checks: local + await: + - id: converge + uses: orun.run/watch@v1 + narrate: "The site built, deployed and passed its smoke, and the convergence run came back green." + with: + # The run for the commit THIS landing merged — the branch's newest + # run, read the moment the merge returns, may be another push's. + sha: "{{ .phase.hooks.land.outputs.mergeSha }}" + repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" + resumeBudget: 3 + waitSeconds: 1800 + # 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 + - id: verify + uses: orun.http/probe@v1 + narrate: "The site answered on stage and prod." + with: + urls: + - "https://{{ .inputs.reponame }}-web-stage.{{ .inputs.subdomain }}.workers.dev" + - "https://{{ .inputs.reponame }}-web-prod.{{ .inputs.subdomain }}.workers.dev" + + # 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: 03-docs + title: The deployment, recorded + description: The live-deployment manifest, rendered from probed reality, and the promotion gate put back. + # An estimate, not a measurement: the render's probes, the task found, + # the commit checked here and merged — nothing built, nothing waited on. + expectedMinutes: 1 + narrate: + start: "Now recording what was actually built — probing every URL and writing the deployment manifest into the repository." + done: "ai/context/deployment.md now records the live deployment, written from probed facts, and prod waits on stage again. {{ .meta.elapsed }}." + failed: "The deployment record did not land. The site is still live; only the write-up is missing." + modules: [] + requires: + phases: [01-product] + hooks: + post: + # THE SITE 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 + 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/03-docs.TaskContract.yaml + # Checked here and merged, as 01-product's landing is; nothing here + # builds. + - id: land + uses: orun.pr/land@v1 + narrate: "The deployment record is merged into main." + 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 1e7aa40..0d8a44f 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 | |------|---------|--------|------------| -| [`sveltekit-auth/`](./sveltekit-auth/) | **SU** | In progress (SU3) | Auth.js's SvelteKit example — sign-in through any of 26 OAuth providers, each offered once its keys are stored, a protected page, JWT sessions with no database — on Cloudflare Workers + Static Assets, and an Orun baseline that instantiates it in one landing | +| [`sveltekit-auth/`](./sveltekit-auth/) | **SU** | ✅ Shipped (`baseline-v1`); not yet live | Auth.js's SvelteKit example — sign-in through any of 26 OAuth providers, each offered once its keys are stored, a protected page, JWT sessions with no database — on Cloudflare Workers + Static Assets, and an Orun baseline that instantiates it in one landing | As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`. diff --git a/specs/epics/sveltekit-auth/IMPLEMENTATION-STATUS.md b/specs/epics/sveltekit-auth/IMPLEMENTATION-STATUS.md index ddf40e1..83d819b 100644 --- a/specs/epics/sveltekit-auth/IMPLEMENTATION-STATUS.md +++ b/specs/epics/sveltekit-auth/IMPLEMENTATION-STATUS.md @@ -5,8 +5,8 @@ | SU0 — the spec | ✅ Shipped | [#1](https://github.com/sourceplane/sveltekit-auth/pull/1) | | SU1 — the auth app on Workers | ✅ Shipped | [#2](https://github.com/sourceplane/sveltekit-auth/pull/2) | | SU2 — the data | Not needed: JWT sessions persist nothing | — | -| SU3 — ready to instantiate | In progress | | -| SU4 — a baseline | Not started | | +| SU3 — ready to instantiate | ✅ Shipped | [#3](https://github.com/sourceplane/sveltekit-auth/pull/3) | +| SU4 — a baseline | ✅ Shipped, tagged `baseline-v1` | [#4](https://github.com/sourceplane/sveltekit-auth/pull/4) | ## What is proven, and how @@ -15,7 +15,9 @@ | The app builds into one Worker with Static Assets (702 KiB, 162 KiB gzipped) | `pnpm build` + `wrangler deploy --dry-run` | | The providers and their keys (all 26, in upstream's order; a blank key is no key; Auth0 needs its issuer, WorkOS its connection), the bindings winning over the dynamic env, the site's name | `apps/web/src/server/*.test.ts`, `apps/web/src/site.test.ts` | | The secret step: a verify lane pushes nothing; a first deploy mints a 43-character key that appears in no argument and no log; an existing key is kept; a failed list refuses; a stored key is used as is; the local `.env` is merged, 0600 | `apps/web/src/worker-secrets.test.ts`, against a stand-in `wrangler` | -| Served by `wrangler dev` and `vite dev`: with no AUTH_SECRET `/auth/session` fails; with one every page renders, `/auth/session` is null, `/signin` says what to connect and its post goes back there, `/protected` denies; with GitHub's keys `/signin` offers GitHub and its post is GitHub's authorize URL with this site's callback; a session cookie sealed with the secret opens `/protected`; sign-out clears it | by hand (SU1); Baseline CI's end-to-end tier, next (SU4) | +| A bootstrap places the site only, renamed throughout, with Auth.js's `SvelteKitAuth` import and call, the example's repository link and its ISC licence intact; its own plan deploys web to stage and prod with the site's Worker, smoke and secret refs | `testing/rebrand.test.sh`, `testing/leak.test.sh`, `testing/placement.test.sh` (SU4) | +| The bootstrapped site installs, typechecks, lints, tests and builds at its landing; its stage lane builds (the secret step naming the Worker's keys and pushing none, no planted value in the bundle) and dry-deploys | `testing/e2e.test.sh` (SU4) | +| Served by `wrangler dev` from the lane's tree: no AUTH_SECRET → the deploy's smoke refuses it; `secret:dev`'s → the smoke passes, every page, `/auth/session` null, `/signin` saying what to connect, `/protected` denied, a 404; GitHub's keys → the button, an authorize URL with this site's callback and PKCE, a session cookie sealed with the Worker's secret opening `/protected`, one sealed with another secret refused, sign-out clearing it | `testing/e2e.test.sh` (SU4) | | The secret push and the deploy on a real account | only a live bootstrap (risk SU-A) | ## Departures from the upstream example diff --git a/specs/epics/sveltekit-auth/README.md b/specs/epics/sveltekit-auth/README.md index d7fb392..c8cebe2 100644 --- a/specs/epics/sveltekit-auth/README.md +++ b/specs/epics/sveltekit-auth/README.md @@ -13,7 +13,7 @@ the monorepo wrapper, tests and the deploy contract. | Field | Value | |-------|-------| -| Status | In progress — SU0 (#1), SU1 (#2) shipped; SU3 | +| Status | ✅ Shipped (`baseline-v1`) — SU0 (#1), SU1 (#2), SU3 (#3), SU4 (#4); proven offline in Baseline CI; not yet live (risk SU-A) | | Cluster | **SU** (SU0, SU1, SU3, SU4; SU2, the data rung, is not needed) | | Owner(s) | `apps/web` · `tooling/wire/worker-secrets.mjs` | | Builds on | `sveltekit-boilerplate`: its scaffolding, its adapter-cloudflare build and its one-landing blueprint; the reference starters' `worker-secrets.mjs` | diff --git a/specs/epics/sveltekit-auth/epic.yaml b/specs/epics/sveltekit-auth/epic.yaml index 8d7a03a..b20e783 100644 --- a/specs/epics/sveltekit-auth/epic.yaml +++ b/specs/epics/sveltekit-auth/epic.yaml @@ -9,7 +9,7 @@ metadata: spec: title: "Auth.js's SvelteKit example on Cloudflare Workers" summary: "Auth.js's SvelteKit example (nextauthjs/sveltekit-auth-example) — a home page, a sign-in page, a protected page and a sign-out over @auth/sveltekit with the example's 26 OAuth providers and JWT sessions — runs on Cloudflare Workers + Static Assets through @sveltejs/adapter-cloudflare, offers each provider only once its keys are stored (and says what to connect when none is), gets its AUTH_SECRET generated on each environment's Worker by the deploy instead of typed, and becomes an Orun baseline that takes a new site from nothing to live on stage and prod in one landing. No database: the sessions persist nothing server-side, so there is no data rung." - state: started + state: completed milestones: - name: "SU0 — the spec" exitCriteria: 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..be53ff9 --- /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 site'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 site's Docs library showed nothing for its +# component and the catalog failed it on docs and on runbook. A component +# also needs a description: it is the catalog's one-line answer to "what is +# this". +# +# And a domain may not share a component's name. The catalog keys entities by +# name, so a `web` domain (`spec.domain: web`) takes the `web` component's +# place, and the site's one deployable goes missing from its own catalog (as +# turso-starter's and the portfolio starter kit's live builds showed). +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 + if spec.get("domain"): + domains.setdefault(spec["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 100755 index 0000000..14f11d5 --- /dev/null +++ b/testing/e2e.test.sh @@ -0,0 +1,426 @@ +#!/usr/bin/env bash +# TIER 2 — the site a bootstrap produces builds, deploys (dry) and serves. +# +# placement.test.sh proves the tree a bootstrap ends with is the right tree. +# This proves it WORKS, by doing to it what its own pipelines will: +# +# 1. at the finished site, the landing's own checks — install with the +# lockfile the site ships, render fixtures, typecheck, lint, test, +# build. The bootstrap's own landings are checked in the box with +# `orun validate` and `orun plan` alone (`checks: local`; their PR's CI +# on an `orun/BASE-…` branch is `plan` alone, and the convergence on +# main builds, deploys and smoke-tests the site), and a later pull +# request of the site runs ci.yml's verify lanes, which build and +# dry-deploy it but do not lint or run the tests — so THIS is where a +# site those steps refuse is caught: before the tag, not after a build +# has merged it; +# 2. the stage lane's own steps, rendered by `orun plan` in the site: on a +# pull request (the verify profile) `build-app` — the component's +# buildCommand, the same step the deploy profile runs; `vite build`, where +# @sveltejs/adapter-cloudflare writes `_worker.js` and the static output +# to where wrangler.jsonc's `main` and `assets.directory` point — +# `verify-build-output` (the component's `workerEntrypoint` and +# `assetsDir`) and `deploy-dry-run` (`wrangler deploy --dry-run --config +# wrangler.jsonc --name <reponame>-web-stage`, which bundles the adapter's +# Worker). They run IN THE TREE THE RUNNER STAGES for the job +# (testing/lib/stage-job.py), with the dependency layout the pinned +# composition produces: if its install step is `scope: lane`, the +# top-level node_modules is a symlink to the source checkout's; if not, +# the job's own install step runs inside the staged tree. (Run in a plain +# checkout, the portfolio baseline's equivalent tier was green while its +# first live bootstrap's lanes died in the lane layout.); +# 3. serve the built Worker with `wrangler dev` FROM THAT STAGED TREE and run +# the component's OWN `smokeCommand` against it, verbatim — the check the +# real deploy ends with — three times over, as the site lives: +# a. with NO `AUTH_SECRET` (a Worker whose deploy lane never set one): +# Auth.js cannot read a session without it, and the smoke must refuse +# the site rather than call it live; +# b. with the secret `pnpm secret:dev` mints into `.env` (0600, kept on +# a second run) and no sign-in provider: the smoke passes, and every +# route the site promises answers — the home page's heading and title +# carry the site's name (escaped, not broken, by an `&` and an `'`), +# `/auth/session` is `null`, `/signin` says no provider is connected +# and what to connect, a sign-in attempt goes back there, `/protected` +# denies, the static files and the hashed `_app` chunks are served, +# and an unknown path is SvelteKit's 404 page; +# c. with GitHub's two keys set: `/signin` offers GitHub, and its form +# post is GitHub's authorize URL with this site's own callback; a +# session cookie minted with the Worker's AUTH_SECRET (Auth.js's own +# JWT encoding — what a finished OAuth callback sets) opens +# `/protected` and names the user, one minted with any other secret is +# no session, and signing out clears it. +# No value planted in the build's environment reaches the built Worker. +# +# What it cannot do is the platform's half: create the repository, mint the +# brokered Cloudflare token, deploy for real and probe workers.dev. That is a +# bootstrap against a workspace (BOOTSTRAP.md); everything short of it is here. +# +# Needs: orun, node, pnpm, python3 (+PyYAML), git, curl, and the network for +# `pnpm install` (or a warm store). A few minutes: two installs and builds +# (the landing's checks over the site, and the stage lane's own in its staged +# tree). +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 curl; do + command -v "$bin" >/dev/null || { echo "e2e.test.sh needs $bin on PATH" >&2; exit 1; } +done + +scratch="$(mktemp -d)" +dev_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 it is +# started as its own process group (setsid) and the whole group is stopped. +stop_dev() { + if [ -n "$dev_pid" ]; then + kill -TERM -- "-$dev_pid" 2>/dev/null || true + for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 -- "-$dev_pid" 2>/dev/null || break; sleep 0.5; done + kill -KILL -- "-$dev_pid" 2>/dev/null || true + dev_pid="" + fi +} +cleanup() { + stop_dev + rm -rf "$scratch" +} +trap cleanup EXIT +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 TURBO_TELEMETRY_DISABLED=1 + +# The landing's own checks, step for step, run here at once on the whole +# tree. A pull request in the site builds and dry-deploys it through ci.yml's +# lanes; the lint and the tests run here, and by hand before a push. +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 +} + +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 finished site ─────────────────────────────────────────────────── +echo "── the finished site: install, the fixture render, typecheck, lint, test, build" +checks "$tree" "$scratch/checks-site.log" + +# ── 2. the deploy lane's steps, for stage ────────────────────────────────── +echo "── the stage lane: build-app, verify-build-output, deploy-dry-run" +# The 01-product landing over the repository's empty first commit: every file +# of the site changed, as on its pull request. +s00="$(git -C "$tree" rev-parse HEAD~2)"; s01="$(git -C "$tree" rev-parse HEAD~1)" +(cd "$tree" && orun plan --intent intent.yaml --trigger github-pull-request --changed \ + --base "$s00" --head "$s01" --env stage --output "$scratch/plan.json") > "$scratch/plan.log" 2>&1 \ + || { echo "FAIL: orun plan" >&2; tail -15 "$scratch/plan.log" >&2; exit 1; } +python3 - "$scratch/plan.json" "$scratch/steps" <<'PY' +import json, pathlib, sys +plan = json.load(open(sys.argv[1])) +out = pathlib.Path(sys.argv[2]); out.mkdir() +job = next(j for j in plan["jobs"] if j["component"] == "web" and j["environment"] == "stage") +for s in job["steps"]: + if s["id"] in ("build-app", "verify-build-output", "deploy-dry-run"): + (out / f"{s['id']}.sh").write_text(s.get("run") or "") + if s["id"] == "install-workspace-dependencies": + (out / "install.sh").write_text(s.get("run") or "") + (out / "install.wd").write_text(s.get("working-directory") or ".") + (out / "install.scope").write_text(s.get("scope") or "job") +(out / "path").write_text(job.get("path") or "apps/web") +for k, v in (job.get("env") or {}).items(): + (out / "env").open("a").write(f"export {k}={json.dumps(v)}\n") +PY +# The job's private tree, staged as orun stages it. The source checkout +# carries no build output (a CI checkout has none, so the plain-tree build's is +# removed rather than copied in), and its dependencies are what the pinned +# composition says: a lane-scoped install ran once in the source tree (step 1 +# ran the same command) and is linked in, or the job installs its own. +rm -rf "$tree/apps/web/.svelte-kit" "$tree/apps/web/.wrangler" +work="$tree/.orun/runs/e2e/web.stage.verify-deploy/work" +[ -f "$scratch/steps/install.sh" ] || { echo "FAIL: the stage lane has no install step" >&2; exit 1; } +if [ "$(cat "$scratch/steps/install.scope")" = lane ]; then + python3 "$here/lib/stage-job.py" "$tree" "$work" --shared-deps + [ -L "$work/node_modules" ] || { echo "FAIL: the staged tree's node_modules is not the lane's symlink" >&2; exit 1; } + echo " staged: $(realpath --relative-to="$tree" "$work"); install scope: lane — node_modules → the source tree's" +else + python3 "$here/lib/stage-job.py" "$tree" "$work" + echo " staged: $(realpath --relative-to="$tree" "$work"); install scope: job — installing inside it" + echo " ▸ install-workspace-dependencies" + (cd "$work/$(cat "$scratch/steps/path")/$(cat "$scratch/steps/install.wd")" && bash -e "$scratch/steps/install.sh") \ + > "$scratch/install.log" 2>&1 || { echo "FAIL: the lane's install step" >&2; tail -30 "$scratch/install.log" >&2; exit 1; } + [ -d "$work/node_modules" ] && [ ! -L "$work/node_modules" ] \ + || { echo "FAIL: the job's install did not land inside its own tree" >&2; exit 1; } +fi +# Values planted where a deploy lane's optional secrets would be: the build +# must never see them (buildCommand unsets each before `vite build`), and with +# no Cloudflare credential (a verify lane binds none) worker-secrets.mjs +# names them and pushes nothing. +planted_auth="e2e-planted-auth-secret-$RANDOM$RANDOM" +planted_gh="e2e-planted-github-secret-$RANDOM$RANDOM" +for step in build-app verify-build-output deploy-dry-run; do + [ -f "$scratch/steps/$step.sh" ] || { echo "FAIL: the stage verify lane has no $step step" >&2; exit 1; } + echo " ▸ $step" + # The runner's per-job environment: the job's env (intent environment + # `env:`) and ORUN_ENVIRONMENT; the step runs in the component's directory. + if ! (cd "$work/$(cat "$scratch/steps/path")" && \ + { [ -f "$scratch/steps/env" ] && source "$scratch/steps/env"; true; } && \ + unset CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID && \ + export ORUN_ENVIRONMENT=stage AUTH_SECRET="$planted_auth" \ + AUTH_GITHUB_ID=e2e-planted-github-id AUTH_GITHUB_SECRET="$planted_gh" && \ + bash -e "$scratch/steps/$step.sh") > "$scratch/$step.log" 2>&1; then + echo "FAIL: the deploy lane's $step step" >&2; tail -40 "$scratch/$step.log" >&2; exit 1 + fi +done +grep -qF "worker-secrets: no Cloudflare credential in this job (a verify lane) — AUTH_GITHUB_ID, AUTH_GITHUB_SECRET, AUTH_SECRET reach $repo-web-stage from the deploy lane" \ + "$scratch/build-app.log" || { echo "FAIL: build-app did not hand the stage Worker its secrets as a verify lane does" >&2; tail -10 "$scratch/build-app.log" >&2; exit 1; } +if grep -rqsF -e "$planted_auth" -e "$planted_gh" "$work/apps/web/.svelte-kit" "$scratch/build-app.log" "$scratch/deploy-dry-run.log"; then + echo "FAIL: a secret in the build's environment reached the built Worker or a log" >&2; exit 1 +fi +for f in .env .dev.vars; do + [ ! -e "$work/apps/web/$f" ] || { echo "FAIL: the stage lane wrote a $f" >&2; exit 1; } +done +echo " the verify lane names the stage Worker's secrets and pushes none; none reaches the bundle" + +# ── 3. serve it, and smoke it as the deploy does ─────────────────────────── +port=$(python3 -c "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print(s.getsockname()[1]);s.close()") +url="http://127.0.0.1:$port" +web="$work/apps/web" +smoke="$(python3 -c "import yaml,sys;print(yaml.safe_load(open(sys.argv[1]))['spec']['parameters']['smokeCommand'])" "$tree/apps/web/component.yaml")" +start_dev() { # LOG + (cd "$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) > "$1" 2>&1 < /dev/null & + dev_pid=$! + for _ in $(seq 1 90); do + curl -s -o /dev/null "$url/robots.txt" && return 0 + kill -0 "$dev_pid" 2>/dev/null || { echo "FAIL: wrangler dev exited" >&2; tail -30 "$1" >&2; exit 1; } + sleep 1 + done + echo "FAIL: wrangler dev never answered" >&2; tail -30 "$1" >&2; exit 1 +} +routes() { # MODE: bare (a secret, no provider) | github (GitHub's keys set) + python3 - "$url" "$values" "$1" "$web" <<'PY' +import html, json, os, re, subprocess, sys, urllib.error, urllib.parse, urllib.request +base, values, mode, web = sys.argv[1], json.load(open(sys.argv[2])), sys.argv[3], sys.argv[4] +name = values["productname"] +problems = [] +def bad(m): problems.append(m) +class Stay(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *a, **k): return None +opener = urllib.request.build_opener(Stay) +def get(path, data=None, headers=None): + req = urllib.request.Request(base + path, data=data, headers=headers or {}) + try: + with opener.open(req, timeout=60) as r: + return r.status, r.headers, r.read() + except urllib.error.HTTPError as e: + return e.code, e.headers, e.read() +def text(fragment): + return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip() +def title(page): + m = re.search(r"<title>(.*?)", page, re.S) + return m and html.unescape(m.group(1)) +def post(path, fields, extra=None): + # As a browser posts a form: it asks for HTML, so an action's redirect is + # a redirect (asked for anything, SvelteKit answers an ActionResult). + headers = {"content-type": "application/x-www-form-urlencoded", "origin": base, "accept": "text/html", **(extra or {})} + return get(path, data=urllib.parse.urlencode(fields).encode(), headers=headers) +def jwt(secret): + # Auth.js's own encoding, from the @auth/core the site resolves: the + # cookie a finished OAuth callback sets, minus the provider round trip. + js = ("import{realpathSync}from'node:fs';import{join}from'node:path';import{pathToFileURL}from'node:url';" + "const c=join(realpathSync('node_modules/@auth/sveltekit'),'..','core');" + "const{encode}=await import(pathToFileURL(join(c,'jwt.js')).href);" + "process.stdout.write(await encode({token:{name:process.env.N,email:process.env.E,sub:'e2e-1'}," + "secret:process.env.S,salt:'authjs.session-token',maxAge:3600}))") + env = {**os.environ, "S": secret, "N": name, "E": "sam@acme.test"} + return subprocess.run(["node", "--input-type=module", "-e", js], cwd=web, env=env, + capture_output=True, text=True, check=True).stdout +def dev_var(key): + for line in open(os.path.join(web, ".env")): + k, _, v = line.rstrip("\n").partition("=") + if k == key: + return json.loads(v) if v.startswith('"') else v + return None + +# / — rendered by the Worker, the site's name on it. +status, _, body = get("/") +page = body.decode() +if status != 200: + bad(f"/ answered {status}") +h1 = re.search(r"]*>(.*?)", page, re.S) +if not h1 or text(h1.group(1)) != name: + bad(f"the home page's heading reads {h1 and text(h1.group(1))!r}, not {name!r}") +if title(page) != name: + bad(f"the home page's is {title(page)!r}, not {name!r}") +if "SvelteKit Auth Example" in page or "sveltekit-auth" in page.replace("sveltekit-auth-example", ""): + bad("the home page still carries the baseline's name") +for nav in ('href="/"', 'href="/protected"'): + if nav not in page: + bad(f"the home page's nav has no {nav}") + +if mode == "bare": + if "You are not signed in" not in page: + bad("the header does not say the visitor is not signed in") + # The hashed client chunks the home page boots from, and the static files. + chunks = sorted(set(re.findall(r"(_app/immutable/[^\"'\s)]+\.js)", page))) + if not chunks: + bad("the home page references no _app/immutable chunk") + for chunk in chunks[:3]: + s, h, _ = get("/" + chunk) + if s != 200 or "javascript" not in (h.get("content-type") or ""): + bad(f"/{chunk} answered {s} {h.get('content-type')}") + for path, ctype in (("/favicon.ico", "image/"), ("/robots.txt", "text/plain")): + s, h, _ = get(path) + if s != 200 or not (h.get("content-type") or "").startswith(ctype): + bad(f"{path} answered {s} {h.get('content-type')}, want 200 {ctype}") + + # Auth.js's own routes, answered by the Worker. + s, _, body = get("/auth/session") + if s != 200 or body.strip() != b"null": + bad(f"/auth/session answered {s} {body[:80]!r}, not 200 null") + s, _, body = get("/auth/providers") + if s != 200 or json.loads(body or b"null") != {}: + bad(f"/auth/providers answered {s} {body[:80]!r}, not 200 {{}}") + + # /signin, with nothing connected: says so, and what to connect. + s, _, body = get("/signin") + signin = body.decode() + if s != 200 or title(signin) != f"Sign in | {name}": + bad(f"/signin answered {s}, <title> {title(signin)!r}") + if 'data-providers="0"' not in signin or "No sign-in provider is connected to this site yet." not in signin: + bad("/signin does not say no provider is connected") + if "AUTH_GITHUB_ID" not in signin or "AUTH_GITHUB_SECRET" not in signin: + bad("/signin does not say which keys connect GitHub") + # The header's own Sign in button posts an empty providerId (Auth.js's + # default); a provider's button would name one. + if re.search(r'name="providerId" value="[^"]+"', signin): + bad("/signin offers a provider's sign-in button with no provider connected") + s, h, _ = post("/signin", {"providerId": "github"}) + if s != 303 or h.get("location") != "/signin": + bad(f"a sign-in with nothing connected answered {s} {h.get('location')}, not 303 /signin") + + # /protected, signed out. + s, _, body = get("/protected") + prot = body.decode() + if s != 200 or "<h1>Access Denied</h1>" not in prot or title(prot) != f"Protected | {name}": + bad(f"/protected, signed out, answered {s} without 'Access Denied'") + + # An unknown path is SvelteKit's own 404, rendered by the Worker. + s, _, body = get("/no-such-page") + nf = body.decode() + if s != 404 or "<h1>404</h1>" not in nf: + bad(f"/no-such-page answered {s} without SvelteKit's 404 page") + done = "/, the _app chunks, the static files, /auth/session, /auth/providers, /signin and its post, /protected, a 404" + +else: + s, _, body = get("/signin") + signin = body.decode() + if 'data-providers="1"' not in signin or "Sign in with GitHub" not in signin: + bad("/signin, with GitHub's keys set, does not offer GitHub") + if "No sign-in provider is connected" in signin: + bad("/signin still says nothing is connected") + if 'name="providerId" value="github"' not in signin: + bad("/signin's GitHub button does not post providerId=github") + s, _, body = get("/auth/providers") + provs = json.loads(body or b"{}") + if list(provs) != ["github"] or provs["github"].get("callbackUrl") != f"{base}/auth/callback/github": + bad(f"/auth/providers answered {provs}, not GitHub with this site's callback") + s, h, _ = post("/signin", {"providerId": "github"}) + loc = urllib.parse.urlsplit(h.get("location") or "") + q = urllib.parse.parse_qs(loc.query) + if s != 302 or f"{loc.scheme}://{loc.netloc}{loc.path}" != "https://github.com/login/oauth/authorize": + bad(f"a GitHub sign-in answered {s} {h.get('location')!r}, not GitHub's authorize URL") + if q.get("client_id") != [dev_var("AUTH_GITHUB_ID")] or q.get("redirect_uri") != [f"{base}/auth/callback/github"]: + bad(f"GitHub's authorize URL carries client_id {q.get('client_id')} and redirect_uri {q.get('redirect_uri')}") + if "code_challenge" not in q: + bad("the GitHub sign-in carries no PKCE challenge") + if dev_var("AUTH_GITHUB_SECRET") in (h.get("location") or ""): + bad("the GitHub client secret is in the authorize URL") + + # A session: Auth.js's JWT, sealed with the Worker's own AUTH_SECRET. + jar = {"cookie": f"authjs.session-token={jwt(dev_var('AUTH_SECRET'))}"} + s, _, body = get("/auth/session", headers=jar) + sess = json.loads(body or b"null") or {} + if s != 200 or (sess.get("user") or {}).get("email") != "sam@acme.test": + bad(f"/auth/session with the site's own session answered {s} {body[:100]!r}") + s, _, body = get("/protected", headers=jar) + prot = body.decode() + if "<h1>Protected page</h1>" not in prot or "sam@acme.test" not in prot or "Session expiry:" not in prot: + bad("/protected, signed in, does not show the protected page and who is signed in") + if "You are not signed in" in prot: + bad("the header, signed in, still says the visitor is not signed in") + # One sealed with any other secret is no session at all. + other = {"cookie": f"authjs.session-token={jwt('not-this-sites-secret-' + 'x' * 32)}"} + s, _, body = get("/auth/session", headers=other) + if body.strip() != b"null": + bad(f"a session sealed with another secret was accepted: {body[:100]!r}") + s, _, body = get("/protected", headers=other) + if "<h1>Access Denied</h1>" not in body.decode(): + bad("/protected opened for a session sealed with another secret") + # Signing out clears it. + s, h, _ = post("/signout", {}, jar) + cleared = [c for c in (h.get_all("set-cookie") or []) if c.startswith("authjs.session-token=")] + if s not in (302, 303) or not cleared or "max-age=0" not in cleared[0].lower().replace(" ", ""): + bad(f"sign-out answered {s} {cleared}, without clearing the session cookie") + elif "httponly" not in cleared[0].lower(): + bad("the session cookie is not httpOnly") + done = "/signin offers GitHub and posts to its authorize URL; a session opens /protected, another secret's does not; sign-out clears it" + +if problems: + for p in problems: + print(f" ✕ {p}", file=sys.stderr) + sys.exit(1) +print(f" {done}") +PY +} + +echo "── wrangler dev over the built Worker, with no AUTH_SECRET" +start_dev "$scratch/dev-bare.log" +echo " ▸ the component's own smokeCommand refuses it, DEPLOYED_URL=$url" +if DEPLOYED_URL="$url" bash -c "$smoke" > "$scratch/smoke-nosecret.log" 2>&1; then + echo "FAIL: the deploy's smoke passed a Worker with no AUTH_SECRET, which cannot read a session" >&2; exit 1 +fi +stop_dev + +echo "── pnpm secret:dev, then wrangler dev with the secret and no provider" +(cd "$web" && pnpm run secret:dev) > "$scratch/secret-dev.log" 2>&1 \ + || { echo "FAIL: pnpm secret:dev" >&2; tail -10 "$scratch/secret-dev.log" >&2; exit 1; } +[ "$(stat -c %a "$web/.env")" = 600 ] || { echo "FAIL: .env is not 0600" >&2; exit 1; } +first="$(grep '^AUTH_SECRET=' "$web/.env" || true)" +[ "${#first}" -ge 55 ] || { echo "FAIL: .env carries no generated AUTH_SECRET" >&2; exit 1; } +(cd "$web" && pnpm run secret:dev) >> "$scratch/secret-dev.log" 2>&1 +[ "$(grep '^AUTH_SECRET=' "$web/.env")" = "$first" ] || { echo "FAIL: a second secret:dev replaced the secret" >&2; exit 1; } +val="${first#AUTH_SECRET=}"; val="${val//\"/}" +if grep -qF -- "$val" "$scratch/secret-dev.log"; then echo "FAIL: secret:dev printed the secret" >&2; exit 1; fi +start_dev "$scratch/dev.log" +echo " ▸ the component's own smokeCommand, DEPLOYED_URL=$url" +DEPLOYED_URL="$url" bash -c "$smoke" || { echo "FAIL: the deploy's smoke refused the site" >&2; exit 1; } +echo " ▸ every route the site promises, signed out" +routes bare +stop_dev + +echo "── wrangler dev with GitHub's keys" +printf 'AUTH_GITHUB_ID="e2e-github-client-id"\nAUTH_GITHUB_SECRET="e2e-github-client-secret-%s"\n' "$RANDOM" >> "$web/.env" +start_dev "$scratch/dev-github.log" +DEPLOYED_URL="$url" bash -c "$smoke" || { echo "FAIL: the deploy's smoke refused the site with a provider" >&2; exit 1; } +echo " ▸ sign-in, a session, sign-out" +routes github +stop_dev + +echo "e2e.test.sh: ok" diff --git a/testing/fixtures/acme.json b/testing/fixtures/acme.json new file mode 100644 index 0000000..efe0431 --- /dev/null +++ b/testing/fixtures/acme.json @@ -0,0 +1,22 @@ +{ + "_comment": [ + "The inputs the placement and leak gates render with. Acme is not a real", + "site 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 site name with an apostrophe and an ampersand (both legal in", + "the card's pattern, both special in JavaScript strings and HTML), a", + "hyphenated repo slug that CONTAINS the word `sveltekit`, 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 site 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-sveltekit", + "productname": "Sam's Notes & Links", + "githuborg": "acme-inc", + "subdomain": "acme", + "orunWorkspace": "ws_0000000000000000000000000000000f", + "epicSlug": "sveltekit-auth-baselining" +} diff --git a/testing/fixtures/baseline-identity.sveltekit-auth.json b/testing/fixtures/baseline-identity.sveltekit-auth.json new file mode 100644 index 0000000..6c9ca2d --- /dev/null +++ b/testing/fixtures/baseline-identity.sveltekit-auth.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/src/site.ts (upstream's own heading, 'SvelteKit Auth Example'); `pascal` is also the name of Auth.js's `SvelteKitAuth`, which the engine protects where the app imports and calls it (UPSTREAM in rebrand.mjs); `domain` and `subdomain` are placeholders, because this baseline has never deployed under a name of its own; `githubOwner` is the owner in the repository's source links.", + "slug": "sveltekit-auth", + "pascal": "SvelteKitAuth", + "productName": "SvelteKit Auth Example", + "domain": "sveltekit-auth.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..8a53e23 --- /dev/null +++ b/testing/leak.test.sh @@ -0,0 +1,118 @@ +#!/usr/bin/env bash +# THE LEAK GATE — what a site carries, and what stays in the factory. +# +# A site built from this baseline is somebody's site, not a copy of this +# repository. It gets the product: the app (its tests inside it), its CI, its +# tooling, its README 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 — nor `tooling/migrations`, a D1 manifest check +# for a database the site does not have. +# +# This asks orun to DERIVE the placement — every file every phase would write +# — and gates that set. Derivation runs no hooks, contacts nothing and writes +# nothing. testing/placement.test.sh gates the same rules over a tree that is +# actually placed and branded. +# +# Needs: orun + python3. No network, no credential. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +command -v orun >/dev/null || { echo "leak.test.sh needs orun on PATH" >&2; exit 1; } + +scratch="$(mktemp -d)" +trap 'rm -rf "$scratch"' EXIT + +echo "── deriving what every phase would place" +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" + +python3 - "$scratch/status.json" "$root" <<'PY' +import json, pathlib, re, sys + +status = json.load(open(sys.argv[1])) +root = pathlib.Path(sys.argv[2]) +problems = [] +def bad(m): problems.append(m) + +# Against an empty output directory every file a phase places is "missing", so +# the union of those lists IS the site's file set. +placed = sorted({f for ph in status["phases"] for f in (ph.get("missing") or [])}) +if len(placed) < 50: + sys.exit(f"only {len(placed)} files derived — the tree is not a site") + +# ── 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 site 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/", "tooling/migrations/", + ".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 site") + +# ── nothing local and nothing built ─────────────────────────────────────── +LOCAL = re.compile(r"(^|/)(\.env(\.[^/]*\.local|\.local)?|\.dev\.vars(\..*)?|node_modules|" + r"\.svelte-kit|\.wrangler|\.turbo|\.orun|[^/]*\.tsbuildinfo)(/|$)") +for p in placed: + if LOCAL.search(p): + bad(f"{p} would ship — a local or built file of whoever ran the bootstrap") + +# ── the site's README, not this repository's ────────────────────────────── +if "README.md" not in placed: + bad("README.md would not ship") +for must in (".github/workflows/ci.yml", + "apps/web/component.yaml", "apps/web/wrangler.jsonc", "apps/web/src/site.ts", + "apps/web/src/site.test.ts", ".rebrand/values.json", "apps/web/.env.example", + "apps/web/LICENSE", "apps/web/src/auth.ts", + "apps/web/src/server/providers.ts", "tooling/wire/worker-secrets.mjs"): + if must not in placed: + bad(f"{must} would not ship, and a site needs it") + +# ── 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 site 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", + "ai/context/operations.md": "ai/context/operations.md", + "ai/context/deployment.md": "ai/context/deployment.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 site about the factory: {line.strip()[:80]}") + +if problems: + print("FAIL: the site would carry the baseline:", file=sys.stderr) + for p in problems: + print(f" - {p}", file=sys.stderr) + sys.exit(1) + +print(f" {len(placed)} files derived across every phase") +print(f" ai/context is exactly {len(ALLOWED_AI)} declared file(s); none of the " + f"{len(NEVER)} factory paths; nothing local or 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..4289b20 --- /dev/null +++ b/testing/lib/bootstrap.sh @@ -0,0 +1,71 @@ +#!/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 site 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; +# - the repository's first commit is an empty one, as on the real thing: +# the platform's landing opens the first pull request against an empty +# "Initial commit" by `orun`, and that commit is the base the first +# landing's push is planned against; +# - `link` (a `run:` hook that calls `orun cloud`) is skipped — it needs a +# workspace; +# - `{{ .inputs.* }}` render from the fixture. +# Everything else — the rebrand, the re-tenant, the work-tree strip, the +# deferrals and their restore, the retouch marker, the deployment-docs +# render — runs exactly as declared. +# +# 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"/{apps,infra,packages,tests} "$logs" + for d in apps infra packages tests; do touch "$tree/$d/.gitkeep"; done + ( + cd "$tree" + git init -q -b main + git config user.email bootstrap@example.invalid + git config user.name "offline bootstrap" + git commit -q --allow-empty -m "Initial commit" + ) || { echo "FAIL: the repository's first commit" >&2; return 1; } + + 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/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..e7b4c84 --- /dev/null +++ b/testing/lib/stage-job.py @@ -0,0 +1,84 @@ +#!/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 a sibling baseline (portfolio-starter-kit, Next.js 16) died in +the --shared-deps layout — Turbopack refuses a dependency that resolves +outside its project root ("Symlink … points out of the filesystem root") — in +a lane its e2e tier had run green over a plain checkout. This site's Vite +build is staged the same way, so the layout the pinned composition plans is +the layout it is tested in. +""" +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..a834d4d --- /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 — + # `githuborg`, `epicSlug`, `domain`, `orunWorkspace` and the identity + # defaults are how a BUILD is driven, not what a product is configured + # with. What must hold is that nothing this file declares arrives at an + # engine that cannot take it. + if bp is not None: + bp_inputs = set((bp.get("inputs") or {}).keys()) + if not bp_inputs: + B("repo-blueprint.yaml declares no inputs — this check has gone blind") + for key in [f.get("key") for f in (spec.get("inputs") or [])]: + if key and key not in bp_inputs: + B(f"inputs[{key}] is not an input of repo-blueprint.yaml — the " + f"console would resolve it and the engine would refuse it " + f"(orun fails closed on an undeclared --set)") + + # ── …AND THE OTHER DIRECTION, for REQUIRED inputs only ─────────────── + # + # The check above is one-directional on purpose: the blueprint declares + # more than this card does, because `epicSlug`, `domain` 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..5db92e0 --- /dev/null +++ b/testing/phases.test.sh @@ -0,0 +1,338 @@ +#!/usr/bin/env bash +# The phases in `repo-blueprint.yaml` must be the phases the bootstrap runs, +# placing what they are meant to place, saying what they are, and naming only +# what the engine can resolve. +# +# The partition below is the bootstrap's order, written down a second time on +# purpose: the order is load-bearing (the deployment record cannot be written +# before the site is live), and a module that drifts into another phase fails +# at landing time, live, with nothing in this repository having looked wrong. +# Moving one is a deliberate change, argued in the diff that edits both places. +# +# ONE LANDING BUILDS THE SITE (SK-5, cirrus-baseline baseline-v22's shape): +# 01-product places every module, and 03-docs only records. +# +# And the shape that keeps a bootstrap fast (orun >= v2.88.0, turso-starter +# baseline-v8's): 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") + +PARTITION = { + # One deployable component, `web`: the site's tests run inside it + # (apps/web's vitest), so there is no test package to place beside it. + "01-product": ["ai-deployment", "ai-operations", "discovery-roots", "github-workflows", + "rebrand-values", "root-gitignore", "root-intent", + "root-package-json", "root-pnpm-lock", + "root-pnpm-workspace", "root-readme", "root-turbo", "tooling-eslint", + "tooling-tsconfig", "tooling-wire", "vscode", "web"], + "03-docs": [], +} +HOOK_ONLY = {"03-docs"} +# The phases that DEPLOY, and so must give a re-run something to land. +DEPLOYS = {"01-product"} +# Each phase's pre, post and await hooks, in order — the one-landing recipe. +# The brokered keys are one `secrets` reconcile. 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. 03-docs awaits nothing: +# its render probes as it writes, and its landing redeploys nothing. +PRE = {"01-product": [], "03-docs": []} +POST = { + "01-product": ["retouch", "git-init", "git-stage", "rebrand", "orun-workspace", "work-tree", + "promotion", "dev-lanes", "git-restage", "rebrand-verify", + "repo", "link", "secrets", "task", "land"], + "03-docs": ["promotion", "dev-lanes", "render", "task", "land"], +} +AWAIT = {"01-product": ["converge", "verify"], "03-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 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 ──────────────── +# A hook-only phase places no files, so orun derives it as `unknown`, and +# `requires.phases` fails closed on `unknown`: a requirement naming one can +# never be satisfied. +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") + +# ── 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 []) + +# ── 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 hooks run in the one-landing 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.items(): + got = [h.get("id") for h in ((by_name.get(name, {}).get("hooks") or {}).get("post") or [])] + if got != want: + bad(f"phase {name}'s post hooks are {got}; the one-landing order is {want}") +for name, want in AWAIT.items(): + got = [h.get("id") for h in ((by_name.get(name, {}).get("hooks") or {}).get("await") or [])] + if got != want: + bad(f"phase {name}'s await hooks are {got}; want {want}") +for p in phases: + if p["name"] not in DEPLOYS: + for h in hooks_of(p): + if (h.get("uses") or "").startswith(("orun.integrations/reconcile@", "orun.run/watch@")): + bad(f"phase {p['name']} deploys nothing and runs {h['uses']} ({h.get('id')})") + +# ── 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") +# A `pre` hook on the task plane would wait for that background at once, +# before the phase had placed a file — the old order, whatever its id. +TASK_PLANE = ("orun.task/", "orun.pr/") +for p in phases: + for h in ((p.get("hooks") or {}).get("pre") or []): + if (h.get("uses") or "").startswith(TASK_PLANE): + bad(f"phase {p['name']}'s pre hook {h.get('id')} uses {h['uses']}, which waits for the " + f"background task set-up — find the task in `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") + +# ── 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}") + +# ── 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") + +for p in phases: + n = p.get("narrate") or {} + ids = {h.get("id") for h in hooks_of(p)} + awaits = bool((p.get("hooks") or {}).get("await")) + for slot in ("start", "await", "done", "failed"): + line = n.get(slot) + if slot == "await" and not awaits: + # A phase that waits on nothing never says its await line. + if line: + bad(f"phase {p['name']} declares narrate.await and has no await hooks — " + f"nobody would ever read it") + continue + if not line: + 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 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")) +print(f" {len(phases)} phases, {placed_n} modules, {len(HOOK_ONLY)} hook-only — in execution order") +print(f" {narrated} authored narration lines, every reference resolving") +PY + +echo "phases.test.sh: ok" diff --git a/testing/placement.test.sh b/testing/placement.test.sh new file mode 100755 index 0000000..311d317 --- /dev/null +++ b/testing/placement.test.sh @@ -0,0 +1,287 @@ +#!/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) — every phase placed in +# order onto what the previous one landed, finished by the blueprint's OWN +# `run:` hooks (rebrand, re-tenant, work-tree strip, the deferrals, the +# retouch marker, the deployment record), each landing a commit; +# 3. the product it ends with: branded with no residue, carrying nothing of +# the factory, re-tenanted, its gates restored, its record rendered; +# 4. what the product's own CI would do with the 01-product merge: `orun +# plan` for a push to main over exactly that commit, onto the +# repository's empty first commit — the site deployed to stage and prod +# side by side, nothing on dev, the Worker, the smoke and the secret refs +# the product's own; +# 5. a `--resume` over the finished site places nothing and un-brands nothing. +# +# testing/e2e.test.sh goes on from here: it installs, builds and serves the +# product and runs its smoke against 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"/{apps,infra,packages,tests} +for d in apps infra packages tests; do touch "$whole/$d/.gitkeep"; done +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 50 ] || fail "only $n files placed — that is not a site" +[ "$fails" -eq 0 ] && echo " $n files placed; the repo-scale gate ran" + +# ── 2. the offline bootstrap ─────────────────────────────────────────────── +echo "── the offline bootstrap: every phase, its 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" = 3 ] || fail "the repository has $commits commits, not its first one and one per phase (1 + 2)" + +# ── 3. the product it ends with ──────────────────────────────────────────── +echo "── the site 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 site:"; 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 = values["reponame"], values["githuborg"], values["productname"], values["subdomain"] + +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/", "tooling/migrations/", + ".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 site — it is the factory") + if re.search(r"(^|/)(\.env(\.local)?|\.dev\.vars|node_modules|\.orun|\.svelte-kit|\.wrangler)(/|$)", p): + bad(f"{p} is in the site — a local or built file") + +# …and no file the site carries NAMES the factory: a comment pointing at +# `testing/` or a link into `specs/` is a dangling reference in somebody +# else's repository. (The baseline's intent.yaml names `specs/` and `tasks/` +# in its `work:` block; 01-product strips the block, so the site's must not.) +FACTORY_REF = re.compile(r"testing/|repo-blueprint|specs/|(^|[^A-Za-z0-9_-])tasks/|BOOTSTRAP\.md|\.baseline/|docs/phases") +for p in tracked: + if p.startswith(".rebrand/"): + continue + try: + text = (tree / p).read_text() + except (UnicodeDecodeError, IsADirectoryError): + continue + for n, line in enumerate(text.splitlines(), 1): + if FACTORY_REF.search(line): + bad(f"{p}:{n} names the factory: {line.strip()[:80]}") +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 site is {sorted(ai)}") + +# The identity, where the site carries it. +site = (tree / "apps/web/src/site.ts").read_text() +if f"SITE_NAME = {json.dumps(name)}\n" not in site: + bad(f"apps/web/src/site.ts does not name the site {name!r}") + +# The upstream's own names contain the baseline's slug and its Pascal form; +# the rebrand that renamed everything else must have left every one alone. +auth = (tree / "apps/web/src/auth.ts").read_text() +for keep in ('import { SvelteKitAuth } from "@auth/sveltekit"', + "export const { handle, signIn, signOut } = SvelteKitAuth(async (event) => {"): + if keep not in auth: + bad(f"apps/web/src/auth.ts lost Auth.js's own {keep.split()[0]!r} line: the rebrand renamed the package's API") +if json.loads((tree / "apps/web/package.json").read_text())["dependencies"].get("@auth/sveltekit") is None: + bad("apps/web/package.json no longer depends on @auth/sveltekit") +lic = (tree / "apps/web/LICENSE").read_text() +if "ISC License" not in lic or "Balázs Orbán" not in lic: + bad("apps/web/LICENSE is not the upstream example's ISC licence and credit") +if "https://github.com/nextauthjs/sveltekit-auth-example" not in (tree / "README.md").read_text(): + bad("README.md no longer credits github.com/nextauthjs/sveltekit-auth-example") +for p in tracked: + if p.startswith(".rebrand/"): + continue + try: + body = (tree / p).read_text() + except (UnicodeDecodeError, IsADirectoryError): + continue + left = body.replace("sveltekit-auth-example", "").replace('import { SvelteKitAuth } from "@auth/sveltekit"', "") \ + .replace("= SvelteKitAuth(async (event)", "") + for n, line in enumerate(left.splitlines(), 1): + if re.search(r"sveltekit-auth|SvelteKitAuth|SVELTEKIT_AUTH", line): + bad(f"{p}:{n} still carries the baseline's name: {line.strip()[:80]}") +comp = yaml.safe_load((tree / "apps/web/component.yaml").read_text())["spec"]["parameters"] +if comp["workerName"] != f"{repo}-web": + bad(f"workerName is {comp['workerName']}, not {repo}-web") +if comp["workersDevSubdomain"] != sub: + bad(f"workersDevSubdomain is {comp['workersDevSubdomain']}, not {sub}") +wrangler = json.loads(re.sub(r"^\s*//.*$", "", (tree / "apps/web/wrangler.jsonc").read_text(), flags=re.M)) +if wrangler["name"] != f"{repo}-web": + bad(f"wrangler.jsonc names the Worker {wrangler['name']}, not {repo}-web") +# The adapter writes where wrangler.jsonc says, and the deploy reads what the +# component says: the two must name the same Worker entry and assets. +if wrangler["main"] != comp["workerEntrypoint"] or wrangler["assets"]["directory"] != comp["assetsDir"]: + bad(f"wrangler.jsonc ({wrangler['main']}, {wrangler['assets']['directory']}) and the component " + f"({comp['workerEntrypoint']}, {comp['assetsDir']}) disagree on the adapter's output") +if json.loads((tree / "package.json").read_text())["name"] != repo: + bad("package.json is not named for the site") + +# 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"] != values["orunWorkspace"]: + bad(f"intent workspace is {intent['execution']['state']['workspace']}, not the site'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 03-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 03-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}") +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 site does not have") + +# The landings, as the phases made them. +if not re.search(r"^# orun: redeploy 01-product \S+$", (tree / "apps/web/component.yaml").read_text(), re.M): + bad("apps/web/component.yaml carries no 01-product redeploy marker") +dep = (tree / "ai/context/deployment.md").read_text() +if "GENERATED by the `03-docs` phase" not in dep or f"https://{repo}-web-prod.{sub}.workers.dev" not in dep: + bad("ai/context/deployment.md was not rendered for the site") +readme = (tree / "README.md").read_text() +if not readme.startswith(f"# {repo}\n") or "This site is **live**" not in readme: + bad("README.md is not the site's, or its live-deployment section was not rendered") + +# 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", "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, gates restored, record rendered") +PY + +# ── 4. the product's own CI, over the 01-product merge ───────────────────── +# The one landing's push: from the repository's empty first commit to the +# whole site, as main sees it the moment the pull request merges. +echo "── orun plan in the site, for the push that merged 01-product" +s00="$(git -C "$tree" rev-parse HEAD~2)"; s01="$(git -C "$tree" rev-parse HEAD~1)" +git -C "$tree" checkout -q "$s01" +(cd "$tree" && orun validate --intent intent.yaml) > "$scratch/validate.log" 2>&1 \ + || { fail "orun validate refused the site's intent at 01-product"; tail -10 "$scratch/validate.log" >&2; } +(cd "$tree" && orun plan --intent intent.yaml --trigger github-push-main --changed \ + --base "$s00" --head "$s01" --output "$scratch/plan.json") > "$scratch/plan.log" 2>&1 \ + || { fail "orun plan failed in the site at 01-product"; tail -15 "$scratch/plan.log" >&2; } +git -C "$tree" checkout -q main +python3 - "$scratch/plan.json" "$values" <<'PY' || fails=$((fails + 1)) +import json, sys +plan, values = json.load(open(sys.argv[1])), json.load(open(sys.argv[2])) +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"]} +if set(jobs) != {("web", "stage"), ("web", "prod")}: + bad(f"the 01-product merge plans {sorted(jobs)}; it must deploy web to stage and prod and nothing else") +for (comp, env), j in jobs.items(): + if not j["profile"].endswith(".deploy"): + bad(f"{comp}@{env} plans profile {j['profile']}, not a deploy") + if j.get("dependsOn"): + bad(f"{comp}@{env} waits on {j['dependsOn']} — during the bootstrap stage and prod deploy side by side") + steps = {s["id"]: s.get("run") or "" for s in j["steps"]} + for need in ("build-app", "deploy", "smoke"): + if need not in steps: + bad(f"{comp}@{env} has no {need} step") + if f'EFFECTIVE_WORKER_NAME="{repo}-web-{env}"' not in steps.get("deploy", ""): + bad(f"{comp}@{env} deploys a Worker not named {repo}-web-{env}") + if f'DEPLOYED_URL="https://${{EFFECTIVE_WORKER_NAME}}.${{WORKERS_DEV_SUBDOMAIN}}.workers.dev"' not in steps.get("smoke", "") \ + or f'WORKERS_DEV_SUBDOMAIN="{sub}"' not in steps.get("smoke", ""): + bad(f"{comp}@{env}'s smoke does not target the site's own workers.dev URL") + if '"${DEPLOYED_URL}/auth/session"' not in steps.get("smoke", "") or '[ "${session}" = "null" ]' not in steps.get("smoke", ""): + bad(f"{comp}@{env}'s smoke is not the site's") + refs = {r["asEnv"]: r["ref"] for r in j.get("secretRefs") or []} + # AUTH_SECRET and the providers' keys: optional, the site's own refs. + for key in ("AUTH_SECRET", "AUTH_GITHUB_ID", "AUTH_GITHUB_SECRET"): + ref = refs.get(key, "") + if ref != f"secret://{ws}/{repo}/{env}/{key}": + bad(f"{comp}@{env} resolves {key} from {ref or 'nowhere'} — not the site's own secret for {env}") + if f'--worker "{repo}-web-${{ORUN_ENVIRONMENT}}"' not in steps.get("build-app", ""): + bad(f"{comp}@{env}'s build hands its secrets to a Worker not named {repo}-web-<env>") + for key in ("CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID"): + ref = refs.get(key, "") + if not ref.startswith(f"secret://{ws}/") or f"project:{repo}" not in ref: + bad(f"{comp}@{env} resolves {key} from {ref or 'nowhere'} — not the site's workspace and project") +if problems: + for p in problems: + print(f" ✕ {p}", file=sys.stderr) + sys.exit(1) +print(f" web → stage + prod, deploy, side by side; Worker, smoke and secrets the site's own") +PY + +# ── 5. a resume over the finished site ──────────────────────────────────── +echo "── --resume over the finished site" +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 site:"; git -C "$tree" status --short | head -10 >&2; } +grep -q "SITE_NAME = \"Sam's Notes & Links\"" "$tree/apps/web/src/site.ts" \ + || fail "--resume reverted the site'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..6bcfa99 --- /dev/null +++ b/testing/rebrand.test.sh @@ -0,0 +1,190 @@ +#!/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 — a source link, the site-name seam, the worker name (in the component +# and in wrangler.jsonc), the environment URLs, the placeholder domain, a +# secret ref — and each runs through as many passes as a bootstrap +# makes (every phase re-runs the rebrand over everything already placed), so a +# value written by an early phase must survive every later one unchanged. +# +# The identity is PINNED (fixtures/baseline-identity.sveltekit-auth.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.sveltekit-auth.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-notes","productname":"Acme Notes","productdomain":"acme.dev","githuborg":"acme-inc","subdomain":"acme","orunWorkspace":"ws_79BDXAZQ"}' + +echo "── rebrand: the site's own identity" +check "a source link names the product's owner and repository" \ + "$acme" README.md \ + 'Source: https://github.com/sourceplane/sveltekit-auth' \ + 'Source: https://github.com/acme-inc/acme-notes' +check "the site-name seam takes the product's name" \ + "$acme" apps/web/src/site.ts 'export const SITE_NAME = "SvelteKit Auth Example"' \ + 'export const SITE_NAME = "Acme Notes"' +check "…and stays a valid string for a name with an apostrophe and an ampersand" \ + '{"reponame":"sams-notes","productname":"Sam'"'"'s Notes & Links","productdomain":"sam.dev"}' \ + apps/web/src/site.ts 'export const SITE_NAME = "SvelteKit Auth Example"' \ + 'export const SITE_NAME = "Sam'"'"'s Notes & Links"' +check "the display name elsewhere is content, and is left alone" \ + "$acme" apps/web/README.md 'Auth.js'"'"'s SvelteKit Auth Example, on Workers.' \ + 'Auth.js'"'"'s SvelteKit Auth Example, on Workers.' +check "the worker name is re-prefixed, the environment suffix kept" \ + "$acme" apps/web/component.yaml 'workerName: sveltekit-auth-web' \ + 'workerName: acme-notes-web' +check "…and so is the Worker the deploy lane hands its secrets to" \ + "$acme" apps/web/component.yaml 'node ../../tooling/wire/worker-secrets.mjs --worker "sveltekit-auth-web-${ORUN_ENVIRONMENT}" --config wrangler.jsonc' \ + 'node ../../tooling/wire/worker-secrets.mjs --worker "acme-notes-web-${ORUN_ENVIRONMENT}" --config wrangler.jsonc' +check "…and so is the name wrangler.jsonc carries" \ + "$acme" apps/web/wrangler.jsonc ' "name": "sveltekit-auth-web",' \ + ' "name": "acme-notes-web",' +check "an environment URL: worker name and subdomain" \ + "$acme" intent.yaml \ + ' url: https://sveltekit-auth-web-stage.your-workers-subdomain.workers.dev' \ + ' url: https://acme-notes-web-stage.acme.workers.dev' +check "the placeholder domain is the product's domain, not a renamed slug" \ + "$acme" intent.yaml ' BASE_DOMAIN: sveltekit-auth.example.com' \ + ' BASE_DOMAIN: acme.dev' +check "no domain given: the reserved placeholder, for an owner to replace later" \ + '{"reponame":"acme-notes","productname":"Acme Notes","githuborg":"acme-inc","subdomain":"acme"}' \ + intent.yaml ' BASE_DOMAIN: sveltekit-auth.example.com' \ + ' BASE_DOMAIN: acme-notes.example.com' +check "an empty domain is no domain" \ + '{"reponame":"acme-notes","productname":"Acme Notes","productdomain":""}' \ + intent.yaml ' BASE_DOMAIN: sveltekit-auth.example.com' \ + ' BASE_DOMAIN: acme-notes.example.com' +check "the repo slug" \ + "$acme" package.json ' "name": "sveltekit-auth",' \ + ' "name": "acme-notes",' +check "a secret ref names the product's workspace and project" \ + "$acme" apps/web/component.yaml 'T: secret://ws_KWQ45Z6M/sveltekit-auth/stage/CLOUDFLARE_API_TOKEN' \ + 'T: secret://ws_79BDXAZQ/acme-notes/stage/CLOUDFLARE_API_TOKEN' +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' +check "without githuborg a source link keeps the baseline's owner" \ + '{"reponame":"acme-notes","productname":"Acme Notes","productdomain":"acme.dev"}' \ + README.md 'Source: https://github.com/sourceplane/sveltekit-auth' \ + 'Source: https://github.com/sourceplane/acme-notes' + +echo "── rebrand: the upstream's own names, which contain the slug, are never rewritten" +check "Auth.js's SvelteKitAuth import (the slug's Pascal form) stays the package's" \ + "$acme" apps/web/src/auth.ts 'import { SvelteKitAuth } from "@auth/sveltekit"' \ + 'import { SvelteKitAuth } from "@auth/sveltekit"' 3 +check "…and so does the one call" \ + "$acme" apps/web/src/auth.ts 'export const { handle, signIn, signOut } = SvelteKitAuth(async (event) => {' \ + 'export const { handle, signIn, signOut } = SvelteKitAuth(async (event) => {' 3 +check "the example's repository keeps its name" \ + "$acme" README.md 'Upstream: https://github.com/nextauthjs/sveltekit-auth-example (ISC)' \ + 'Upstream: https://github.com/nextauthjs/sveltekit-auth-example (ISC)' 3 +check "…beside this repository's own link, which is renamed" \ + "$acme" README.md 'From github.com/nextauthjs/sveltekit-auth-example to https://github.com/sourceplane/sveltekit-auth.' \ + 'From github.com/nextauthjs/sveltekit-auth-example to https://github.com/acme-inc/acme-notes.' 3 +check "the package it is built on is not a slug" \ + "$acme" apps/web/package.json ' "@auth/sveltekit": "1.11.3"' \ + ' "@auth/sveltekit": "1.11.3"' + +echo "── rebrand: a written value is not rewritten, in any later pass" +contains='{"reponame":"sveltekit-auth-2","productname":"SvelteKit Auth Example 2","productdomain":"sveltekit-auth.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": "sveltekit-auth",' \ + ' "name": "sveltekit-auth-2",' 3 +check "a worker name built on it survives three passes" \ + "$contains" apps/web/component.yaml 'workerName: sveltekit-auth-web' \ + 'workerName: sveltekit-auth-2-web' 3 +check "a domain containing the baseline's domain survives three passes" \ + "$contains" intent.yaml 'BASE_DOMAIN: sveltekit-auth.example.com' \ + 'BASE_DOMAIN: sveltekit-auth.example.com.au' 3 +check "a subdomain containing the placeholder survives three passes" \ + "$contains" apps/web/component.yaml 'workersDevSubdomain: your-workers-subdomain' \ + 'workersDevSubdomain: your-workers-subdomain-2' 3 +check "a site name containing the baseline's name survives three passes" \ + "$contains" apps/web/src/site.ts 'export const SITE_NAME = "SvelteKit Auth Example"' \ + 'export const SITE_NAME = "SvelteKit Auth Example 2"' 3 + +# --verify runs in every phase. 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": "sveltekit-auth-2"' pass --values +verify "without them it cannot know, and fails" \ + "$contains" package.json '"name": "sveltekit-auth-2"' fail +verify "given the values, a real leftover still fails" \ + "$acme" package.json '"name": "sveltekit-auth"' fail --values +verify "a leftover worker name fails" \ + "$acme" apps/web/component.yaml 'workerName: sveltekit-auth-web' fail --values +verify "a leftover code identifier fails (no rule renames it — so nothing may spell it)" \ + "$acme" apps/web/src/lib/x.js 'export class SvelteKitAuth {}' fail --values +verify "the upstream's import and call are not residue" \ + "$acme" apps/web/src/auth.ts 'import { SvelteKitAuth } from "@auth/sveltekit"' pass --values +verify "…nor the example's repository" \ + "$acme" README.md 'https://github.com/nextauthjs/sveltekit-auth-example' pass --values +verify "a clean product passes" \ + "$acme" package.json '"name": "acme-notes"' 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 = "SVELTEKIT_AUTH_TOKEN"\n' > "$tmp/apps/web/x.js" +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..e524cd9 --- /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 site 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..39e32b7 --- /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 site's +// landing is a SvelteKit build per environment; a third, on the dev rung, +// 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 03-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 its landing +// node tooling/bootstrap/dev-lanes.mjs --restore # 03-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 +// 03-docs leaves the marker in intent.yaml, and `--restore` (or a re-run of +// 03-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..ed6edf8 --- /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 03-docs, the last landing, puts it back: +// +// node tooling/bootstrap/promotion.mjs --defer # 01-product, before its landing +// node tooling/bootstrap/promotion.mjs --restore # 03-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 03-docs +// leaves the marker in intent.yaml, and `--restore` (or a re-run of 03-docs) +// is the whole fix. docs/phases/03-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..ce9512a --- /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 +// +// 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: a `tests/<app>` package beside `apps/<app>` would carry one +// too, and only the first is named for the app. + +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", ".svelte-kit", ".wrangler", ".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..ac16e62 --- /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 site 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 its 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/migrations/manifest.mjs b/tooling/migrations/manifest.mjs new file mode 100644 index 0000000..ea8d7a5 --- /dev/null +++ b/tooling/migrations/manifest.mjs @@ -0,0 +1,42 @@ +#!/usr/bin/env node +// Keeps packages/db/src/manifest.ts honest: every entry's `checksum` is the +// sha256 of its migration file. +// +// node manifest.mjs check # exit 1 and list every mismatch +// node manifest.mjs fix # rewrite the checksums in manifest.ts +// +// Run from packages/db (the package scripts do). An applied migration's +// checksum is immutable — `fix` is for a migration that has not been applied +// anywhere yet. +import { createHash } from "node:crypto"; +import { readFileSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; + +const mode = process.argv[2]; +if (mode !== "check" && mode !== "fix") { + console.error("usage: manifest.mjs <check|fix>"); + process.exit(2); +} +const manifestPath = resolve("src/manifest.ts"); +const migrationsDir = resolve("src/migrations"); +let source = readFileSync(manifestPath, "utf8"); + +const entryRe = /path:\s*"([^"]+)",\s*checksum:\s*"([0-9a-f]{64})"/g; +const mismatches = []; +source = source.replace(entryRe, (whole, path, recorded) => { + const actual = createHash("sha256").update(readFileSync(resolve(migrationsDir, path))).digest("hex"); + if (actual !== recorded) mismatches.push({ path, recorded, actual }); + return mode === "fix" ? whole.replace(recorded, actual) : whole; +}); + +if (mismatches.length === 0) { + console.log("manifest: every checksum matches its file"); + process.exit(0); +} +if (mode === "fix") { + writeFileSync(manifestPath, source); + for (const m of mismatches) console.log(`manifest: ${m.path} ${m.recorded.slice(0, 8)} → ${m.actual.slice(0, 8)}`); + process.exit(0); +} +for (const m of mismatches) console.error(`manifest: ${m.path} recorded ${m.recorded} but the file hashes to ${m.actual}`); +process.exit(1); diff --git a/tooling/rebrand/rebrand.mjs b/tooling/rebrand/rebrand.mjs new file mode 100644 index 0000000..8f92c8b --- /dev/null +++ b/tooling/rebrand/rebrand.mjs @@ -0,0 +1,485 @@ +#!/usr/bin/env node +// Rebrand renamer for the sveltekit-auth baseline (zero-dependency). +// +// This repository is a baseline: a product is instantiated from it, branded, +// and deployed as somebody's own site. This script rewrites every *instance +// identity* literal in the product tree — repo slug, the site's display name, +// the repository's source links, 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 — 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 +// it is built on, whose names contain the slug (UPSTREAM below). +// +// 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-notes", // required — repo slug +// "productname": "Acme Notes", // required — the site's display name +// "productdomain": "acme.dev", // optional — default <reponame>.example.com (set later) +// "githuborg": "acme-inc", // owner of the product repo (source link) +// "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 +// 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 the repository's source links +const BASELINE_IDENTITY_FILE = + arg("baseline-identity") ?? + path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".baseline", "identity.json"); +const BASELINE_DEFAULTS = { + slug: "sveltekit-auth", + pascal: "SvelteKitAuth", + productName: "SvelteKit Auth Example", + domain: "sveltekit-auth.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 site 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$", + "\\.(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; + } + }); +} + +// ── 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. +// ── The upstream's identity (never rewritten) ────────────────── +// +// This baseline's slug is upstream's own name, twice over. Auth.js's +// SvelteKit integration exports `SvelteKitAuth` — the slug's own Pascal form — +// and the app is built on that one call; and the example's repository is +// `nextauthjs/sveltekit-auth-example`, which the README, the licence and the +// docs credit. Renaming either would make a product import a function that +// does not exist and credit a repository that does not exist. So the few +// places the tree names them — the import and the call in apps/web/src/auth.ts, +// the example's repository and its Vercel deployment — are masked before the +// rules run and allowed by the leftover sweep. `@auth/sveltekit` and +// `sveltekit.authjs.dev` spell no slug. testing/rebrand.test.sh holds each of +// these unchanged in a branded product. +const UPSTREAM = [ + /import \{ SvelteKitAuth \} from "@auth\/sveltekit"/g, // apps/web/src/auth.ts: the one import + /\bSvelteKitAuth\(async \(event\)/g, // apps/web/src/auth.ts: the one call + /github\.com\/nextauthjs\/sveltekit-auth-example\b/g, // the example's repository + /\bsveltekit-auth-example\.vercel\.app\b/g, // its deployment + /\bsveltekit-auth-example\b/g, // its name +]; + +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 [ + // The repository's source links (README, docs: github.com/<owner>/<slug>). + // 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, intent environment + // URLs, docs). + [baseline.subdomain, subdomain, "workers.dev subdomain"], + ]; +} + +function regexPairs(files) { + const list = [ + // The display-name seam (apps/web/src/site.ts). JSON.stringify writes + // a valid JS 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 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..d02c419 --- /dev/null +++ b/tooling/rebrand/values.example.json @@ -0,0 +1,8 @@ +{ + "reponame": "acme-notes", + "productname": "Acme Notes", + "productdomain": "acme.dev", + "githuborg": "acme-inc", + "subdomain": "acme", + "orunWorkspace": "ws_XXXXXXXX" +}