From 0199520f8dda41441a8cfe8e546f97a034f6dc38 Mon Sep 17 00:00:00 2001 From: Rahul Varghese Date: Wed, 28 Oct 2026 21:15:00 +0530 Subject: [PATCH] SL2: strapi-launchpad becomes an Orun baseline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The commerce baseline's machinery on this tree: blueprint.yaml (the console card: one Cloudflare provider, the subdomain read from the connection, no domain asked, nothing of Strapi's asked) and repo-blueprint.yaml (one landing, 01-product, then the record, 02-docs; task set-up in the background, landings checked in the box, a 5 s watch, one secrets reconcile minting workers-deploy, r2-data and the account id). .baseline/ (identity — slug strapi-launchpad, the LaunchPad seam — the site's README with Connecting Strapi, and the task contracts), the rename engine, the bootstrap helpers, the deployment-record renderer probing / and /api/health, the phase pages, the context pack, and the baseline's tests: manifest, phases, coverage, rebrand, retouch, bootstrap-defer, wire, generated component docs, the leak gate (the slug only as the identity, the site's name only at its seam, the sample and the licence shipped), the offline bootstrap with the product's own plan, and the end-to-end tier: the stage lane's steps in a staged tree, the product served as born (its smoke, every page from the sample under the product's name, never a 500), then rebuilt with a stand-in Strapi connected (testing/lib/fake-strapi.py over the same seed) and browsed — a second visit reads Strapi not at all, a change stays cached while fresh, draft mode reads drafts past the cache. The end-to-end tier found that next/font/google fails on GitHub's runners (Google Fonts answers a font URL without an extension, which next/font's loader cannot read), so Inter is now self-hosted through next/font/local — the variable font's latin subset from @fontsource-variable/inter (OFL-1.1, shipped beside it) — and the build needs no font network. Every tier passes locally on orun v2.89.0. Co-Authored-By: Claude Orun-Task: SL-3 --- .baseline/identity.json | 9 + .baseline/product/README.md | 210 ++++++ .baseline/tasks/01-product.TaskContract.yaml | 27 + .baseline/tasks/02-docs.TaskContract.yaml | 13 + .github/workflows/baseline.yml | 152 ++++ .github/workflows/tag.yml | 97 +++ BOOTSTRAP.md | 274 +++++++ README.md | 47 +- ai/context/current.md | 46 ++ ai/context/decisions.md | 24 + ai/context/deployment.md | 7 + ai/context/open-risks.md | 18 + ai/context/operations.md | 185 +++++ apps/web/app/[locale]/layout.tsx | 13 +- apps/web/app/fonts/Inter-OFL.txt | 93 +++ .../app/fonts/inter-latin-wght-normal.woff2 | Bin 0 -> 48256 bytes blueprint.yaml | 171 +++++ docs/phases/01-product.md | 82 +++ docs/phases/02-docs.md | 39 + docs/phases/README.md | 125 ++++ hooks/render-deployment-docs.sh | 175 +++++ repo-blueprint.yaml | 683 ++++++++++++++++++ specs/epics/README.md | 2 +- .../strapi-launchpad/IMPLEMENTATION-STATUS.md | 3 +- specs/epics/strapi-launchpad/README.md | 2 +- specs/epics/strapi-launchpad/epic.yaml | 2 +- testing/bootstrap-defer.test.sh | 67 ++ testing/coverage.test.sh | 264 +++++++ testing/e2e.test.sh | 287 ++++++++ testing/fixtures/acme.json | 25 + .../baseline-identity.strapi-launchpad.json | 9 + testing/leak.test.sh | 235 ++++++ testing/lib/bootstrap.sh | 60 ++ testing/lib/e2e-visit.py | 245 +++++++ testing/lib/fake-strapi.py | 138 ++++ testing/lib/run-hooks.py | 72 ++ testing/lib/stage-job.py | 82 +++ testing/manifest.test.sh | 446 ++++++++++++ testing/phases.test.sh | 411 +++++++++++ testing/placement.test.sh | 384 ++++++++++ testing/rebrand.test.sh | 219 ++++++ testing/retouch.test.sh | 199 +++++ testing/wire.test.sh | 188 +++++ tooling/bootstrap/dev-lanes.mjs | 114 +++ tooling/bootstrap/promotion.mjs | 123 ++++ tooling/bootstrap/retouch.mjs | 254 +++++++ tooling/bootstrap/work-tree.mjs | 73 ++ tooling/rebrand/rebrand.mjs | 472 ++++++++++++ tooling/rebrand/values.example.json | 8 + 49 files changed, 6863 insertions(+), 11 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/02-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/app/fonts/Inter-OFL.txt create mode 100644 apps/web/app/fonts/inter-latin-wght-normal.woff2 create mode 100644 blueprint.yaml create mode 100644 docs/phases/01-product.md create mode 100644 docs/phases/02-docs.md create mode 100644 docs/phases/README.md create mode 100755 hooks/render-deployment-docs.sh create mode 100644 repo-blueprint.yaml create mode 100755 testing/bootstrap-defer.test.sh create mode 100755 testing/coverage.test.sh create mode 100755 testing/e2e.test.sh create mode 100644 testing/fixtures/acme.json create mode 100644 testing/fixtures/baseline-identity.strapi-launchpad.json create mode 100755 testing/leak.test.sh create mode 100644 testing/lib/bootstrap.sh create mode 100644 testing/lib/e2e-visit.py create mode 100644 testing/lib/fake-strapi.py 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 testing/wire.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/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..0e42f3a --- /dev/null +++ b/.baseline/identity.json @@ -0,0 +1,9 @@ +{ + "_comment": "THIS TREE'S OWN IDENTITY — the FROM side of every rebrand. tooling/rebrand/rebrand.mjs reads it to know what to rename AWAY from; a product's identity is the --values file, which is the TO side. Change a value here only together with the tree: these strings must be what the tree actually contains, or the rename silently misses and the product ships carrying this baseline's name. `productName` is the SITE_NAME seam in apps/web/lib/site.ts; `slug` also names the R2 bucket names (terraform `repo`), the Worker and its self-reference binding, and the secret project — and it may appear NOWHERE ELSE in a shipped file (the rename would rewrite it), nor may the `pascal` form (the leftover sweep fails on it). The template's own words — `Strapi`, the CMS it reads, and `LaunchPad` in the sample content — are not this identity: the rename never touches them (the site's name in code is the seam). `domain` and `subdomain` are placeholders, because this baseline has never deployed under a name of its own; `githubOwner` is the owner in the repository links the docs and the site carry.", + "slug": "strapi-launchpad", + "pascal": "StrapiLaunchpad", + "productName": "LaunchPad", + "domain": "strapi-launchpad.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..4f01f81 --- /dev/null +++ b/.baseline/product/README.md @@ -0,0 +1,210 @@ +# strapi-launchpad + +A Strapi-powered marketing site — a home page built from Strapi's dynamic +zones, pricing, FAQ and contact pages, a blog and a product catalogue, in +English and French, with draft mode for Strapi's preview — on **Cloudflare +Workers + Static Assets** through +[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), built from the +Next.js front end of [LaunchPad](https://github.com/strapi/LaunchPad) (MIT — +`apps/web/LICENSE.md`). Every read from Strapi is cached with `"use cache"` in +an **R2 bucket** that Terraform provisions per environment; the tag cache and +the revalidation queue are **Durable Objects** the Worker itself exports. + +It is live from its first deploy, before any Strapi project exists: it renders +the template's own seed — the pages, posts, products and images LaunchPad's +Strapi ships with — as **sample content**, under a bar that says how to +connect Strapi. Once you give the build your project's URL, it renders yours. + +## Live deployment + + +Not recorded yet. The bootstrap's last phase writes the live URLs, the +workspace, whether a Strapi project is connected 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 pages: `/[locale]` home, `/[locale]/[slug]` (pricing, FAQ, contact…), `/[locale]/blog`, `/[locale]/products`, sign-up; `/api/preview`, `/api/exit-preview` (draft mode), `/api/health` | `apps/web/app` | +| The site's name and its source link | `apps/web/lib/site.ts` (`SITE_NAME`, `SOURCE_URL`) | +| Strapi's reads, cached with `"use cache"` and tagged; whether a project is connected | `apps/web/lib/strapi/client.ts` | +| The sample content (the template's seed, as Strapi returns it) and its images | `apps/web/sample/strapi`, `apps/web/public/uploads`, `apps/web/lib/strapi/sample.ts` | +| The locale redirect | `apps/web/proxy.ts`, `apps/web/i18n.config.ts` | +| The dynamic-zone blocks, the navbar and footer | `apps/web/components` | +| Workers build, cache bindings and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.template.jsonc` + `wiring.fixture.json` (→ `wrangler.jsonc`), `component.yaml` | +| The R2 bucket (stage, prod) | `infra/terraform/cloudflare-r2` | +| Tests | `tests/web` (vitest) | + +## Getting started + +```bash +pnpm install +pnpm run wire:fixture # render apps/web/wrangler.jsonc from the offline fixture +pnpm typecheck +pnpm lint +pnpm test +pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next +``` + +With no Strapi URL the build is the site on its sample content. To work +against your project, copy `apps/web/.env.example` to `apps/web/.env.local` +and set `STRAPI_URL`, then: + +```bash +pnpm --filter @app/web dev # http://localhost:3000, Next's dev server +pnpm --filter @app/web preview # wrangler dev over the built Worker, a local R2 bucket and local Durable Objects +``` + +## Connecting Strapi + +1. **A Strapi project with LaunchPad's content types.** The site reads the + content model of LaunchPad's Strapi app — the `global`, `blog-page` and + `product-page` single types, the `pages`, `articles` and `products` + collections, the dynamic-zone components and their populate middlewares — + which is the `strapi/` app in [strapi/LaunchPad](https://github.com/strapi/LaunchPad). + Deploy that app to [Strapi Cloud](https://cloud.strapi.io) (create a + project from your own copy of the repository, with `strapi` as the base + directory), or run it yourself. To start from the content this site shows + now, import the template's seed into it + (`yarn strapi import -f ./data/export_20250116105447.tar.gz` in `strapi/`). + The site reads published content as the Public role, which the seed's + permissions already allow. +2. **Give the build your project**, once per deployed environment. The build + inlines the URL — server and browser code both read it — so it is this + repository's Orun secret, and stage and prod can each name their own + project: + + ```bash + orun secrets set STRAPI_URL --env stage # prompts: https://.strapiapp.com + orun secrets set STRAPI_URL --env prod + ``` + + Then **redeploy the site**: a secret is read when the site builds, and + setting one builds nothing. Use **Deploy by hand** below, or change the + stamp on the last line of `apps/web/component.yaml` (`# orun: redeploy …`) + and merge. From that deploy on, the pages are your project's and the + sample bar is gone. The redirects (Strapi's `redirections` collection) are + read when the site builds, so a new redirect shows on the next deploy. +3. **Preview drafts** (optional). Strapi's preview opens + `/api/preview?secret=&url=&status=draft`, which turns + on Next's draft mode: every read then asks Strapi for drafts, past the + cache. Set the secret as a Worker secret in each environment — Cloudflare's, + so deploys leave it alone — and the same value as `PREVIEW_SECRET` and + `CLIENT_URL` (this site's URL) in your Strapi project: + + ```bash + pnpm --filter @app/web exec wrangler secret put PREVIEW_SECRET --name strapi-launchpad-web-prod + ``` + + (and the same for `strapi-launchpad-web-stage`). Until it is set, preview + is refused. + +Published content is cached at the edge with Next's `minutes` profile +(`cacheLife('minutes')`: an entry older than a minute is served once more +while it is re-read in the background, and none outlives an hour), so a +published change shows within a minute or two; a redeploy shows it at once. + +## How the cache is wired + +The Worker binds the bucket as `NEXT_INC_CACHE_R2_BUCKET` (every `"use cache"` +entry), and two Durable Objects: `NEXT_TAG_CACHE_DO_SHARDED` (which tags were +revalidated, and when) and `NEXT_CACHE_DO_QUEUE` (background revalidation of +stale entries, through the Worker's own `WORKER_SELF_REFERENCE` binding). The +bucket's name is never hand-written: `apps/web/wrangler.template.jsonc` names +it as a wiring token, and `wrangler.jsonc` is that template rendered — from +`wiring.fixture.json` for local work and verification, and on every deploy +from the document the `cloudflare-r2` Terraform root publishes after its +apply (`WIRING_CLOUDFLARE_R2`, per environment). Edit the template, then +`pnpm run wire:fixture` and commit the render with the template. The Durable +Objects need no root: the migration in the config creates them on the first +deploy. + +## How it deploys + +Merges to `main` converge through [Orun](https://github.com/sourceplane/orun): +`.github/workflows/ci.yml` plans the changed components and runs each lane +against the workspace in `intent.yaml`. The R2 bucket applies first, then the +site builds for that environment — its bucket, its origin, and its Strapi +project if one is set — and deploys, to `stage`, then to `prod` once stage +has converged on the same commit; `dev` only verifies. The Worker is +`strapi-launchpad-web-` on your account's workers.dev subdomain, and +every deploy is smoke-tested over HTTP: the home page must render its +navigation, and `/api/health`, which only the Worker can answer, must say ok. +A pull request runs the same pipeline's verify lanes, with nothing applied or +deployed: the R2 bucket planned for stage and prod, and the site built and +dry-deployed for each environment. They do not run the tests or the linter — +run those before you push (Getting started, above). (A push to `main` +applies, builds and deploys.) + +The pipeline holds one credential, GitHub's own `GITHUB_TOKEN`. The Cloudflare +tokens and account id are brokered per run from the workspace's Cloudflare +connection — one to deploy the Worker, one with R2 access for the bucket's +apply — and the bucket names and your project's URL travel as Orun secrets; +nothing provider-shaped is stored in the repository or in GitHub. The preview +secret is a Worker secret, set once on the Workers themselves. + +**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 setting your +project's URL, say. A component with nothing to run in that environment (a +test suite in `prod`) is left out with a notice. + +## How it maps to Vercel + +| Vercel | Here | +|---|---| +| Next.js hosting (SSR, route handlers, the proxy, draft mode) | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets (`ASSETS`) | +| Cache Components with `"use cache"`, `cacheLife` and `cacheTag` | `"use cache"`, its profile and its tags kept (`experimental.useCache`); pages render per request (below) | +| Data Cache entries | The R2 bucket bound as `NEXT_INC_CACHE_R2_BUCKET` | +| `revalidateTag` | A sharded Durable Object tag cache consulted on every cache read | +| Stale-while-revalidate | A Durable Object queue that re-renders stale entries through the Worker | +| Image Optimization (`/_next/image`, `sharp`) | Off (`images.unoptimized`): Strapi's media are served as uploaded | +| `NEXT_PUBLIC_API_URL` | The Orun secret `STRAPI_URL` (above); the sample content until set | +| `PREVIEW_SECRET` | A Worker secret | +| Deploy on push | Orun applies the bucket and deploys `strapi-launchpad-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`) | + +Cache Components are off: `@opennextjs/cloudflare` 1.20 cannot run Next.js +16's Cache Components on workerd yet (a Cache Components page answers 500 and +then hangs), so the site keeps every `"use cache"` read, its profile and its +tags through `experimental.useCache`, and renders each page at request time +from those cached reads — every page reads draft mode, so none was +prerendered upstream either. + +## Custom domain + +The site answers on workers.dev from its first deploy. To serve it on your +own domain: + +1. Add the domain to the Cloudflare account the site deploys into, and attach + it to the Worker (dashboard → Workers & Pages → + `strapi-launchpad-web-prod` → Settings → Domains & Routes → Add → + Custom domain). +2. Set the environment's public origin in `intent.yaml`, so the next deploy + resolves the site's Open Graph images against it (until then they use the + workers.dev URL): + + ```yaml + environments: + prod: + env: + SITE_URL: https://www.example.com + ``` + + The site was born with the reserved placeholder + `strapi-launchpad.example.com` where its domain goes: `BASE_DOMAIN` under + each environment in `intent.yaml`. Replace it with your domain in the same + change, and land it with a change under `apps/web` so the merge rebuilds + the site. Point your Strapi project's `CLIENT_URL` at the new domain too. + +## Credits + +The site is the Next.js front end of [strapi/LaunchPad](https://github.com/strapi/LaunchPad), +designed and developed by [Aceternity](https://aceternity.com) and +[Strapi](https://strapi.io); its sample content and images are LaunchPad's +seed. MIT — `apps/web/LICENSE.md`. diff --git a/.baseline/tasks/01-product.TaskContract.yaml b/.baseline/tasks/01-product.TaskContract.yaml new file mode 100644 index 0000000..1aa5eb6 --- /dev/null +++ b/.baseline/tasks/01-product.TaskContract.yaml @@ -0,0 +1,27 @@ +# Task contract template for the 01-product landing. +# Unbound to a key on purpose: `orun.task/ensure@v1` seals and attaches it to +# the key the allocator issues. It lives under `.baseline/`, not `tasks/`, +# because `tasks/` is this repository's own work tree (`intent.yaml` `work:`), +# where an unkeyed contract is an error. gates: [] is a DECLARATION — merge +# alone finishes this task; the main convergence is the gate the bootstrap +# watches, not one the plane observes as a PR check. +# +# The whole product in one landing. `affects` names COMPONENTS, by +# metadata.name: the phase's retouch hook reads this list to decide which +# component.yaml files get the redeploy marker, so a re-run of the phase has a +# diff and exactly these components are re-planned — the deploy set and the +# task plane's statement of the work are one list. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The product's repository is born and linked, the whole product lands in one pull request, and one convergence applies the R2 cache bucket and deploys the site on stage and prod + affects: + - cloudflare-r2 + - web + - web-tests + doneWhen: + - repo pushed, main pinned as default, workspace linked + - WIRING_CLOUDFLARE_R2 published on stage and prod + - main convergence green (R2 applied, then the site built, deployed and smoke-tested on stage and prod) + - the site answers on both workers.dev URLs + gates: [] diff --git a/.baseline/tasks/02-docs.TaskContract.yaml b/.baseline/tasks/02-docs.TaskContract.yaml new file mode 100644 index 0000000..d62a6e7 --- /dev/null +++ b/.baseline/tasks/02-docs.TaskContract.yaml @@ -0,0 +1,13 @@ +# Task contract template for the 02-docs landing. See 01-product's header. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The live deployment is recorded from verified facts as agent-readable state in the product's repo + 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..08354df --- /dev/null +++ b/.github/workflows/baseline.yml @@ -0,0 +1,152 @@ +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 the one product phase, +# that the R2 bucket's wiring reaches the Worker's config, that a placed +# tree comes up branded and carrying nothing of the factory — and plans the +# bucket before the Worker on a merge — and that the product it produces +# installs, builds, deploys (dry), serves, and takes a cart. +# +# ─── 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, wire) + 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 wire; 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 product would carry, derived by the + # floor too), and the placement tier (the offline bootstrap: both phases + # placed and finished by the blueprint's own hooks, then the product's own + # `orun plan` for the 01-product merge — the R2 apply before the Worker's + # deploy — by an orun at or above the product's lane pin, below). + 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-shop \ + --set "productname=Acme Shop" \ + --set githuborg=acme-inc + - name: the leak gate — what a product carries + run: bash testing/leak.test.sh + # The placement tier ENDS with the product's own `orun plan` — what the + # product's ci.yml runs — so it needs an orun at the product's lane pin + # or newer: one older than v2.78.4 plans a pull request with apps/web + # waiting on the R2 plan, because it does not apply a dependsOn edge's + # `modeRules` (advisory on a PR, enforced on main). The test refuses an + # orun older than the pin rather than assert the wrong CLI's plan. The + # offline bootstrap before it reads the blueprint, which takes the + # bootstrap floor (v2.88.0: the one `secrets` reconcile, the task set-up + # in the background, the landings checked in the box), so this tier + # runs the floor, which is newer than the lane pin. + - uses: sourceplane/orun-action@v1.2.0 + with: + version: v2.88.0 + - name: placement — the offline bootstrap, and the product's own plan + run: | + git config --global user.email ci@example.invalid + git config --global user.name "baseline ci" + bash testing/placement.test.sh + + # Tier 2. THE PRODUCT IT PRODUCES WORKS: its one landing installed, its + # fixture rendered, type-checked, linted, tested and built, the stage lane's + # own structure check, build (the live wiring render included), output check + # and dry deploy in the tree orun stages, 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, and + # the floor is newer than the product'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 product 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..21ed870 --- /dev/null +++ b/BOOTSTRAP.md @@ -0,0 +1,274 @@ +# BOOTSTRAP — a new product from this baseline, in one landing + +How to go from **nothing** to a **site live on stage and prod, its R2 +cache buckets applied, documented**, with ONE provider consent — and how its +owner then connects a Strapi project. + +There is one artifact: **`repo-blueprint.yaml`**. It declares what to place, +in what order, what each phase needs first, and what to say while it runs. +`orun new` is the whole runtime — the phases below are its `--phase` names, +not separate workflows. The console card the platform renders is +**`blueprint.yaml`**; it names the build document and states the inputs, the +brokered secrets and the programme, and `testing/manifest.test.sh` holds it +to what the build document does. + +Target wall-clock: **about fourteen minutes** — an estimate summed from the +phases (13 + 1) until a bootstrap measures it; no build of this baseline has +been timed. The shape: the task set-up in the background while ONE landing +is placed, branded and checked in the box (`orun validate` and `orun plan`, +no runner waited for), then one convergence — the R2 bucket applied on stage +and prod, then the site built with its name and deployed, stage and +prod side by side — then a short docs landing that restores the promotion +gate. + +## 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 product's own `ci.yml` pins its lanes + separately (v2.78.4). +- A Cloudflare account with **R2 enabled** (R2 must be activated once in the + dashboard, even on the free plan; Durable Objects with SQLite storage are + on the free plan too) and its **Account API token** with Workers Scripts + Write, Workers KV Storage Write and **Workers R2 Storage Write** (the + console's Connect recipe lists the exact permission groups). It is the ONLY + provider credential this baseline needs, minted into two scopes: the + brokered `workers-deploy` token deploys the Worker, and the `r2-data` token + (`CLOUDFLARE_R2_TOKEN`) applies the bucket — `workers-deploy` carries no + R2. +- **No Strapi project.** The site goes live on the template's own seed as + sample content; Strapi is a third party the platform does not broker, so + the owner connects a project after the build (§4). +- An Orun Cloud workspace for the product — `orunWorkspace`, or the + workspace the build runs in (ORUN_WORKSPACE) when that is unset — with an + **admin-role API key** for headless runs (secret writes below admin are + masked as `not_found`). +- **The repository allow-listed in the workspace** (console → Settings → Git + repos), unless the credential can write links. `01-product`'s `link` step + stops and names the fix if it is not. + +## 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 https://github.com/sourceplane/strapi-launchpad +cd strapi-launchpad + +orun new --blueprint repo-blueprint.yaml \ + --out ~/sites/acme-launch --run-hooks --resume \ + --set reponame=acme-launch --set productname="Acme Launch" \ + --set githuborg=acme-inc \ + --set orunWorkspace=ws_XXXXXXXX \ + --set subdomain= +``` + +`subdomain` is the workers.dev subdomain of the Cloudflare account you deploy +into (Workers & Pages → your subdomain). A build started from the console, or +with `orun baseline new --from bst_…`, never asks for it: the platform reads +it from the workspace's Cloudflare connection, the same one the deploy tokens +mint from. Only a hand-run build like this one passes it. + +**`--run-hooks` is the difference between placing files and bootstrapping a +product.** Without it `orun new` writes the tree and stops: no repository, no +landing, no convergence watch, no probe. That is deliberate — it is what +makes the offline bootstrap in `testing/` possible with no workspace and no +provider. + +`--resume` is safe to re-run from anywhere, a fresh container with a fresh +`--out` included: **phase state is derived from the tree, never stored.** A +phase whose files are present but branded derives as `drifted`, and +`--resume` leaves it placed rather than reverting the product's identity. + +## 1b. Or phase by phase + +| phase | what it lands | verified by | +|---|---|---| +| `01-product` | the repository, created and linked; the WHOLE product in one PR — intent, CI, tooling, identity, the R2 root, the site and its tests; the brokered Cloudflare secrets (deploy, R2, account id) | its commit validated and planned in the box (as the PR and as the merge), then merged; the convergence green (R2 applied, then the storefront — which resolves `WIRING_CLOUDFLARE_R2` — built, deployed, smoke-tested); both workers.dev URLs answering | +| `02-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-launch --run-hooks \ + --phase 01-product --values ~/acme-launch.values.yaml +# … then 02-docs +``` + +`02-docs` reads the identity back from `.rebrand/values.json` in the placed +tree, but the blueprint's **required** inputs — `reponame`, `productname`, +`githuborg` — are validated before anything runs, so pass them every time (a +`--values` file is easier). The domain is not one of them: the site goes live +on workers.dev, and `productdomain` defaults to empty, which brands the +reserved placeholder `.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 ` | places exactly that phase; its `requires.phases` still gates | +| `--until ` | places every phase through that one and stops | + +What lands in the product is PRODUCT-ONLY: the app, its R2 root, its tests, +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, and no file that ships names one of them. That +promise is a test: `testing/leak.test.sh` derives what every phase would +place and gates the set and its sources, and `testing/placement.test.sh` +gates the same rules over a placed, branded tree. + +## 2. Why one landing is safe: the plan carries the order + +The bucket must exist before the Worker that binds it: the Worker's +`wrangler.jsonc` carries the bucket's name, rendered in its build from the +wiring document the R2 root publishes after its apply, and a deploy whose +R2 binding names a bucket that does not exist is refused. That order used to +need landings of its own. It does not, because the product's plan holds it: + +- `apps/web/component.yaml` declares `dependsOn: cloudflare-r2` with + `mode: enforced`, and `modeRules` making it advisory on + `github-pull-request`. On the merge the Worker's deploy waits for its + environment's apply; on a pull request nothing deploys, so nothing waits. +- A job resolves its secrets when it STARTS, so `WIRING_CLOUDFLARE_R2_` + is there when the deploy begins. +- The deploy resolves the document from the place every later run looks + (its `component.yaml` secret refs), so a green convergence already says it + is there: a missing one fails its lane. There is no separate check. + +`testing/phases.test.sh` fails if a component that reads a wiring document +does not wait for its publisher this way; `testing/placement.test.sh` plans +the product's own merge and asserts the R2 lanes run first. + +### Two Cloudflare tokens, on purpose + +`workers-deploy` grants Workers Scripts and KV write — and no R2. The R2 +root's Terraform has to list the account's buckets (`adopt.tf`) and create +one, so it authenticates with its own key, `CLOUDFLARE_R2_TOKEN`, minted from +the `r2-data` template — its own entry in the one +`orun.integrations/reconcile@v1` hook (`secrets`), beside the deploy token's +`workers-deploy` — and bound in +`infra/terraform/cloudflare-r2/component.yaml` as the provider's +`CLOUDFLARE_API_TOKEN` (the way a D1 root binds a `d1-edit` token). The card +(`blueprint.yaml` `spec.secrets`) mirrors the hook, and +`testing/manifest.test.sh` holds the two together. + +## 3. 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 https://github.com/sourceplane/strapi-launchpad +cd strapi-launchpad +orun new --blueprint repo-blueprint.yaml \ + --out /work/acme-launch --run-hooks --resume --progress json \ + --values /work/acme-launch.values.yaml +``` + +| requirement | detail | +|---|---| +| `GITHUB_TOKEN` | fine-grained PAT: **read** on this repository; on the PRODUCT's repository **contents write**, **pull-requests write**, **actions read+write** (`orun.run/watch@v1` resumes runs with `gh run rerun`), **checks read**; **repository create** on the owner if `01-product` creates it (or pre-create it — supported) | +| classic token caveat | a classic PAT or gh OAuth token also needs the `workflow` scope to push `.github/workflows/` | +| pinning | the clone's `--branch ` pins everything: the blueprint, its modules and its hooks' scripts all come from that one commit | + +## 4. After the product is live + +- **Connect a Strapi project** (the owner's step; the platform does not + broker it): a Strapi Cloud project running LaunchPad's `strapi/` app, then + the Orun secret `STRAPI_URL` per environment and a redeploy of the site — + the build inlines it. For Strapi's preview, the Worker secret + `PREVIEW_SECRET` (`wrangler secret put … --name -web-`) and + the same value in the project. The product's README, "Connecting Strapi", + has every step. +- **Change the site**: anything under `apps/web`; its name is + `apps/web/lib/site.ts`. Every merge to `main` redeploys. +- **Add a binding** (D1, KV, another bucket): a Terraform root that + lease-publishes `WIRING_`, a token in `wrangler.template.jsonc`, its + fixture entry, and in `apps/web/component.yaml` the root in the build's + `--components`, the `WIRING__` secretEnv and an enforced + `dependsOn` on it. `ai/context/operations.md` in the product says the same. +- **Custom domain**: attach it to the Worker in Cloudflare (the product's + README, "Custom domain"). There is no domain phase: attaching a domain + needs zone permissions the brokered `workers-deploy` token does not carry. + Then set the environment's `SITE_URL` in `intent.yaml`, so the next deploy + resolves its Open Graph images against the domain. +- **Refresh the record**: re-run `--phase 02-docs`; it is idempotent. + +## 5. 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 wire; do bash testing/$t.test.sh; done +bash testing/leak.test.sh # needs orun +bash testing/placement.test.sh # needs orun >= ci.yml's pin, node, pnpm: the offline bootstrap and the product's own plan +bash testing/e2e.test.sh # + network for pnpm: the product built in the job tree, dry-deployed and served +``` + +The offline bootstrap (`testing/lib/bootstrap.sh`) places both phases in +order and finishes each with the blueprint's OWN `run:` hooks — read out of +`repo-blueprint.yaml`, not transcribed — so the retouch marker, the rebrand, +the re-tenant, the deferrals and their restore, and the deployment record +all run exactly as a real bootstrap runs them. Only the platform's typed +actions (task, repo, link, reconcile, land, watch, secrets, +probe) are stood in for, a landing becoming a commit. What no offline test +can do is the platform's half: the bucket applied for real (the R2 root is +held to `terraform validate`), the tokens minted, the deploy, the probes — +and a real Strapi project: the e2e connects a stand-in that answers the site's +reads from the template's seed, not a real Strapi. + +## 6. Cutting a baseline tag (maintainers) + +Every product built from this repository resolves a `baseline-vN` tag, so +the tag is cut by a workflow rather than by hand: + +```bash +gh workflow run tag.yml -f version=baseline-v1 # from main +gh workflow run tag.yml -f version=baseline-v1 -f ref= +``` + +It refuses a version that is not `baseline-v` 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 ` | the workspace's GitHub connection is to another account. Connect the App installation on `` (console → Integrations → GitHub), then `--resume` | +| `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 | +| `01-product` stops at `link` | the repository is not linked to the workspace and the credential cannot link it. Allow-list it (console → Settings → Git repos) and re-run the phase | +| Secret WRITE fails `not_found` while listings work | the API key's role is below admin; re-mint it with the admin role | +| `secrets` fails `parent_grant_insufficient` on `CLOUDFLARE_R2_TOKEN` | the connection's token lacks Workers R2 Storage Write; add it, re-connect, re-run `01-product` | +| R2 lane: Authentication error (10000) | the R2 root is not authenticating with `CLOUDFLARE_R2_TOKEN` (its component.yaml), or the account has not activated R2 | +| deploy lane: Authentication error (10000) | the connection's token lacks Workers Scripts write; re-issue it, re-connect, re-run `01-product` | +| R2 lane: bucket already exists (10004) | `adopt.tf` imports a bucket of the same name; restore it if removed. Two products with one `reponame` in one account share bucket names — pick another `reponame` | +| web lane fails resolving `WIRING_CLOUDFLARE_R2_` | that environment's R2 apply failed — read its lane; the web lane waits on it | +| web lane: `WIRING_CLOUDFLARE_R2` not found | that environment's R2 apply published nothing: the R2 component lost its `secretOutputs`, or its lane was not in the plan. Re-run the phase; its retouch marker re-plans the R2 root | +| `land` stops: `the landing's own check failed — orun plan for …` | the product's tree does not plan — the line after it is orun's own error (an unknown component type, a composition that does not resolve). Nothing was pushed. Fix the tree (or the baseline) and re-run the phase | +| `land` waits on CI after all | the product's repository requires a status check on `main` (branch protection or a ruleset), so GitHub refused the early merge; the landing waits for the check as a `checks: ci` landing would, then merges | +| 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 R2 root and the storefront re-plan | +| The live site shows the sample content and the connect bar | no Strapi project is connected — expected after a bootstrap. The product's README, "Connecting Strapi" | +| A project is connected, but the pages are still the sample's | `STRAPI_URL` is read when the site BUILDS; redeploy it (the product's README, "Deploy by hand") | +| Connected, and a page is empty or a 404 | the project is not running LaunchPad's content types, or the Public role cannot read them — the product's README, "Connecting Strapi" | +| The product's `intent.yaml` says `workspace: ws_SET_ME` | `orunWorkspace` was empty and the build ran outside a workspace; set it and re-run `01-product` | +| A bootstrap stopped before `02-docs`; prod no longer waits on stage | the gate is deferred, not dropped: run `02-docs`, or `node tooling/bootstrap/promotion.mjs --restore --file /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 | +| web lane `verify-app-structure` fails on `wrangler.jsonc` | the config is not committed. It is the fixture render of `wrangler.template.jsonc`: `pnpm run wire:fixture` and commit it | +| web lane `build-app`: `Symlink apps/web/node_modules/next is invalid, it points out of the filesystem root` | the product's intent pins stack-tectonic ≥ 0.20.0, whose lane-scoped install links each job's node_modules out of its tree, which Next 16's Turbopack refuses. Pin 0.19.0 (`intent.yaml` says why) | +| the convergence reported green, then `verify` got 404 | a second workflow ran on the push to main and the watch took its run. Only `ci.yml` may run on a push to main | diff --git a/README.md b/README.md index 6461ec1..50ac7a5 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,9 @@ Strapi's preview — running on **Cloudflare Workers + Static Assets** through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with the Next.js data cache in an **R2 bucket** provisioned by Terraform through [Orun](https://github.com/sourceplane/orun) and the tag cache and revalidation -queue in **Durable Objects** the Worker itself exports, deployed by -[Orun](https://github.com/sourceplane/orun) to stage and prod on every merge. -Packaging it as an Orun baseline is the next milestone (SL2). +queue in **Durable Objects** the Worker itself exports, 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. The Strapi server is not part of it: running Strapi needs a long-lived Node server (a container), which this baseline does not carry. A fresh build needs @@ -22,6 +22,45 @@ owner connects a project by setting its URL as an Orun secret and redeploying. See [`specs/epics/strapi-launchpad`](specs/epics/strapi-launchpad/README.md) for the design, the milestones and the as-built status. +## Instantiating a product + +```bash +git clone --depth 1 --branch https://github.com/sourceplane/strapi-launchpad +cd strapi-launchpad +orun new --blueprint repo-blueprint.yaml --out ~/sites/acme-launch --run-hooks --resume \ + --set reponame=acme-launch --set productname="Acme Launch" \ + --set githuborg=acme-inc --set subdomain= +``` + +Or, once the platform's registry lists it, from the Orun console (Baselines → +`strapi-launchpad` → Build). Two phases: **`01-product`** creates the +repository and lands the whole product as ONE pull request — intent, CI, +tooling, the R2 root, the site and its tests — and one convergence applies the +R2 bucket on stage and prod and then deploys the site bound to it; +**`02-docs`** records the live deployment from probed facts. +**[BOOTSTRAP.md](BOOTSTRAP.md)** is the operator guide; +[docs/phases/](docs/phases/README.md) has a page per phase. + +The new repository receives the **product only** — the app, its R2 root, its +tests, its CI, its tooling, a README of its own and its operating contract — +renamed throughout to the product's name, repository, Cloudflare Worker and +bucket names. None of this repository's machinery ships. Its owner then +connects a Strapi project with one Orun secret and a redeploy (the product's +README, "Connecting Strapi"); the card asks for nothing of Strapi's, because +the platform does not broker it. + +| 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 product's README and context pack | `.baseline/product/README.md`, `ai/context/` | +| The baseline's tests: contract, wiring, leak, offline bootstrap, end to end | `testing/`, `.github/workflows/baseline.yml` | +| Cutting a `baseline-vN` tag | `.github/workflows/tag.yml` | + ## What is here (the product) | Surface | Where | @@ -102,3 +141,5 @@ if the two disagree. | Workflow | What it runs | Ships to a product | |---|---|---| | `ci.yml` | the Orun pipeline, and the only workflow a product carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the R2 root planned for stage and prod, the site built and dry-deployed per environment; they neither lint nor run the tests, which `baseline.yml`'s e2e tier runs before every tag), except the bootstrap's own landings (`orun/BASE-*`), where `plan` alone runs and nothing waits for it (the landing checked its commit in the box); a merge applies the R2 bucket, then 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 wiring path, the blueprint read by the pinned orun, the leak gate, the offline bootstrap with the product's own plan, the product built in the job tree, dry-deployed and served as born (on its sample content), then built again with a stand-in Strapi connected and browsed — its cache reused, draft mode past it | 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..c00c13e --- /dev/null +++ b/ai/context/current.md @@ -0,0 +1,46 @@ +# strapi-launchpad — 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 + +The Next.js front end of LaunchPad (strapi/LaunchPad — Vercel's LaunchPad: +Next.js × Strapi Starter) on Cloudflare Workers + Static Assets through +`@opennextjs/cloudflare`, its Next.js cache in an R2 bucket and two Durable +Objects the Worker exports, 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`) — the R2 bucket applied before the Worker that binds it — then +records what went live (`02-docs`). The Strapi server is not carried (it +needs a container); with no Strapi project connected the site renders the +template's own seed as sample content, and the owner connects a project by +setting its URL as an Orun secret and redeploying. It fits Workers Free (about +2.1 MiB gzipped). + +## Release + +| | | +|---|---| +| Latest tag | `baseline-v1` (SL2) | +| Proven live | No. Everything short of the platform is proven offline in Baseline CI — the site built and served as born on its sample content, then connected to a stand-in Strapi, its cache reused and draft mode past it. The tokens minted, a real R2 apply, a real `wrangler deploy`, the probes and a real Strapi Cloud project are still to come (risk SL-A) | + +## Where to read + +| Question | Page | +|---|---| +| What shipped, and every departure from upstream | `specs/epics/strapi-launchpad/IMPLEMENTATION-STATUS.md` | +| Why it is built this way | [decisions.md](decisions.md), then `specs/epics/strapi-launchpad/design.md` | +| What could still go wrong | [open-risks.md](open-risks.md), then `specs/epics/strapi-launchpad/risks-and-open-questions.md` | +| How to instantiate it | `BOOTSTRAP.md`, `docs/phases/` | +| What each component is | `apps/web/docs/`, `infra/terraform/cloudflare-r2/docs/`, `tests/web/docs/` (generated; `python3 tooling/catalog/gen-component-docs.py`) | + +## Next + +1. Bootstrap one site from `baseline-v1` and record its timings; connect a + Strapi Cloud project running LaunchPad's `strapi/` app to it once and use + its preview. That closes SL-A and SL-B. +2. When an npm release of @opennextjs/cloudflare runs Cache Components on + workerd (opennextjs-cloudflare#1450), turn them back on (SL-C). diff --git a/ai/context/decisions.md b/ai/context/decisions.md new file mode 100644 index 0000000..d97f34d --- /dev/null +++ b/ai/context/decisions.md @@ -0,0 +1,24 @@ +# strapi-launchpad — 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 | Only LaunchPad's `next/` front end; the Strapi server is not carried | Strapi is a long-lived Node server with a database: it needs a container, which no Orun composition provides; the brief ships the Next app against Strapi Cloud | `specs/epics/strapi-launchpad/design.md` §1 | +| 2 | OpenNext on Workers + Static Assets, the commerce baseline's shape | The site is a Next.js App Router app: route handlers, the proxy and draft mode run in the Worker | design.md §2 | +| 3 | The incremental cache in R2, the tag cache (sharded) and the revalidation queue in Durable Objects | The template caches every Strapi read with `"use cache"`; the static-assets cache cannot hold them (OpenNext refuses composable entries in it), and R2 + Durable Objects is the commerce baseline's proven shape | design.md §3 | +| 4 | `experimental.useCache`, not `cacheComponents` | A Cache Components page answers 500 then hangs under the adapter (opennextjs-cloudflare#1450). Every `"use cache"` read, profile and tag is kept; every page reads draft mode, so none prerendered upstream either | design.md §4, risk SL-C | +| 5 | Next.js 16.3.8, not upstream's ^16.3.1 lock | @opennextjs/cloudflare 1.20.11's floor | IMPLEMENTATION-STATUS | +| 6 | The sample content is the template's own seed, recorded from a Strapi that imported it (populate middlewares applied), both locales, `formats` dropped; the 40 images it names ship under `public/uploads` | An honest "before you connect" state: the site as LaunchPad's Strapi serves it, not invented content | design.md §5 | +| 7 | One connection seam (`isStrapiConnected`, the build-time URL): unconnected, every read is the sample's and nothing is fetched; a bar says how to connect | A baseline goes live with no key the platform cannot broker | design.md §5 | +| 8 | `STRAPI_URL` is an OPTIONAL build secret (`optionalSecretEnv`), inlined as the template's `NEXT_PUBLIC_API_URL`; `PREVIEW_SECRET` is a Worker secret | Browser code reads the URL; the preview secret is read at request time | design.md §5 | +| 9 | One site-name seam (`SITE_NAME`, `lib/site.ts`); the logo, sign-up and default metadata read it; the leak gate fails another | The rename rewrites one line and has no sweep for the name | risk SL-H | +| 10 | Each environment builds for its own origin: `NEXT_PUBLIC_SITE_URL` (the metadataBase) = `SITE_URL` or the workers.dev URL | The sample's Open Graph images are relative; upstream resolved them against localhost | IMPLEMENTATION-STATUS | +| 11 | Two upstream bugs fixed: `/` with no Accept-Language (a 500 in the locale matcher) and a missing page (a TypeError) | A crawler or a health check must not 500; a missing page is Next's noindex not-found page | IMPLEMENTATION-STATUS | +| 12 | Images unoptimized; `sharp` dropped | Workers has no Next.js image optimizer | IMPLEMENTATION-STATUS | +| 12a | Inter self-hosted (next/font/local, @fontsource-variable/inter, OFL) instead of next/font/google | Google Fonts answers GitHub's runners with a font URL next/font cannot read; the build needs no font network | IMPLEMENTATION-STATUS | +| 13 | Direct dependencies at upstream's locked versions; motion-dom and motion-utils held by override | framer-motion 12.23.12 imports what later motion-dom releases removed | IMPLEMENTATION-STATUS | +| 14 | The e2e connects a stand-in Strapi (`testing/lib/fake-strapi.py`) over the same seed | Strapi's REST reads, offline, deterministic, with draft reads it can tell apart | design.md §7 | +| 15 | stack-tectonic 0.19.0, `ci.yml` as the commerce baseline's, no `checks.yml`, the domain not asked, the subdomain from the Cloudflare connection | The commerce baseline's settled shape | `intent.yaml`, `blueprint.yaml` | diff --git a/ai/context/deployment.md b/ai/context/deployment.md new file mode 100644 index 0000000..34337b5 --- /dev/null +++ b/ai/context/deployment.md @@ -0,0 +1,7 @@ +# strapi-launchpad — live deployment manifest + +> Not rendered yet. The bootstrap's `02-docs` phase probes every live URL and +> regenerates this file from what answered — the workspace, the URLs and +> their status, whether a Strapi project is connected, 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..97962de --- /dev/null +++ b/ai/context/open-risks.md @@ -0,0 +1,18 @@ +# strapi-launchpad — open risks + +What is not yet proven or not yet decided. The full write-up of every risk, +including the accepted and resolved ones, is +`specs/epics/strapi-launchpad/risks-and-open-questions.md`; this page lists +only what is still live, so it should be short. + +| ID | Risk | State | What closes it | +|---|---|---|---| +| SL-A | No live bootstrap yet: the repository created and linked, the two tokens minted, a real `terraform apply`, a real `wrangler deploy` with the R2 and Durable Object bindings, the probes | OPEN | One bootstrap from a tag against a workspace | +| SL-B | No real Strapi project connected: a Strapi Cloud project running LaunchPad's `strapi/` app, its CORS and Public-role permissions, and its preview button are untested | OPEN | A Strapi Cloud project connected once | +| SL-C | Cache Components off until @opennextjs/cloudflare runs them on workerd | ACCEPTED | An npm release with a fix for opennextjs-cloudflare#1450 | +| SL-I | LaunchPad declares MIT (its `next/README.md`, `strapi/package.json`) but ships no LICENSE file; `apps/web/LICENSE.md` is the standard MIT text with LaunchPad's authors as holders | OPEN — for the registry's owner to review | A LICENSE in strapi/LaunchPad, or a decision | + +Accepted, and worth knowing before you change them: SL-D (Next pinned to +16.3.8 with the adapter), SL-E (images unoptimized), SL-F (the sample is the +seed as published — its English hero reads "(Draft) …"), SL-G (the stand-in +is not a real Strapi), SL-H (the site-name seam; gated). diff --git a/ai/context/operations.md b/ai/context/operations.md new file mode 100644 index 0000000..c6be525 --- /dev/null +++ b/ai/context/operations.md @@ -0,0 +1,185 @@ +# strapi-launchpad — operating contract (for humans and agents) + +This is the standing guide to how this site is deployed and operated. +Instance facts (live URLs, workspace, whether a Strapi project is connected, +the secrets it uses) live in [deployment.md](deployment.md), rendered from +probed reality by the bootstrap's `02-docs` phase; this file is the contract +that stays true between deployments. It is written to give an agent with +repository read access enough context to reason about and operate the site +without any other source. + +## What this system is + +A Strapi-powered marketing site on Cloudflare, expressed as an Orun +component-native desired-state repo. Strapi itself — the content, the media, +the admin — is the owner's project (Strapi Cloud, or their own Strapi running +LaunchPad's `strapi/` app), reached over its REST API; nothing here runs +Strapi. + +- **`infra/terraform/cloudflare-r2`** — one R2 bucket per deployed + environment (`stage`, `prod`), applied by Terraform: the site's Next.js + incremental cache. After each apply it publishes a wiring document — + `{r2_bucket_name}` — as the Orun secret `WIRING_CLOUDFLARE_R2` on that + environment. +- **`apps/web`** — the site: LaunchPad's Next.js front end built by + `@opennextjs/cloudflare` into one Worker plus Static Assets. Every page + renders per request from cached Strapi reads: each read is a `"use cache"` + function (`lib/strapi/client.ts`) tagged by type or document with Next's + `minutes` profile. The Worker binds the bucket (`NEXT_INC_CACHE_R2_BUCKET`) + and exports two Durable Objects: the tag cache and the revalidation queue. + Until a Strapi project is connected, every read is answered by the bundled + sample (`apps/web/sample/strapi`, the template's own seed) and nothing is + fetched. +- **`tests/web`** — the sample and the client's switch to it, the site-name + seam, the locale proxy, `/api/health`, the preview route's refusal and the + build's settings (vitest). No lane runs it: the `dev` lane of `tests/web` + installs it and checks its structure, so run `pnpm typecheck`, `pnpm lint` + and `pnpm test` before you push. +- **`tooling/*`** — shared TypeScript and ESLint configuration, and the + wrangler renderer that turns `wrangler.template.jsonc` plus a wiring + document into `wrangler.jsonc`. + +Environments: **`stage`** and **`prod`** are deployed; **`dev` is +verify-only by design** — lanes build and dry-deploy, nothing deploys, and +no bucket exists for it (its build renders the committed fixture). + +## 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. **The bucket before the Worker.** `cloudflare-r2` applies for the + environment and publishes `WIRING_CLOUDFLARE_R2`. `apps/web` declares an + enforced `dependsOn` on it for pushes to `main`, so its deploy starts only + after that apply — and a job resolves its secrets when it starts, so the + document is there. +4. `apps/web` renders `wrangler.jsonc` from that document (the real bucket + name) and builds once per environment: `NEXT_PUBLIC_SITE_URL` is the + environment's `SITE_URL` (intent.yaml) or its workers.dev URL, and the + Strapi URL is the environment's `STRAPI_URL` secret, when set (the + redirects are read from it then). `wrangler deploy` ships + `strapi-launchpad-web-` (the Durable Objects are created by the + config's migration on the first deploy), and a smoke test fetches `/` + (which must render the site's navigation) and `/api/health`, which only + the Worker answers. +5. `prod` deploys after `stage` has converged on the same commit + (`environments.prod.promotion` in intent.yaml). +6. **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. + +On a pull request nothing applies or deploys: the R2 root plans, the site +builds and dry-deploys, and the edges in step 3 are advisory. + +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`. +- Setting or changing `STRAPI_URL` builds nothing: it is read when the site + builds. Redeploy it (below). So are Strapi's redirects. +- `wrangler.jsonc` is generated. Edit `wrangler.template.jsonc`, run + `pnpm run wire:fixture` and commit both; the deploy renders its own + config from the template, so a stale committed render misleads local work. + +## The content + +- **No Strapi project connected** (no `STRAPI_URL` for the environment): + the build and the Worker fetch nothing; every page renders the bundled + sample — the template's seed, in English and French — under a bar that + says how to connect Strapi; the seed's redirects redirect; + `/api/health` answers `{"ok":true,"content":"sample"}`. +- **Connected**: every page reads the project through cached reads (the + bar is gone); `/api/health` answers `{"ok":true,"content":"strapi"}`; + media are the project's (`/uploads/…`). An entry older than a + minute is served once more while it is re-read in the background; none + outlives an hour. +- **Draft mode**: `/api/preview?secret=&url=` turns + it on (Strapi's preview button opens it); every read then asks Strapi for + drafts, past the cache, until `/api/exit-preview`. With no + `PREVIEW_SECRET` set, preview is refused (401). +- `/` redirects to the visitor's locale (`en`, `fr`) by Accept-Language; a + page that does not exist is Next's not-found page, marked `noindex`. + +## Secrets model + +- **Brokered provider secrets**: `CLOUDFLARE_API_TOKEN` (the + `workers-deploy` scope: Workers Scripts and KV Storage write) deploys the + Worker; `CLOUDFLARE_R2_TOKEN` (the `r2-data` scope: R2 Storage write) is + what the R2 root's Terraform authenticates with, because the deploy token + carries no R2; `CLOUDFLARE_ACCOUNT_ID` is the connection fact both bind. + Minted per run from the workspace's Cloudflare connection — no long-lived + values at rest, nothing to rotate by hand. +- **Wiring**: `WIRING_CLOUDFLARE_R2` on `stage` and `prod`, written by the R2 + root's apply (lease-published), read by the Worker's build as + `WIRING_CLOUDFLARE_R2_`. It holds the bucket name, not a credential. +- **The project**: `STRAPI_URL` per environment, an Orun secret the owner + sets (`orun secrets set STRAPI_URL --env `), optional — read by the + build and inlined as `NEXT_PUBLIC_API_URL`, because browser code reads it + too. It is not a credential: the site reads published content as Strapi's + Public role. +- **Worker secrets**: `PREVIEW_SECRET` on `strapi-launchpad-web-`, set + by the owner with `wrangler secret put`; the pipeline never reads or + writes it. +- Inspect by NAME only: `orun secrets list --org --project` and + `--env stage|prod`; `wrangler secret list --name strapi-launchpad-web-`. + 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); +# /api/health says whether it serves the sample or a Strapi project +curl -s https://strapi-launchpad-web-stage.your-workers-subdomain.workers.dev/api/health +curl -s -o /dev/null -w '%{http_code}\n' https://strapi-launchpad-web-prod.your-workers-subdomain.workers.dev/en + +# the wiring and the project the deploys read, and workspace readiness +orun secrets list --org --env stage && orun secrets list --org --env prod +orun integrations list --org --json && orun cloud check --org +``` + +## Common operations + +| task | how | +|---|---| +| change the site | edit `apps/web` (its name: `apps/web/lib/site.ts`), merge | +| edit the content | in the Strapi project's admin; published changes show within a minute or two | +| connect a Strapi project | the README's "Connecting Strapi": `STRAPI_URL` per environment, then redeploy the site | +| preview drafts | `PREVIEW_SECRET` as a Worker secret, and the same value (with `CLIENT_URL`) in the Strapi project | +| change the sample | re-export it from a Strapi that imported the seed you want, as `apps/web/sample/strapi/..json` without `formats`, and its images into `apps/web/public/uploads` | +| 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= [-f component=]` — 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 `) and merge — it is a deploy trigger, nothing reads it | +| empty the data cache | delete the bucket's `incremental-cache/` objects, or redeploy | +| add a binding (D1, KV, another bucket) | a Terraform root under `infra/terraform/` that publishes `WIRING_`, a token in `wrangler.template.jsonc`, its fixture entry, the root in the build's `--components`, the `WIRING__` secretEnv and an enforced `dependsOn` on it in `apps/web/component.yaml` | +| serve a custom domain | attach it to the Worker in Cloudflare and set `SITE_URL` for the environment in `intent.yaml` (README, "Custom domain"), then replace the placeholder `strapi-launchpad.example.com` in `intent.yaml`'s `BASE_DOMAIN` with it | +| add a runtime secret | `wrangler secret put --name strapi-launchpad-web-` for the Worker; `orun secrets set --org --env ` for a lane | +| headless credentials | `ORUN_TOKEN` (workspace-scoped) + `GITHUB_TOKEN` | + +The deployment record is the bootstrap's `02-docs` phase. Re-running it (the +Orun console's Retry on that phase, or `orun new … --phase 02-docs`) +re-probes the URLs and re-renders [deployment.md](deployment.md); it is +idempotent. + +## Evolution + +Structural changes 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. When +@opennextjs/cloudflare runs Cache Components on workerd, turning them back on +(`cacheComponents: true` in `apps/web/next.config.ts`, in place of +`experimental.useCache`) restores upstream's configuration; the +`"use cache"` reads need no change. diff --git a/apps/web/app/[locale]/layout.tsx b/apps/web/app/[locale]/layout.tsx index ae2e50f..c4868ff 100644 --- a/apps/web/app/[locale]/layout.tsx +++ b/apps/web/app/[locale]/layout.tsx @@ -1,6 +1,6 @@ import { Metadata } from 'next'; import { ViewTransitions } from 'next-view-transitions'; -import { Inter } from 'next/font/google'; +import localFont from 'next/font/local'; import { draftMode } from 'next/headers'; import type { PropsWithChildren } from 'react'; import React from 'react'; @@ -16,10 +16,15 @@ import { fetchSingleType, isStrapiConnected } from '@/lib/strapi'; import { cn } from '@/lib/utils'; import type { LocaleParamsProps } from '@/types/types'; -const inter = Inter({ - subsets: ['latin'], +// Inter, self-hosted: the variable font's latin subset (weights 100–900, +// covering the template's 400–900), from @fontsource-variable/inter 5.2.8 — +// OFL-1.1, ../fonts/Inter-OFL.txt. Upstream fetched it from Google Fonts at +// build time, which fails on GitHub's runners (Google answers a font URL +// without an extension, which next/font's loader cannot read). +const inter = localFont({ + src: '../fonts/inter-latin-wght-normal.woff2', display: 'swap', - weight: ['400', '500', '600', '700', '800', '900'], + weight: '100 900', }); // Default Global SEO for pages without them diff --git a/apps/web/app/fonts/Inter-OFL.txt b/apps/web/app/fonts/Inter-OFL.txt new file mode 100644 index 0000000..40589da --- /dev/null +++ b/apps/web/app/fonts/Inter-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter) Inter-Italic[opsz,wght].ttf: Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/apps/web/app/fonts/inter-latin-wght-normal.woff2 b/apps/web/app/fonts/inter-latin-wght-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..d15208de03cd1ad7c5199f0a0ce915fe841e4722 GIT binary patch literal 48256 zcmY(qQ;;}L&?GpvJ@Xsewr$(CZQHhO+qP}nHuwMC-frAwKU8*AMD|NXKXg{R$%!%o z00R7nZhrvO{{rAX{(l_wf9L)u|NjS8sP4bOMq%s~dp>bh0mUc_KAHc5E|@-_lCpqu zfGim)KnN?HH6jF5Ko@^N0Sa_D8~}Y_HZLG65HWB(1_(ZAC@pva2n@KE(@cV3_rJN@ zn;~mU`I0RJ|H+Cb#jiShU^cg6`%XnS7bCbgg;C{t9iDca{lng-mFvI%FegiD6m8pN z`_JD$G)3d@FJGZEOKh?vwFPSdW*2cc0wYxVV2D{tb@kF9Yg_0c?AmFTV}z(AIX2o% zbRV=fRtM}F;{$;rLcW}5?IlE|+b1%2-cvuD&UoawY`)@_X=c6RC(2%7q(kw8_;ocFmVabMzd#!`S#lF4}TNR1HVRdk&j$3c@!VLD?fRP8wTo&;#< z^>TZjk^$};QGy^-M1Xk%!mBn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DoDQSs^q(Np6tHZ--qzG|gYYbHN91e+)jBd?W@F@Og-xpO1j+2{~|L zQ3^tY@Oa9_LfLtU5Xg+j za)YzLwdD;ucXk!yVAnUE9?CA@I-osM$AAv*MN)KIO0cNDJXPZ{tBq)Ma*M*NLvr|ggzT(k8&Diziw%}5!U%gf=bl;q6_Zs zSX-$O)h;HSDdB8Sqbp@anTQG(B@Z6!Ydum5O*5tvkz%ObZfpK$x;N#{v_fsKp4IAu z<+Qdi1ECN$uQgy>ghT!on{(I9ifOh+7Enu$Nn?_FA!Sa`=%d81yWRLK>}hLlWEH#@ z=h~bGADN%zNSgek=0iy@70JAx9r0SEx}&8SW|6k*F4_BT-+au1pb)VmkFzx&qYvuvf>RH45Rn z{T#+_5L&EKVz?A9Zuu}+k_Afu6vCx=kz>Q;5eBexV3$c4FidQqd!_+2mKSdT@tb^` zpal00K(GDaumnIMOs}y45U^9g003+NfbIck0B->CD{vLm$UQd6j|%Z-jLrS|$+2AV zcoKRRD#n#xY4Ac2Gegc0CecSM=6zow9U$}+WS-^`Wq21j)({W0zIbZCPvGa@T?O4MgT03=&6St#>snIr7UzT-&}k z>v>pU6xG@og7{IenU-t)AK{BTuc|ejZA%x*LUR&K(0^EM7~AFrThcz7;mW#-?oTFLTj(bCRieu&P`s;A7 ov+5Z$hJGB_FISZ`lH5O4PBqq<6^F{d-($z`vHZ{4l`jAQ04qY + Vercel's LaunchPad (Next.js × Strapi Starter) as a product of its own: + the LaunchPad marketing site — a home page built from Strapi's dynamic + zones, pricing, FAQ and contact pages, a blog and a product catalogue, + in English and French, with draft mode for Strapi's preview — built by + OpenNext into one Cloudflare Worker with Static Assets. Every Strapi + read is cached with "use cache" in an R2 bucket Terraform provisions per + environment, with its tag cache and revalidation queue in Durable + Objects. CI applies the bucket and deploys the site to stage and prod on + merge. It goes live before any Strapi project exists, on the template's + own seed as sample content, and reads yours once you set its URL. One + provider, one consent, one landing. + tags: [marketing, cms, strapi, i18n, r2, cloudflare, nextjs] +spec: + source: + repo: sourceplane/strapi-launchpad + # No `tag`. The registry pins it; this file is fetched at it. + + # ── What the operator reads first ──────────────────────────────────────── + overview: + lede: > + A Strapi-powered marketing site on Cloudflare: LaunchPad's Next.js + front end on one Worker, every Strapi read cached in R2. It deploys on + the template's own sample content before your Strapi project exists; + set your project's URL and it renders your pages, posts and products. + architecture: + - layer: Edge + items: [web] + - layer: Content + items: [Strapi (your project - connected after the build)] + - layer: Cache + items: [R2 (cloudflare-r2), Durable Objects (tag cache and queue)] + - layer: Delivery + items: [GitHub Actions, OpenNext, Terraform] + outcome: + - Live on stage and prod, in one landing + - The R2 cache bucket applied before the Worker that binds it + - Live on sample content before a Strapi project is connected + - Strapi reads cached at the edge + - Every merge redeploys, smoke-tested + - Its own CI from the first commit + + 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. Strapi is not a provider the platform brokers: the + # site deploys on its bundled sample content, and its owner connects a + # Strapi project after the build by setting its URL as an Orun secret — + # the product's README, "Connecting Strapi" — so the card asks for + # nothing of Strapi's. + 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 `.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 logo, the sign-up heading, the default page title. + example: Acme Launch + - 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, the phase probes and the verify + # URLs below. The integration reads it from Cloudflare at connect and on + # its hourly health check; the bootstrap door fills this input from the + # connection the build is BOUND to, the same one CLOUDFLARE_ACCOUNT_ID + # and the deploy tokens mint from, so all three name one account. The + # console renders no field for it. 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 one `orun.integrations/reconcile@v1` + # hook (`secrets`) mints these, brokered, during 01-product. ────────────── + # Transcribed from that hook's own `secrets:` entries (each key and its + # template), in its order, so testing/manifest.test.sh compares this list + # to the document that mints them. The console renders them read-only: no + # credential is ever typed, shown or stored. Keys that already exist are + # kept. The bucket names are not here: they are not credentials, and the + # bucket's own apply publishes them. Nor is anything of Strapi's: the + # platform does not broker it, and the site needs none to go live. + secrets: + - key: CLOUDFLARE_API_TOKEN + provider: cloudflare + template: workers-deploy + why: Deploys the site's Worker and its static assets + - key: CLOUDFLARE_R2_TOKEN + provider: cloudflare + template: r2-data + why: Applies the R2 cache bucket — the deploy token deliberately carries no R2 + - 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: strapi-launchpad-baselining # = repo-blueprint.yaml's `epicSlug` default + epicName: "Marketing site baselining — {productname}" + milestones: + # The whole product is one landing (01-product): the repository, the R2 + # root, the site and its tests are one pull request and one + # convergence. + - name: 01-product + - name: 02-docs + + bootstrap: + # THE BUILD DOCUMENT. There is no umbrella workflow and no agent brief: + # every phase is declared in it and orun runs it. + blueprint: repo-blueprint.yaml + # Summed from the phases' expectedMinutes (14 + 1). An estimate until a + # bootstrap measures it: no build of this baseline has been timed. + expectedMinutes: 15 + 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..f0aaf7b --- /dev/null +++ b/docs/phases/01-product.md @@ -0,0 +1,82 @@ +# 01-product — the product, built in one landing + +**Places** every module: the root manifests, CI, tooling and the identity +file; `infra/terraform/cloudflare-r2` (the R2 cache bucket per environment); +`apps/web` (the LaunchPad site, its sample content, its OpenNext build, its +wrangler template and fixture, its deploy contract); `tests/web` (vitest). +Then brands them, lands them as ONE pull request, and watches the ONE +convergence that merge triggers. + +**Requires** both connections live — GitHub (the App installation on the +OWNER of the repository, the only way the platform sees its pull requests) +and Cloudflare (every deploy credential below is minted from it) — probed, +waited for up to ten minutes each, so the consent can be clicked while it +waits. Strapi is not required: the site goes live on its sample content, +and the owner connects a project afterwards (the product's README, +"Connecting Strapi"). + +## 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 the components `.baseline/tasks/01-product.TaskContract.yaml` names: `cloudflare-r2`, `web`, `web-tests` | +| `git-init`, `stage`, `rebrand` | the tree becomes a repository, then the product's | +| `orun-workspace` | intent.yaml's `workspace:` becomes the product's (or `ws_SET_ME`, which fails loudly) | +| `work-tree` | intent.yaml's `work:` block — this repository's epics and tasks — is removed | +| `promotion`, `dev-lanes` | prod's promotion gate and dev's push-to-main activation deferred until `02-docs` | +| `restage`, `rebrand-verify` | the sweep: no identity of this baseline left anywhere | +| `repo` | `orun.repo/ensure@v1` creates `/` (or finds it) | +| `link` | the repository becomes the workspace's; `orun cloud check` is the gate | +| `secrets` | `orun.integrations/reconcile@v1`, the three keys in one hook, created side by side, each under its own template: `CLOUDFLARE_API_TOKEN` from `workers-deploy` (Workers Scripts and KV write, for the site's deploy — it carries no R2); `CLOUDFLARE_R2_TOKEN` from `r2-data` (R2 Storage write, which the R2 root's Terraform binds as its provider token); `CLOUDFLARE_ACCOUNT_ID`, the connection fact both bind | +| `task` | finds the phase's task and yields its key — waiting, if it must, for the background set-up | +| `land` | one PR bound to the task, its commit checked in the box first (`checks: local`: `orun validate`, then `orun plan` as the PR and as the merge would plan it, under a second); merged without waiting for the PR's CI | +| `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` on the merge plans, with dev's push activation and the +promotion gate deferred: + +| lane | waits on | does | +|---|---|---| +| `cloudflare-r2 · stage` / `· prod` | nothing | `terraform apply` of `stg--stage` / `prod--prod` with the `r2-data` token, adopting a bucket of that name if one exists (`adopt.tf`), then lease-publishes `WIRING_CLOUDFLARE_R2` = `{r2_bucket_name}` on that environment | +| `stage · web` / `prod · web` | that environment's R2 apply (`dependsOn: cloudflare-r2`, `mode: enforced` on main) | resolves `WIRING_CLOUDFLARE_R2_` as it starts, renders `wrangler.jsonc` with the real bucket name, builds with OpenNext, deploys `-web-` (the Durable Objects' migration runs on this first deploy), and smoke-tests it: `/` must answer and `/robots.txt` must name the origin it was asked on, which only the Worker renders | + +Stage and prod run side by side. `web-tests` verifies on dev only, on a pull +request. The landing's own pull request runs `plan` alone, and nothing waits +for it — the same plan ran in the box before the push: the baseline's own CI +installed, type-checked, linted, tested and built this exact tree before the +tag was cut. A later pull request's `web-tests` lane installs and checks the +package; it does not run the suite, so the product's developers run +`pnpm test` and `pnpm lint` before they push. + +## Verified + +The convergence run for the merge commit is green — the site resolved +`WIRING_CLOUDFLARE_R2` from stage and prod, where every later deploy reads +it; `https://-web-{stage,prod}..workers.dev` answer — +on the sample content, until the owner connects a Strapi project. + +## Troubleshooting + +| symptom | cause → fix | +|---|---| +| parks on the `providers` probe | GitHub (on the repository's owner) or Cloudflare is not connected to the workspace. Connect it (console → Integrations), then re-run the phase — the probe is a wait, not a failure | +| 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 | +| `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 | +| `secrets` fails `parent_grant_insufficient` on `CLOUDFLARE_R2_TOKEN` | the connection's Account API token lacks Workers R2 Storage Write; add it (the console's Connect recipe lists it under "R2 data access"), re-connect, re-run the phase | +| R2 lane: Authentication error (10000) on the bucket list or create | the R2 root is not using the `r2-data` token — `infra/terraform/cloudflare-r2/component.yaml` must bind `CLOUDFLARE_API_TOKEN` to `CLOUDFLARE_R2_TOKEN`; the deploy token carries no R2 | +| R2 lane: `The bucket you tried to create already exists` (10004) | `adopt.tf` imports a bucket of the same name; if it was removed, restore it. Two products with the same `reponame` in one account share bucket names — use a distinct `reponame` | +| 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, re-connect, re-run the phase | +| web lane fails resolving `WIRING_CLOUDFLARE_R2_` | that environment's R2 apply failed or never ran — read its lane; the web lane waits on it, so it shows as not run on a fresh failure | +| web lane `build-app`: `wire: missing wiring documents` | the job started without the document — the `dependsOn` edge is gone from `apps/web/component.yaml`, or the secretEnv names the wrong key | +| web lane `verify-app-structure`: `test -f wrangler.jsonc` fails | `apps/web/wrangler.jsonc` is not committed (an old `.gitignore` entry); render it with `pnpm run wire:fixture` and commit it | +| `build-app` fails: `Symlink apps/web/node_modules/next is invalid, it points out of the filesystem root` | the site's `intent.yaml` pins stack-tectonic ≥ 0.20.0 (lane-scoped install). Pin 0.19.0 — `intent.yaml`'s comment says why | +| 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 | +| 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 | +| convergence failed AFTER the PR merged; re-running 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 store's tree says which | diff --git a/docs/phases/02-docs.md b/docs/phases/02-docs.md new file mode 100644 index 0000000..257ce3f --- /dev/null +++ b/docs/phases/02-docs.md @@ -0,0 +1,39 @@ +# 02-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 `/` and `/api/health` on both environments (whether the Worker itself answered, and whether a Strapi project is connected) 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 or a custom +domain: every generated section is re-rendered from scratch. + +```bash +orun new --blueprint repo-blueprint.yaml --out \ + --run-hooks --phase 02-docs --values +``` + +## 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 /intent.yaml +node tooling/bootstrap/dev-lanes.mjs --restore --file /intent.yaml +``` diff --git a/docs/phases/README.md b/docs/phases/README.md new file mode 100644 index 0000000..77f1d59 --- /dev/null +++ b/docs/phases/README.md @@ -0,0 +1,125 @@ +# 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**. Run them one at a time with +`--phase `, 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 product 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 + +| phase | lands | verified by | +|---|---|---| +| [`01-product`](01-product.md) | **the GitHub repo created** and the whole product in ONE pull request: intent, CI, tooling, identity, the R2 root, the site and its tests | the convergence green (R2 applied, then the site built, deployed and smoke-tested), both URLs answering | +| [`02-docs`](02-docs.md) | the live-deployment record; the promotion gate and dev's lanes put back | committed manifest matches probed reality | + +**One landing, not three.** Before the one-landing shape a site like this +landed its scaffold, its data plane and its app as separate pull requests, +because the bucket had to exist before the Worker that binds it. The plan +carries that order now: `apps/web` declares `dependsOn: cloudflare-r2` with +`mode: enforced` on a push to main, so the convergence that follows the one +merge applies the bucket first and deploys the site after it — and a +job resolves its secrets when it starts, so the bucket name the apply +published is there. On a pull request the edge is advisory: nothing deploys. +`testing/phases.test.sh` checks the edge; `testing/placement.test.sh` checks +the product's own plan honours it. + +Every landing is a pull request on a branch named for its task +(`orun/BASE--`), checked before it is pushed: `orun validate`, then +`orun plan` as the pull request and as the merge would plan it, in the box, +in under a second (`checks: local`). Then it merges; nothing waits for the +PR's CI. On those branches `ci.yml` runs `plan` only and skips the lanes, +because the merge runs them on main a minute later, for real, and that +convergence is what the phase watches. The product carries no other +workflow: the baseline's own CI (Tier 2) installs, renders the fixture, +type-checks, lints, tests and builds this landing before a tag is cut, and +every later pull request in the product runs `ci.yml`'s verify lanes (which +build and dry-deploy, but neither lint nor run the tests). + +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: attach it to the Worker, then set the environment's +`SITE_URL` in `intent.yaml` so the next deploy resolves the site's Open +Graph images against it. + +## Inputs + +`01-product` takes the site's identity once and writes it into the repo +(`.rebrand/values.json`); `02-docs` reads it back from the placed tree. But +the blueprint's **required** inputs — `reponame`, `productname`, +`githuborg` — are validated before any phase runs, so they must be supplied +on every invocation, single-phase ones included. A `--values` file is easier +than repeating `--set`. + +- `productdomain` — NOT ASKED, default empty. The site goes live on + workers.dev; empty brands the reserved placeholder `.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. 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 `strapi-launchpad-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-launch --run-hooks --phase 01-product \ + --values ~/acme-launch.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 the product phase 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 01-product ` line at the end of + each component.yaml its task contract names (`cloudflare-r2`, `web`, + `web-tests`), so a re-run after a failed convergence still has a diff to + land and re-plans exactly those components. +2. `git init`, stage, `rebrand`, the workspace rewrite, the work-tree strip, + the two bootstrap deferrals (prod's promotion gate, dev's push lanes), + restage, `rebrand --verify` — the identity rename over the whole tree, + then a sweep that fails on any of this baseline's identity left behind. +3. `repo`, `link`, the brokered Cloudflare credentials (the deploy token, + the R2 token and the account id, one `secrets` hook), `task`, `land`. The + baseline's lockfile is placed as it is and installed `--frozen-lockfile` + by the lanes; nothing re-resolves it. + +## When a phase fails + +- **Before it lands** (a probe that timed out, a rebrand residue, a refused + link): nothing was merged. Fix what the message names and re-run the phase. +- **After it lands** (the convergence went red): the files are on main. + `orun.run/watch@v1` has already resumed the run up to three times. Re-run + the phase (`--phase 01-product`, `--redo 01-product` under `--resume`, or + the console's Retry): its `retouch` hook gives the landing a diff and the + R2 root and the site re-plan. diff --git a/hooks/render-deployment-docs.sh b/hooks/render-deployment-docs.sh new file mode 100755 index 0000000..cb04328 --- /dev/null +++ b/hooks/render-deployment-docs.sh @@ -0,0 +1,175 @@ +#!/usr/bin/env bash +# Render the site's LIVE-DEPLOYMENT documentation from verified state. +# Called by phase 02-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 +# +# What it writes (in ): +# ai/context/deployment.md — REGENERATED: URLs with live probe results (and +# whether the Worker itself answered, and +# whether a Strapi project is connected), +# identity, the R2 wiring, 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 +# 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 }" +ws="${2:-}" +L="${3:?usage: render-deployment-docs.sh }" + +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="?" + +# /api/health is answered by the Worker alone — no static file has that path — +# and says what the build reads: `{"ok":true,"content":"sample"|"strapi"}` — +# the bundled sample (the template's seed) until a Strapi project is +# connected, the project after. `/` redirects to the visitor's locale (307). +# curl emits the -w format even on connection failure (000) — capture, don't +# append, or a failed probe reads "000000". +probe() { # URL → " " + local health code worker content + health="$(mktemp)" + code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 "$1/" 2>/dev/null)" || true + curl -s -o "$health" --max-time 20 "$1/api/health" 2>/dev/null || true + if grep -q '"ok":true' "$health" 2>/dev/null; then worker=worker; else worker=no-worker; fi + content="$(sed -n 's/.*"content":"\([a-z-]*\)".*/\1/p' "$health" 2>/dev/null | head -1)" + printf '%s %s %s' "${code:-000}" "$worker" "${content:-?}" + rm -f "$health" +} +badge() { # " " + local code worker content + read -r code worker content <<<"$1" + case "$code" in + 2*|3*) + if [ "$worker" != worker ]; then echo "answering $code, /api/health not answered by the Worker" + elif [ "$content" = strapi ]; then echo "LIVE ($code) — Strapi project connected" + else echo "LIVE ($code) — sample content, no Strapi project connected yet"; fi ;; + 000) echo "unreachable" ;; + *) echo "answering $code" ;; + esac +} + +stage_url="https://${brand}-web-stage.${sub}.workers.dev" +prod_url="https://${brand}-web-prod.${sub}.workers.dev" +rows="" +for pair in "stage|$stage_url" "prod|$prod_url"; do + env="${pair%%|*}"; url="${pair#*|}" + rows+="| site (${env}) | ${url} | $(badge "$(probe "$url")") |"$'\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 < GENERATED by the \`02-docs\` phase on ${now}; re-run it to refresh +> (idempotent; see [operations.md](operations.md)). Hand-edits here are +> overwritten. No secret values appear in this file — secrets are named only. + +## Identity + +| | | +|---|---| +| repository / project slug | \`${repo}\` | +| Orun workspace | \`${ws}\` | +| declared in | \`intent.yaml\` → \`execution.state.workspace\` | +| Workers | \`${brand}-web-stage\`, \`${brand}-web-prod\` on \`${sub}.workers.dev\` | +| R2 buckets (the Next.js cache of its Strapi reads) | \`stg-${repo}-stage\`, \`prod-${repo}-prod\` (\`infra/terraform/cloudflare-r2\`); their names reach the Workers as \`WIRING_CLOUDFLARE_R2\` on each environment | +| 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 and no +bucket. Until a Strapi project is connected (the README's "Connecting +Strapi"), each site renders the bundled sample content — the template's own +seed — under a bar that says how to connect one. + +## 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 | +| \`CLOUDFLARE_R2_TOKEN\` | the workspace | BROKERED (\`r2-data\`): applies the R2 bucket — the deploy token carries no R2 | +| \`CLOUDFLARE_ACCOUNT_ID\` | the workspace | the connection's account id — a fact, not a credential | +| \`WIRING_CLOUDFLARE_R2\` | \`${repo}\` on stage and on prod | written by the R2 root's apply: the bucket's name, not a credential | +| \`STRAPI_URL\` | \`${repo}\` on stage and on prod, set by the owner (optional) | the Strapi project the build reads — its public URL, not a credential | + +Brokered secrets are minted per run, so no long-lived value is at rest. 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}\`. The preview secret (\`PREVIEW_SECRET\`, Strapi's draft mode), once +set, is a Worker secret on the Workers above, not an Orun secret, and is not +listed here. + +## 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 — +the R2 bucket first, then the site. 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 = "", "" +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 `02-docs` phase); how it deploys and how to operate it: +[ai/context/operations.md](ai/context/operations.md). +{end}""" +s = open("README.md").read() +if begin in s and end in s: + s = re.sub(re.escape(begin) + r".*?" + re.escape(end), lambda _m: body, s, count=1, flags=re.S) +else: + lines = s.splitlines(keepends=True) + at = 1 + while at < len(lines) and lines[at].strip() == "": + at += 1 + lines.insert(at, f"\n## Live deployment\n\n{body}\n") + s = "".join(lines) +open("README.md", "w").write(s) +print("render-docs: README live-deployment section rendered") +PY +echo "render-docs: done" diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml new file mode 100644 index 0000000..666b2c6 --- /dev/null +++ b/repo-blueprint.yaml @@ -0,0 +1,683 @@ +apiVersion: orun.dev/v1 +kind: Blueprint +metadata: + name: strapi-launchpad + description: >- + The strapi-launchpad marketing site as a Blueprint of itself — instantiate a + new LaunchPad repository (the Strapi-powered Next.js marketing site on + Cloudflare Workers + Static Assets, R2 and Durable Objects as the Next.js + cache, the bucket Terraform provisions per environment, the template's + own seed as sample content until the owner connects a Strapi project) and take it from nothing to + live on stage and prod: ONE landing that places, brands and merges the whole product, + one convergence that applies the bucket before the Worker that binds it, + then a hook-only phase that records what went live. Run one at a time with + `--phase ` 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-shop) — intent metadata.name, the Worker name prefix, the R2 bucket names, the secret project. + productname: + type: string + required: true + description: The site's display name (e.g. "Acme Launch") — the logo, the sign-up heading and the default page title. + productdomain: + type: string + default: "" + description: >- + The site's own domain, once it has one (e.g. www.acme.dev). NOT ASKED: + the site answers on workers.dev from its first deploy, each + environment built for its own workers.dev origin (or its SITE_URL in + intent.yaml), and a domain is an owner's step after it. Empty, the rebrand writes the reserved + placeholder `.example.com` where the domain goes (BASE_DOMAIN + in intent.yaml, for every environment), 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 footer 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 and 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 and secrets. + Unset, it is the workspace the build runs in; with none anywhere, + 01-product writes a placeholder that fails loudly rather than silently + claiming another tenant's workspace. + epicSlug: + type: string + pattern: "^[a-z][a-z0-9-]*$" + default: strapi-launchpad-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 + - .next + - .open-next + - .wrangler + - .terraform + - node_modules + - .orun + - plan.json + - "**/*.tsbuildinfo" + - "**/next-env.d.ts" + - "**/*.tfstate" + - "**/*.tfstate.backup" + - "**/.terraform.lock.hcl" + # `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 02-docs renders. One module per file, so a new + # file in ai/context/ cannot ship without somebody writing a module for it. + - name: ai-operations + mode: copy + source: baseline + from: ai/context/operations.md + to: ai/context/operations.md + - name: ai-deployment + mode: copy + source: baseline + from: ai/context/deployment.md + to: ai/context/deployment.md + + # ── the 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. `packages/` has no component in this product, so it exists + # only through this file. 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 ─────────────────────────────────────────────────────── + # Only what a SITE runs: the TypeScript and ESLint configuration and the + # wrangler renderer its build calls. The factory's tooling (rebrand, + # bootstrap) stays here. + - name: tooling-tsconfig + mode: copy + source: baseline + from: tooling/tsconfig + to: tooling/tsconfig + - name: tooling-eslint + mode: copy + source: baseline + from: tooling/eslint + to: tooling/eslint + - name: tooling-wire + mode: copy + source: baseline + from: tooling/wire + to: tooling/wire + + # ── the data plane ─────────────────────────────────────────────────────── + # INFRA BEFORE APP, twice over: placed before the app that binds it (this + # DAG), and applied before it on every merge to main (apps/web's enforced + # `dependsOn: cloudflare-r2` in the convergence's plan). + - name: cloudflare-r2 + mode: copy + source: baseline + from: infra/terraform/cloudflare-r2 + to: infra/terraform/cloudflare-r2 + + # ── the site ───────────────────────────────────────────────────────────── + - name: web + mode: copy + source: baseline + from: apps/web + to: apps/web + dependsOn: [cloudflare-r2, tooling-eslint, tooling-tsconfig, tooling-wire] + - name: web-tests + mode: copy + source: baseline + from: tests/web + to: tests/web + dependsOn: [web, tooling-eslint, tooling-tsconfig] + +# ── 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: "Marketing site baselining — {{ .inputs.productname }}" + description: >- + Everything the strapi-launchpad baseline builds for + {{ .inputs.productname }} in {{ .inputs.githuborg }}/{{ .inputs.reponame }}: + the repository, its CI, its R2 cache buckets 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 }}, linked to the workspace, the product merged as one pull request + - the R2 buckets applied and their wiring published on stage and prod + - the site built, deployed and answering on stage and prod + - id: m02 + uses: orun.task/ensure@v1 + background: true + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 02-docs + exitCriteria: + - ai/context/deployment.md on main matches the probed live URLs + - prod waits on stage again + - id: t01 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 01-product + name: "Build the product in one landing" + brief: >- + Create {{ .inputs.githuborg }}/{{ .inputs.reponame }} and land the + whole product as its first pull request — intent, CI, tooling, the + R2 root, the site and its tests, branded as {{ .inputs.productname }} + — then see one convergence apply the buckets and deploy the + site to stage and prod, smoke-tested over HTTP. + prefix: BASE + contract: .baseline/tasks/01-product.TaskContract.yaml + - id: t02 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 02-docs + name: "Record the live deployment" + brief: >- + Probe every live URL one last time and write the deployment record + into the repository from what actually answered, not from what the + blueprint intended. + prefix: BASE + contract: .baseline/tasks/02-docs.TaskContract.yaml + +# ── PHASES ──────────────────────────────────────────────────────────────── +# A phase is orun's own barrier over the module DAG and the whole of what a +# phase DOES: what it is for a person (`title`), what to budget +# (`expectedMinutes`), what must already be true (`requires`), and the hooks +# that do its work around placement — `pre` before, `post` after, `await` for +# what is still converging when the hooks are done. +# +# THE ORDER HERE IS THE EXECUTION ORDER, and the numbered names are the names +# the task plane's milestones carry. A dependency may never point forward +# across a phase boundary; orun refuses the blueprint if one does. +# +# TWO PHASES. `01-product` places, brands and lands EVERYTHING as one pull +# request, and the convergence that merge triggers deploys it in dependency +# order — the R2 bucket before the Worker that binds it, because apps/web +# depends on cloudflare-r2 with `mode: enforced` on a push to main. Nothing +# about that order needs a landing of its own; the plan carries it. +# `02-docs` places NO modules: it is hooks only, a separately landable unit +# with its own task and its own PR. +phases: + - name: 01-product + title: The product, built in one landing + description: The whole tree — manifests, CI, tooling, the R2 root, the site and its tests — branded, landed as one pull request, and deployed by one convergence. + # An estimate, not a measurement — no bootstrap of this baseline has been + # timed: the landing checked here (no runner's Checks or `plan` waited + # for) and merged, then the merge's convergence — the R2 apply, then the + # site's install and build, deploy and smoke, stage and prod side by + # side. The commerce baseline's 13 on the same shape, plus one for this + # site's larger install (three.js and the animation packages; a cold + # build is about a minute on a laptop; a runner is slower). + expectedMinutes: 14 + narrate: + start: "Creating the repository and landing the whole product in one pull request — intent, CI, tooling, the R2 cache bucket and the site with its tests. Then one convergence applies the bucket and deploys the site on stage and prod. Usually about {{ .meta.expectedMinutes }} minutes." + await: "One convergence is deploying the product: the R2 bucket first, then the site built with its name, on stage and prod side by side. The site's Next.js build is the long pole; nothing is stuck." + done: "{{ .inputs.reponame }} is live on stage and prod — {{ .meta.files }} files on main, branded as {{ .inputs.productname }}, the site answering on its sample content until a Strapi project is connected. That took {{ .meta.elapsed }}." + failed: "The product did not come up. The failing lane above names the component — the R2 apply, or the site's build, deploy or smoke — and a provider error is in its log; whatever deployed is still there." + modules: [ai-deployment, ai-operations, cloudflare-r2, 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, web-tests] + # THE PLATFORM MUST BE ABLE TO SEE THE REPOSITORY BEFORE IT EXISTS. Every + # phase lands a pull request that files under its task, and the platform + # learns of a PR only through the GitHub App installation on the account + # that OWNS the repository. So the owner's connection is asked for here, + # before a repository is created, and waited for like any other consent. + # And the Cloudflare connection, which every deploy credential below is + # minted from — asked for here too, since this phase is the one that + # deploys. + requires: + probe: + - id: providers + uses: orun.doctor/check@v1 + with: + providers: [github, cloudflare] + githubOwner: "{{ .inputs.githuborg }}" + waitSeconds: 600 + pollSeconds: 20 + hooks: + # The whole tree is placed when these run. rebrand.mjs enumerates it + # 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. + post: + # A RE-RUN MUST HAVE SOMETHING TO LAND. A convergence can fail AFTER + # its PR merged, and the merge has already put every file 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 ` — and the + # landing has a diff that re-plans exactly those components. The + # marker is a deploy trigger, not state: nothing reads it back. + - id: retouch + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/retouch.mjs", "--phase", "{{ .phase.name }}", "--affects", "{{ .baseline.dir }}/.baseline/tasks/01-product.TaskContract.yaml"] + - id: git-init + run: ["git", "init", "-q"] + - id: stage + run: ["git", "add", "-A"] + - id: rebrand + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--values", ".rebrand/values.json", "--allow-dirty"] + # Re-tenant the 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 02-docs. tooling/bootstrap/promotion.mjs. + - id: promotion + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/promotion.mjs", "--defer"] + # DEV'S VERIFY LANES STAY OFF MAIN UNTIL THE BOOTSTRAP IS DONE, by the + # same mechanism: a third Next.js build on the 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: 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. + # This product needs two scopes on purpose, and still gets them: each + # key keeps its own template. `workers-deploy` (Workers Scripts and KV + # write) deploys the site's Worker; it carries NO R2, so the R2 + # root cannot create or list a bucket with it. `r2-data` (Workers R2 + # Storage Write) is the R2 root's own token, CLOUDFLARE_R2_TOKEN, which + # its component binds as the provider's CLOUDFLARE_API_TOKEN — the way + # a D1 root binds a d1-edit token. The account id is a connection fact + # both bind. 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_R2_TOKEN, template: r2-data } + - { 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 product in one landing" + prefix: BASE + contract: .baseline/tasks/01-product.TaskContract.yaml + # THE PRODUCT IS A PULL REQUEST THAT IS CHECKED, THEN MERGED — checked + # HERE (`checks: local`, orun >= v2.88.0): `orun validate`, then + # `orun plan` as the pull request and as the merge to main plan it, + # on the commit, before it is pushed. That is what the PR's `plan` + # job checks (the intent, every component and every composition + # resolve), plus the merge's own plan, in under a second instead of a + # runner's. A tree that fails is never pushed. The PR's CI still runs + # (`plan` alone on a bootstrap branch, `orun/BASE-…`, ci.yml); nothing + # waits for it. The merge runs every lane on main a minute later, for + # real, and that convergence is what `await` watches. + - id: land + uses: orun.pr/land@v1 + narrate: "The product is merged into main." + with: + task: "{{ .phase.hooks.task.outputs.key }}" + epic: "{{ .inputs.epicSlug }}" + branchSlug: "{{ .phase.name }}" + title: "feat: {{ .inputs.productname }}, the whole product from the strapi-launchpad baseline" + checks: local + await: + - id: converge + uses: orun.run/watch@v1 + narrate: "The R2 bucket applied, the site built with its name, 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. + # Only ci.yml runs on a push to main, so it is that workflow's run. + 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 + # NO SEPARATE WIRING CHECK. The R2 root's apply lease-publishes its + # wiring document to the project's stage and prod rungs, and its one + # reader resolves it in this convergence from the place every later + # run looks: the site's deploy job, on stage and on prod, + # resolves WIRING_CLOUDFLARE_R2_STAGE and _PROD (apps/web/component.yaml's + # secretEnv, waiting on the apply — enforced on main) before its first + # step, fail-closed. A missing document fails that lane, so a green run + # already says it is there. WIRING_CLOUDFLARE_R2 was the await's only + # key, so the await goes with it. + - 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: 02-docs + title: The deployment, recorded + description: The live-deployment manifest, rendered from probed reality, and the promotion gate and dev's lanes put back. + # An estimate, not a measurement: the render's two probes, the task, and + # one landing checked here and merged, with nothing after it to wait for. + 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/02-docs.TaskContract.yaml + # Checked here and merged, as 01-product's landing is + # (`checks: local`). + - 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 8ee7bbd..b81b0a9 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 | |------|---------|--------|------------| -| [`strapi-launchpad/`](./strapi-launchpad/) | **SL** | In progress (SL1: the site on Workers) | LaunchPad's Next.js front end (Vercel's LaunchPad: Next.js × Strapi Starter) on Cloudflare Workers, its Strapi reads cached in R2 + Durable Objects, the template's seed as sample content until a Strapi project is connected | +| [`strapi-launchpad/`](./strapi-launchpad/) | **SL** | ✅ Shipped (`baseline-v1`); live bootstrap pending | LaunchPad's Next.js front end (Vercel's LaunchPad: Next.js × Strapi Starter) on Cloudflare Workers, its Strapi reads cached in R2 + Durable Objects, the template's seed as sample content until a Strapi project is connected | As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`. diff --git a/specs/epics/strapi-launchpad/IMPLEMENTATION-STATUS.md b/specs/epics/strapi-launchpad/IMPLEMENTATION-STATUS.md index 2c06577..6be33f4 100644 --- a/specs/epics/strapi-launchpad/IMPLEMENTATION-STATUS.md +++ b/specs/epics/strapi-launchpad/IMPLEMENTATION-STATUS.md @@ -4,7 +4,7 @@ |---|---|---| | SL0 — the spec | ✅ | SL-1 | | SL1 — the site on Workers | ✅ | SL-2 | -| SL2 — a baseline | planned | SL-3 | +| SL2 — a baseline | ✅ | SL-3, tagged `baseline-v1` | ## Departures from the upstream template @@ -25,6 +25,7 @@ Everything not listed here is strapi/LaunchPad `next/` as it is at `c54b5c2`. | 11 | `app/api/health/route.ts` | The deploy's smoke and the record's probe | | 12 | ESLint: upstream's `next/core-web-vitals` in eslint-config-next 16's flat form, with `react-hooks/immutability`, `refs`, `set-state-in-effect` and `purity` off by name | Next 16 removed `next lint`; the React Compiler rules postdate the template's animation components | | 13 | `typecheck` (`next typegen && tsc`), `preview` and `wire:fixture` scripts | The workspace's checks and the wiring | +| 13a | Inter self-hosted through `next/font/local` (`app/fonts/inter-latin-wght-normal.woff2`, the variable font's latin subset from @fontsource-variable/inter 5.2.8, OFL-1.1 — `app/fonts/Inter-OFL.txt`) instead of `next/font/google` | On GitHub's runners Google Fonts answers a font URL with no extension and next/font's loader throws; the build needs no network for fonts | | 14 | `LICENSE.md` (MIT, as upstream declares; it ships no LICENSE file) and `README.md` replaced by the app's own | The licence travels with the code | | 15 | Not carried: `strapi/`, `astro/`, `nuxt/`, `tanstack/`, `scripts/`, the root's yarn and prettier setup, `next/migration-log.md` | The Next front end only (design §1) | diff --git a/specs/epics/strapi-launchpad/README.md b/specs/epics/strapi-launchpad/README.md index b4827df..b965feb 100644 --- a/specs/epics/strapi-launchpad/README.md +++ b/specs/epics/strapi-launchpad/README.md @@ -9,7 +9,7 @@ in Durable Objects.** | | | |---|---| -| Status | In progress — SL1 on main: the site runs on Workers | +| Status | ✅ Shipped (`baseline-v1`) — proven offline in Baseline CI; not yet live (risk SL-A) | | Upstream | [strapi/LaunchPad](https://github.com/strapi/LaunchPad) `next/` (MIT, declared), at `c54b5c2` (2026-10-16); the seed is its `strapi/data` export | | Reference | [cms-sanity](https://github.com/sourceplane/cms-sanity) for a CMS-backed site that goes live before the CMS is connected; [commerce](https://github.com/sourceplane/commerce) for the OpenNext, R2 and Durable Object cache shape | | Key | `SL` | diff --git a/specs/epics/strapi-launchpad/epic.yaml b/specs/epics/strapi-launchpad/epic.yaml index bd567b8..6830583 100644 --- a/specs/epics/strapi-launchpad/epic.yaml +++ b/specs/epics/strapi-launchpad/epic.yaml @@ -9,7 +9,7 @@ metadata: spec: title: "LaunchPad's Strapi-powered marketing site on Cloudflare Workers" summary: "LaunchPad's Next.js front end (Vercel's LaunchPad: Next.js × Strapi Starter) — a home page from Strapi's dynamic zones, pricing, FAQ, contact, a blog and products, in English and French, every Strapi read a \"use cache\" entry, with draft mode — runs as one Cloudflare Worker with Static Assets, its data cache in R2 and its tag cache and revalidation queue in Durable Objects, live on the template's own seed before a Strapi project is connected, and becomes an Orun baseline that takes a new site from nothing to live on stage and prod in one landing." - state: started + state: completed milestones: - name: "SL0 — 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..0903bd0 --- /dev/null +++ b/testing/coverage.test.sh @@ -0,0 +1,264 @@ +#!/usr/bin/env bash +# EVERY COMPONENT THIS REPO SHIPS IS PLACED BY EXACTLY ONE PHASE +# (saas-bootstrap-engine BE5, Tier 0). +# +# `repo-blueprint.yaml` decides what a product is made of. A component that no +# module names is not a component a product gets — and nothing would say so. +# The failure is quiet and late: the fork builds, its CI goes green, and the +# missing piece surfaces when somebody looks for a worker that was never +# copied. +# +# orun already enforces the other half — every MODULE belongs to exactly one +# phase, and a module naming an unknown module is a parse error. What it cannot +# know is what this repository contains, because a blueprint declares what to +# place and not what exists. That is this file's job. +# +# bash + python3 + PyYAML. No network, no orun, no credential. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +echo "── every component against the blueprint that places it" +python3 - "$root" <<'PY' +import pathlib, sys + +try: + import yaml +except ImportError: + sys.exit("PyYAML is required for the coverage gate (pip install pyyaml)") + +root = pathlib.Path(sys.argv[1]) +problems = [] +def bad(m): problems.append(m) + +# A component directory this repository deliberately keeps to itself. Declared +# with its reason rather than skipped by a pattern: "tests/*" would also hide +# the test suite a product genuinely needs, and the next +# baseline-only directory should have to be argued for in a diff. +# EMPTY: every component here is a product's. The baseline's own suites live in +# `testing/`, which is not a component at all and so is not one this gate can +# miss. The map stays so that the next baseline-only directory has to be +# argued for in a diff; the check below refuses an exemption whose directory is +# absent, so a stale entry cannot linger. +BASELINE_ONLY: dict[str, str] = {} + +bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text()) + +# Where each module takes its content from, and which phase places it. +placed_by = {} +for m in bp.get("modules") or []: + src = (m.get("from") or "").rstrip("/") + if src: + placed_by.setdefault(src, []).append(m["name"]) +phase_of = {n: ph["name"] for ph in (bp.get("phases") or []) for n in ph["modules"]} + +components = sorted( + p.parent.relative_to(root).as_posix() + for p in root.rglob("component.yaml") + if "node_modules" not in p.parts and ".git" not in p.parts +) +if not components: + sys.exit("no component.yaml anywhere — this check has gone blind") + +for comp in components: + modules = placed_by.get(comp, []) + reason = BASELINE_ONLY.get(comp) + + if reason and modules: + bad(f"{comp} is declared baseline-only ({reason}) and yet {modules[0]} " + f"places it — one of the two is wrong") + continue + if reason: + continue + if not modules: + bad(f"{comp} is a component and no module places it. Either add one, or " + f"declare it baseline-only in this file with the reason.") + continue + if len(modules) > 1: + bad(f"{comp} is placed by {len(modules)} modules ({', '.join(modules)}) " + f"— a component comes from one place") + continue + if modules[0] not in phase_of: + bad(f"{comp} is placed by {modules[0]}, which is in no phase") + +# The other direction: a module naming a path this repo does not have places +# nothing, silently. orun resolves `from` against the source tree and an absent +# path is an empty module, not an error. +for src, modules in sorted(placed_by.items()): + if not (root / src).exists(): + bad(f"module {modules[0]} takes its content from {src}, which does not " + f"exist — it would place nothing, and say nothing") + +# A directory named baseline-only must actually BE one, or the exemption is +# protecting nothing and will outlive the thing it was written for. +for comp in BASELINE_ONLY: + if not (root / comp).exists(): + bad(f"{comp} is declared baseline-only and does not exist — drop the entry") + +# ── WHAT THE CATALOG SEES OF EACH COMPONENT ─────────────────────────────── +# +# Every component ships its generated pages (overview, architecture, runbook) +# and must ATTACH them in `spec.docs`: a `docs/` folder no manifest declares is +# never attached, so a fresh product's Docs library showed nothing for any +# component and the catalog failed every one of them on docs and on runbook. +# A component also needs a description: it is the catalog's one-line answer to +# "what is this", and the test suite had none. +# +# And a domain may not share a component's name. The catalog keys entities by +# name, so the `web` domain (`spec.domain: web`) took the `web` component's +# place, and the product's one deployable was missing from its own catalog. +WANT_DOCS = {"overview": "docs/overview.md", "architecture": "docs/architecture.md", "runbook": "docs/runbook.md"} +names, domains = {}, {} +for comp in components: + if comp in BASELINE_ONLY: + continue + doc = yaml.safe_load((root / comp / "component.yaml").read_text()) or {} + meta, spec = doc.get("metadata") or {}, doc.get("spec") or {} + names[meta.get("name")] = comp + for domain in (spec.get("domain"), (meta.get("labels") or {}).get("domain")): + if domain: + domains.setdefault(domain, comp) + if not (meta.get("description") or "").strip(): + bad(f"{comp}/component.yaml has no metadata.description — the catalog shows the component with nothing to say") + docs = spec.get("docs") or {} + got = {"overview": docs.get("overview")} + for page in docs.get("pages") or []: + got[page.get("role")] = page.get("path") + for role, path in WANT_DOCS.items(): + if got.get(role) != path: + bad(f"{comp}/component.yaml does not attach {path} as its {role} " + f"(spec.docs) — the page ships and the catalog never sees it") + elif not (root / comp / path).is_file(): + bad(f"{comp}/component.yaml attaches {path}, which does not exist") +for domain, comp in sorted(domains.items()): + if domain in names: + bad(f"{comp} declares domain `{domain}`, which is also the name of the " + f"component in {names[domain]} — the catalog keeps one of the two") + +# ── WHAT `ignore` ACTUALLY EXCLUDES (BE6) ────────────────────────────────── +# +# orun matches an ignore entry two ways, and WHICH ONE depends on the entry: +# a pattern containing no glob metacharacter is compared against each path +# SEGMENT, and only a pattern containing one is compared against the whole +# relative path. So `apps/admin-worker/wrangler.jsonc` matches nothing at all — +# no segment is ever equal to it — and the entry is INERT while reading exactly +# like a rule. +# +# That was not hypothetical. Twelve such entries were inert in this file's own +# blueprint, and a canary written to `apps/admin-worker/wrangler.jsonc` was +# placed straight into a product — which is the leak their comment says they +# exist to prevent. An `ignore` list that silently does nothing is worse than +# no list, because the comment above it reads as a defence. +for entry in bp.get("ignore") or []: + if "/" in entry and not any(c in entry for c in "*?["): + bad(f'ignore entry "{entry}" names a path and has no glob character, so orun ' + f'matches it against path SEGMENTS and it excludes nothing. Write it as ' + f'"**/{entry}".') + +# A workflow that runs the FACTORY must not ship to the factory's products. +# `github-workflows` copies the whole `.github` directory, so a lane added for +# this repository travels to every product built from it — and one that reads a +# path under `testing/` cannot work there, because `testing/` is not placed. +# A nightly lane did exactly this once: shipped, on a cron, reading an intent +# file no product has. +ignored = set(bp.get("ignore") or []) +workflows = sorted((root / ".github" / "workflows").glob("*.y*ml")) +for wf in workflows: + text = wf.read_text(encoding="utf-8") + if "testing/" not in text: + continue + rel = f".github/workflows/{wf.name}" + if f"**/{rel}" not in ignored and rel not in ignored: + bad(f"{rel} reads a path under testing/, which no product is placed with, " + f"and is not in the blueprint's ignore list — so it ships into every " + f'product and fails there. Add "**/{rel}" to ignore.') + +# ONE WORKFLOW ON A PUSH TO MAIN, in what a product carries. The bootstrap +# watches each phase's convergence with `orun.run/watch@v1` and `sha:`, which +# takes the newest workflow run for the merge commit — from any workflow. A +# second one on push (the Checks workflow this baseline once shipped 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..d533e5b --- /dev/null +++ b/testing/e2e.test.sh @@ -0,0 +1,287 @@ +#!/usr/bin/env bash +# TIER 2 — the product 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 01-product landing (the commit its one pull request merges), +# install with the lockfile the product ships, render the wrangler +# fixture and check the committed config IS that render, typecheck, +# lint, test, build. The landing's own PR runs `plan` alone (an +# `orun/BASE-*` branch), so THIS is where a product 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 product for +# a pull request (the verify profile: the deploy profile has no dry run) +# — `verify-app-structure` (which checks the wrangler config exists +# BEFORE anything is built), `build-app` (the component's buildCommand: +# the live wiring render, then the build), `verify-build-output` and +# `deploy-dry-run` (`wrangler deploy --dry-run --name -web-stage`). +# They run IN THE TREE THE RUNNER STAGES for the job +# (testing/lib/stage-job.py), with the dependency layout the pinned +# composition produces, and with the stage wiring document in the job's +# environment as the platform resolves it (the component's secretEnv) — +# so the bucket name in the built config is asserted to be the +# document's, not the fixture's; +# 3. serve the built Worker with `wrangler dev` (a local R2 bucket and local +# Durable Objects) and run the component's OWN `smokeCommand` against it, +# verbatim — the check the real deploy ends with — and then do what a +# visitor does on a fresh deploy with NO Strapi project: `/` redirects by +# Accept-Language; every page renders from the bundled sample (the +# template's own seed) under the product's name, with the bar that says +# how to connect Strapi; the seed's redirects redirect; a missing page is +# Next's noindex not-found page; `/api/health` says `sample`; preview is refused; +# 4. CONNECT A PROJECT, as the owner does: the same lane's build again, with +# the environment's `STRAPI_URL` secret resolved (the component's +# optionalSecretEnv) to a stand-in Strapi (testing/lib/fake-strapi.py — +# Strapi's REST answers for the same seed, offline) and the preview +# secret as a Worker secret; then browse every page and prove the cache: +# a second visit reads Strapi not at all and a change in Strapi stays +# cached; draft mode, entered only with the preview secret, reads the +# draft from Strapi on every request. +# +# What it cannot do is the platform's half: create the repository, mint the +# brokered Cloudflare tokens, apply the bucket, deploy for real and probe +# workers.dev — or reach a real Strapi project: the stand-in answers the +# reads the site makes from the seed's documents. The R2 root is verified to +# `terraform validate` and its plan is part of every pull request's lanes; +# the apply needs an account. +# +# Needs: orun, node, pnpm, python3 (+PyYAML), git, curl, and the network for +# `pnpm install` (or a warm store). Several minutes: two installs and three +# builds of the site. +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="" +fake_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. +cleanup() { + 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 + fi + [ -z "$fake_pid" ] || kill -TERM -- "-$fake_pid" 2>/dev/null || true + 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 NEXT_TELEMETRY_DISABLED=1 TURBO_TELEMETRY_DISABLED=1 + +# The landing's own checks, step for step — the ones the product's retired +# Checks workflow ran, run here at once on the whole tree. A product's pull +# requests verify through ci.yml's lanes (the site built — Next's build +# type-checks it — and dry-deployed per environment, the R2 root planned), +# which neither lint nor run the tests, so before a tag THIS is where those +# are held. +LANDING_CHECKS=( + "pnpm install --frozen-lockfile" + "pnpm run wire:fixture" + "git diff --exit-code" + "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" +s01="$(git -C "$tree" rev-parse HEAD~1)" + +# ── 1. the product's one pull request ────────────────────────────────────── +echo "── 01-product's landing: install, the fixture render, typecheck, lint, test, build" +git -C "$tree" worktree add -q "$scratch/at-01" "$s01" +checks "$scratch/at-01" "$scratch/checks-01.log" +# The landing's build is done; its tree is not needed again, and the disk is shared. +git -C "$tree" worktree remove --force "$scratch/at-01" + +# ── 2. the stage lane's steps, in the job's own tree ────────────────────── +echo "── the stage lane: verify-app-structure, build-app, verify-build-output, deploy-dry-run" +# A pull request that changes the page: the lane `orun plan` gives it. +git -C "$tree" checkout -q -b e2e-pr +echo "" >> "$tree/apps/web/README.md" +git -C "$tree" -c user.email=e2e@example.invalid -c user.name=e2e commit -qam "a pull request" +(cd "$tree" && orun plan --intent intent.yaml --trigger github-pull-request --changed \ + --base main --head HEAD --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 ("verify-app-structure", "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") +(out / "secrets").write_text("\n".join(r["asEnv"] for r in job.get("secretRefs") or [])) +PY +# The job's private tree, staged as orun stages it. The source checkout +# carries no build output (nothing was built in it), and its dependencies are +# what the pinned composition says: a lane-scoped install ran once in the +# source tree and is linked in, or the job installs its own. +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 + (cd "$tree" && 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; } + 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 +[ ! -e "$work/apps/web/.open-next" ] || { echo "FAIL: the staged tree carries build output" >&2; exit 1; } +# What the platform resolves into the job before its first step: the wiring +# documents the R2 root lease-published (the component's secretEnv), shaped as +# its `wiring` output — `{r2_bucket_name}`. Names no fixture carries, so the +# built config proves which one it was rendered from. +for env in stage prod; do + key="WIRING_CLOUDFLARE_R2_$(echo "$env" | tr a-z A-Z)" + grep -qx "$key" "$scratch/steps/secrets" || { echo "FAIL: the stage lane does not resolve $key" >&2; exit 1; } +done +export WIRING_CLOUDFLARE_R2_STAGE='{"r2_bucket_name":"stg-'"$repo"'-stage-applied"}' +export WIRING_CLOUDFLARE_R2_PROD='{"r2_bucket_name":"prod-'"$repo"'-prod-applied"}' +for step in verify-app-structure 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:`), its resolved secrets, 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; } && \ + export ORUN_ENVIRONMENT=stage && 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 -q "\"stg-$repo-stage-applied\"" "$work/apps/web/wrangler.jsonc" \ + || { echo "FAIL: the lane's build did not render the stage bucket name from its wiring document" >&2; exit 1; } +grep -q 'NEXT_INC_CACHE_R2_BUCKET' "$scratch/deploy-dry-run.log" && grep -q "stg-$repo-stage-applied" "$scratch/deploy-dry-run.log" \ + || { echo "FAIL: the dry run does not bind NEXT_INC_CACHE_R2_BUCKET to the stage bucket" >&2; tail -20 "$scratch/deploy-dry-run.log" >&2; exit 1; } +grep -q 'NEXT_TAG_CACHE_DO_SHARDED' "$scratch/deploy-dry-run.log" && grep -q "WORKER_SELF_REFERENCE" "$scratch/deploy-dry-run.log" \ + || { echo "FAIL: the dry run lost the Durable Object or self-reference bindings" >&2; tail -20 "$scratch/deploy-dry-run.log" >&2; exit 1; } +echo " the built config binds NEXT_INC_CACHE_R2_BUCKET to the stage document's bucket; the dry run accepts it" +# The Strapi project is the owner's, after the build: the lane names its URL +# as an OPTIONAL secret, so a fresh product's build — this one — has none. +python3 - "$scratch/plan.json" "$repo" <<'PY' || exit 1 +import json, sys +plan, repo = json.load(open(sys.argv[1])), sys.argv[2] +job = next(j for j in plan["jobs"] if j["component"] == "web" and j["environment"] == "stage") +refs = {r["asEnv"]: r for r in job.get("secretRefs") or []} +for env_key, key in (("STRAPI_URL", "STRAPI_URL"),): + r = refs.get(env_key) + if not r or not str(r.get("ref", r.get("uri", ""))).endswith(f"/{repo}/stage/{key}"): + sys.exit(f"FAIL: the stage lane does not resolve {env_key} from the product's {key} secret: {r}") + if not r.get("optional"): + sys.exit(f"FAIL: the stage lane requires {key}; a fresh product has no Strapi project yet") +print(" the lane resolves STRAPI_URL as an optional build secret — none on a fresh product") +PY +# The origin this lane's build is for: what its metadataBase resolves the +# relative Open Graph images against. +sub="$(python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['subdomain'])" "$values")" +site_origin="https://$repo-web-stage.$sub.workers.dev" + + +# ── 3. serve it as born, and smoke it as the deploy does ─────────────────── +serve() { # PERSIST-DIR → url; serves the staged tree's built Worker + local port + port=$(python3 -c "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print(s.getsockname()[1]);s.close()") + (cd "$work/apps/web" && exec setsid pnpm exec wrangler dev --config wrangler.jsonc --ip 127.0.0.1 --port "$port" \ + --name "$repo-web-stage" --persist-to "$1" --show-interactive-dev-session=false) > "$scratch/dev.log" 2>&1 < /dev/null & + dev_pid=$! + url="http://127.0.0.1:$port" + for _ in $(seq 1 120); do + curl -s -o /dev/null "$url/api/health" && return 0 + kill -0 "$dev_pid" 2>/dev/null || { echo "FAIL: wrangler dev exited" >&2; tail -30 "$scratch/dev.log" >&2; exit 1; } + sleep 1 + done + echo "FAIL: wrangler dev never answered" >&2; tail -30 "$scratch/dev.log" >&2; exit 1 +} +stop_serving() { + [ -n "$dev_pid" ] || return 0 + 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="" +} + +echo "── wrangler dev over the built Worker, as born (no Strapi project)" +serve "$scratch/state-born" +echo " ▸ the component's own smokeCommand, DEPLOYED_URL=$url" +smoke="$(python3 -c "import yaml,sys;print(yaml.safe_load(open(sys.argv[1]))['spec']['parameters']['smokeCommand'])" "$tree/apps/web/component.yaml")" +DEPLOYED_URL="$url" bash -c "$smoke" || { echo "FAIL: the deploy's smoke refused the site" >&2; exit 1; } + +echo " ▸ a visitor on a fresh deploy: the sample content, asked to connect Strapi, never a 500" +E2E_SAMPLE="$work/apps/web/sample/strapi" python3 "$here/lib/e2e-visit.py" born "$url" "$values" "$site_origin" || exit 1 +stop_serving + +# ── 4. connect a project: the owner's secrets, the lane's build again ───── +echo "── connecting a Strapi project: the stand-in API, STRAPI_URL for stage, the lane's build again" +api_port=$(python3 -c "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print(s.getsockname()[1]);s.close()") +(exec setsid python3 "$here/lib/fake-strapi.py" --sample "$work/apps/web/sample/strapi" \ + --uploads "$work/apps/web/public/uploads" --port "$api_port") > "$scratch/fake-strapi.log" 2>&1 < /dev/null & +fake_pid=$! +api="http://127.0.0.1:$api_port" +for _ in $(seq 1 30); do curl -s -o /dev/null "$api/__calls" && break; sleep 0.5; done +curl -s -o /dev/null "$api/__calls" || { echo "FAIL: the stand-in Strapi never answered" >&2; cat "$scratch/fake-strapi.log" >&2; exit 1; } +# What the platform resolves into the job once the owner has set the +# environment's STRAPI_URL (the component's optionalSecretEnv). +for step in build-app verify-build-output; do + echo " ▸ $step" + if ! (cd "$work/$(cat "$scratch/steps/path")" && \ + { [ -f "$scratch/steps/env" ] && source "$scratch/steps/env"; true; } && \ + export ORUN_ENVIRONMENT=stage STRAPI_URL="$api" && \ + bash -e "$scratch/steps/$step.sh") > "$scratch/$step-connected.log" 2>&1; then + echo "FAIL: the lane's $step with Strapi connected" >&2; tail -40 "$scratch/$step-connected.log" >&2; exit 1 + fi +done +python3 -c "import json,sys;r=json.load(open(sys.argv[1]));sys.exit(0 if r.get('api',0)>0 else 1)" \ + <(curl -s "$api/__calls") || { echo "FAIL: the connected build read nothing from Strapi (its redirections)" >&2; exit 1; } +grep -rqF "$api" "$work/apps/web/.open-next/server-functions" \ + || { echo "FAIL: the connected build did not inline the project's URL" >&2; exit 1; } +# The preview secret is a Worker secret the owner puts on the Worker; +# wrangler dev reads it from .dev.vars beside the config. +preview="e2e-preview-secret-0123456789abcdef" +printf 'PREVIEW_SECRET=%s\n' "$preview" > "$work/apps/web/.dev.vars" +serve "$scratch/state-connected" +DEPLOYED_URL="$url" bash -c "$smoke" || { echo "FAIL: the deploy's smoke refused the connected site" >&2; exit 1; } +echo " ▸ a visitor: every page from Strapi; the cache reused; draft mode past it" +E2E_API="$api" E2E_PREVIEW_SECRET="$preview" E2E_SAMPLE="$work/apps/web/sample/strapi" \ + python3 "$here/lib/e2e-visit.py" connected "$url" "$values" "$site_origin" || exit 1 +stop_serving + +echo "e2e.test.sh: ok" diff --git a/testing/fixtures/acme.json b/testing/fixtures/acme.json new file mode 100644 index 0000000..c4018ac --- /dev/null +++ b/testing/fixtures/acme.json @@ -0,0 +1,25 @@ +{ + "_comment": [ + "The inputs the placement, leak and e2e 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 TypeScript", + "strings and HTML), a hyphenated repo slug that CONTAINS this baseline's", + "own slug (`strapi-launchpad`, which the rename must not chase twice),", + "an owner other than the baseline's, and NO domain — a console build asks", + "for none, so the placeholder .example.com is what a site is", + "born with (here `acme-strapi-launchpad.example.com`, which ENDS in the baseline's", + "own placeholder domain) — 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-strapi-launchpad", + "productname": "Sam's Tees & Mugs", + "githuborg": "acme-inc", + "subdomain": "acme", + "orunWorkspace": "ws_0000000000000000000000000000000f", + "epicSlug": "strapi-launchpad-baselining" +} diff --git a/testing/fixtures/baseline-identity.strapi-launchpad.json b/testing/fixtures/baseline-identity.strapi-launchpad.json new file mode 100644 index 0000000..286cb80 --- /dev/null +++ b/testing/fixtures/baseline-identity.strapi-launchpad.json @@ -0,0 +1,9 @@ +{ + "_comment": "THE IDENTITY testing/rebrand.test.sh PINS ITS FIXTURES TO. That suite tests the rename ENGINE, and its fixtures spell this baseline's identity out literally; passed as --baseline-identity, a later change to .baseline/identity.json (a baseline promoted under a new name) cannot silently turn every case into a comparison against the wrong FROM side.", + "slug": "strapi-launchpad", + "pascal": "StrapiLaunchpad", + "productName": "LaunchPad", + "domain": "strapi-launchpad.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..9b90821 --- /dev/null +++ b/testing/leak.test.sh @@ -0,0 +1,235 @@ +#!/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 site, its R2 root, its tests, 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 — and no file it does get may so much +# as NAME one of those paths, because in the product they do not exist. +# +# This asks orun to DERIVE the placement — every file every phase would write +# — and gates that set and the sources it is copied from. 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" + +# intent.yaml's `work:` block names this repository's epic and task tree; the +# product's copy has it stripped by a 01-product hook before it lands, so the +# source is gated as the product receives it. +cp "$root/intent.yaml" "$scratch/intent.yaml" +node "$root/tooling/bootstrap/work-tree.mjs" --strip --file "$scratch/intent.yaml" >/dev/null + +python3 - "$scratch/status.json" "$root" "$scratch/intent.yaml" <<'PY' +import json, pathlib, re, sys +import yaml + +status = json.load(open(sys.argv[1])) +root = pathlib.Path(sys.argv[2]) +stripped_intent = pathlib.Path(sys.argv[3]) +problems = [] +def bad(m): problems.append(m) + +# Against an empty output directory every file a phase places is "missing", so +# the union of those lists IS the 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/", ".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)?|\.env\.configurator\.local|\.dev\.vars(\..*)?|" + r"node_modules|\.next|\.open-next|\.wrangler|\.turbo|\.orun|\.terraform|next-env\.d\.ts|" + r"[^/]*\.tsbuildinfo|[^/]*\.tfstate(\.backup)?|\.terraform\.lock\.hcl)(/|$)") +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/lib/site.ts", "tests/web/component.yaml", + ".rebrand/values.json", "apps/web/.env.example", "packages/.gitkeep", + # the wiring path: the template, its fixture, the committed render + # the deploy lane checks for, and the renderer the build calls + "apps/web/wrangler.template.jsonc", "apps/web/wiring.fixture.json", + "apps/web/wrangler.jsonc", "tooling/wire/live.mjs", "tooling/wire/render.mjs", + # the R2 root the site binds + "infra/terraform/cloudflare-r2/component.yaml", + "infra/terraform/cloudflare-r2/terraform/main.tf", + "infra/terraform/cloudflare-r2/terraform/adopt.tf", + # the Next.js cache on Workers, and the config that inlines the + # Strapi URL and sets the redirects + "apps/web/open-next.config.ts", "apps/web/next.config.ts", + # a site with no Strapi project connected: the client's switch, the + # sample it reads (the template's own seed) and an image it shows, + # the redirects the seed carries, the bar that says how to connect + # one, the locale redirect, and the deploy's health probe + "apps/web/lib/strapi/client.ts", "apps/web/lib/strapi/sample.ts", + "apps/web/lib/strapi/sample-redirections.ts", + "apps/web/sample/strapi/global.en.json", "apps/web/sample/strapi/pages.fr.json", + "apps/web/public/uploads/logo_6a13c79c4b.png", "apps/web/components/banner.tsx", + "apps/web/proxy.ts", "apps/web/app/api/health/route.ts", + # Strapi's preview (draft mode), and the template's licence (MIT) + "apps/web/app/api/preview/route.ts", "apps/web/LICENSE.md"): + if must not in placed: + bad(f"{must} would not ship, and a site needs it") + +# ── no shipped file names the factory ───────────────────────────────────── +# Read from the SOURCE each placed file is copied from (the module's `from`). +# A product's file that points a reader at `testing/` or `repo-blueprint.yaml` +# points at nothing: those paths do not exist in the product. +FACTORY = re.compile(r"repo-blueprint|BOOTSTRAP\.md|(? [until-phase] +# +# What stands in for the platform: +# - the typed actions (`uses:` — task, repo, reconcile, land, watch, probe) +# are skipped; a landing becomes a commit on `main`, which is what the +# next phase's placement sees on the real thing too; +# - `link` (a `run:` hook that calls `orun cloud`) is skipped — it needs a +# workspace; +# - `{{ .inputs.* }}` render from the fixture. +# Everything else — the 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 + + 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/e2e-visit.py b/testing/lib/e2e-visit.py new file mode 100644 index 0000000..a0f2fdf --- /dev/null +++ b/testing/lib/e2e-visit.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python3 +"""What a visitor does to the served Worker — testing/e2e.test.sh's stages 3 and 4. + + e2e-visit.py born + e2e-visit.py connected (E2E_API, E2E_PREVIEW_SECRET) + +`born` is a fresh product, no Strapi project: `/` redirects to the visitor's +locale; every page renders from the bundled sample (the template's own seed) +under the product's name, with the bar that says how to connect Strapi; the +seed's redirects redirect; a page that does not exist is a 404; the images +are the Worker's own; `/api/health` says `sample`; preview is refused. + +`connected` is the same product built with the stand-in Strapi +(testing/lib/fake-strapi.py) as its project: the pages render from it and the +bar is gone; a second visit reads Strapi not at all (every read is a +`"use cache"` entry in the local R2 bucket), and a change in Strapi stays +cached; draft mode — entered only with the preview secret — reads the draft +from Strapi on every request, past the cache. +""" +import html +import json +import os +import re +import sys +import urllib.error +import urllib.request + +mode, base, values, origin = sys.argv[1], sys.argv[2], json.load(open(sys.argv[3])), sys.argv[4] +name = values["productname"] +SAMPLE = os.environ.get("E2E_SAMPLE") or os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..", "..", "apps", "web", "sample", "strapi") +problems = [] + + +def bad(m): + problems.append(m) + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *a, **k): + return None + + +opener = urllib.request.build_opener(NoRedirect) + + +def request(url, data=None, headers=None, method=None): + req = urllib.request.Request(url, data=data, headers=dict(headers or {}), method=method) + try: + r = opener.open(req, timeout=90) + except urllib.error.HTTPError as e: + r = e + return r.status, r.headers, r.read() + + +def get(path, headers=None): + s, h, b = request(base + path, headers=headers) + return s, h, b.decode("utf-8", "replace") + + +def text_of(page): + """The page's text as a visitor reads it: scripts, comments (React's text + separators) and tags dropped, entities decoded, whitespace collapsed.""" + page = re.sub(r"", " ", page, flags=re.S) + page = re.sub(r"", "", page, flags=re.S) + return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", page))) + + +def title_of(page): + """The document's title — not an inline SVG icon's own .""" + page = re.sub(r"<svg\b.*?</svg>", "", page, flags=re.S) + m = re.search(r"<title>(.*?)", page, re.S) + return html.unescape(m.group(1)) if m else None + + +def logo_name(page): + m = re.search(r'(.*?)', page, re.S) + return html.unescape(m.group(1)) if m else None + + +def og_image(page): + m = re.search(r''") + s, _, fr = get("/fr") + fr_hero = home_of("fr")["dynamic_zone"][0].get("heading") + if fr_hero and fr_hero not in text_of(fr): + bad(f"/fr does not show the French sample's hero heading {fr_hero!r}") + s, _, plist = get("/en/products") + for p in products: + if p["name"] not in text_of(plist): + bad(f"/en/products does not list the sample product {p['name']!r}") + s, h, _ = get("/en/i-have-a-question") + if s not in (307, 308) or not (h.get("Location") or "").endswith("/en/faq"): + bad(f"the seed's redirect /i-have-a-question answered {s} → {h.get('Location')!r}, not /en/faq") + # A slug with no page is Next's not-found page, marked noindex. Its status + # is 200: the template's loading boundary has streamed the shell before the + # page can call notFound(), and Next answers a late notFound() that way. + s, _, missing = get("/en/no-such-page") + if s not in (200, 404) or "NEXT_HTTP_ERROR_FALLBACK;404" not in missing \ + or "could not be found" not in missing \ + or not re.search(r' --uploads --port N + +It answers the REST reads the site makes through @strapi/client, from the +same documents the site ships as its sample (the template's seed, as a real +Strapi returned it): `GET /api/?locale=xx` and +`GET /api/?…filters[slug][$eq]=…&locale=xx`, published or draft, +and `GET /api/redirections` (not localized), which the build reads. +A draft read (`status=draft`) answers the same documents with every +`metaTitle` prefixed `[draft] `, so a test can tell which one the site asked +for. Media under `/uploads/` are served from the site's own copies. + +Control endpoints, for the test only: + GET /__calls {"api": N, "draft": N} reads answered so far + POST /__set {"type": "pages", "locale": "en", "slug": "homepage", + "path": ["seo", "metaTitle"], "value": "…"} + changes one field of one document (or of a single + type, without "slug") from now on +""" +import argparse +import copy +import json +import os +import re +import urllib.parse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +ap = argparse.ArgumentParser() +ap.add_argument("--sample", required=True) +ap.add_argument("--uploads", required=True) +ap.add_argument("--port", type=int, required=True) +args = ap.parse_args() + +DOCS = {} +for f in os.listdir(args.sample): + m = re.fullmatch(r"(.+)\.([a-z]{2})\.json", f) + if m: + DOCS.setdefault(m.group(1), {})[m.group(2)] = json.load(open(os.path.join(args.sample, f))) + elif f.endswith(".json"): + # A collection with no locale (`redirections`): the same documents in every locale. + DOCS[f[:-5]] = {"*": json.load(open(os.path.join(args.sample, f)))} +CALLS = {"api": 0, "draft": 0} + + +def bracket_params(query): + """`filters[slug][$eq]=x&locale=en` → {"filters": {"slug": {"$eq": "x"}}, "locale": "en"}.""" + out = {} + for key, values in urllib.parse.parse_qs(query, keep_blank_values=True).items(): + parts = [key.split("[", 1)[0]] + re.findall(r"\[([^\]]*)\]", key) + node = out + for p in parts[:-1]: + node = node.setdefault(p, {}) + node[parts[-1]] = values[-1] + return out + + +def value_of(v): + return v.get("$eq") if isinstance(v, dict) else v + + +def drafted(doc): + doc = copy.deepcopy(doc) + + def walk(o): + if isinstance(o, dict): + for k, v in o.items(): + if k == "metaTitle" and isinstance(v, str): + o[k] = "[draft] " + v + else: + walk(v) + elif isinstance(o, list): + for x in o: + walk(x) + + walk(doc) + return doc + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def send(self, status, body, ctype="application/json"): + data = body if isinstance(body, bytes) else json.dumps(body).encode() + self.send_response(status) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + url = urllib.parse.urlsplit(self.path) + if url.path == "/__calls": + return self.send(200, CALLS) + if url.path.startswith("/uploads/"): + p = os.path.join(args.uploads, os.path.basename(url.path)) + if not os.path.isfile(p): + return self.send(404, {"error": "not found"}) + ext = p.rsplit(".", 1)[-1].lower() + ctype = {"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "svg": "image/svg+xml", + "webp": "image/webp"}.get(ext, "application/octet-stream") + return self.send(200, open(p, "rb").read(), ctype) + m = re.fullmatch(r"/api/([a-z-]+)", url.path) + if not m or m.group(1) not in DOCS: + return self.send(404, {"data": None, "error": {"status": 404, "name": "NotFoundError"}}) + q = bracket_params(url.query) + filters = q.get("filters") or {} + locale = q.get("locale") or value_of(filters.get("locale")) or "en" + draft = q.get("status") == "draft" + CALLS["api"] += 1 + CALLS["draft"] += 1 if draft else 0 + docs = DOCS[m.group(1)].get(locale, DOCS[m.group(1)].get("*")) + if isinstance(docs, list): + slug = value_of(filters.get("slug")) + data = [d for d in docs if slug is None or d.get("slug") == slug] + data = [drafted(d) for d in data] if draft else data + meta = {"pagination": {"page": 1, "pageSize": 25, "pageCount": 1, "total": len(data)}} + return self.send(200, {"data": data, "meta": meta}) + if docs is None: + return self.send(404, {"data": None, "error": {"status": 404, "name": "NotFoundError"}}) + return self.send(200, {"data": drafted(docs) if draft else docs, "meta": {}}) + + def do_POST(self): + if self.path != "/__set": + return self.send(404, {}) + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}") + docs = DOCS[body["type"]][body["locale"]] + doc = next(d for d in docs if d.get("slug") == body["slug"]) if isinstance(docs, list) else docs + node = doc + for k in body["path"][:-1]: + node = node[k] + node[body["path"][-1]] = body["value"] + return self.send(200, {"ok": True}) + + +ThreadingHTTPServer(("127.0.0.1", args.port), Handler).serve_forever() 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 [--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. }}` — and anything else left between braces is an error, so +a hook that starts using a template this cannot render fails loudly rather +than running with a literal `{{ … }}` in its argv. + +`uses:` hooks are the platform's typed actions (task, repo, land, watch, +probe, reconcile). They need a workspace and the network, and are reported as +skipped; the caller stands in for the ones whose effect the tree needs (a +landing is a commit). +""" +import json +import pathlib +import re +import subprocess +import sys + +import yaml + + +def main() -> int: + args = sys.argv[1:] + skip = set() + if "--skip" in args: + i = args.index("--skip") + skip = {s for s in args[i + 1].split(",") if s} + args = args[:i] + args[i + 2:] + blueprint, phase_name, slot, tree, baseline_dir, values_path = args + bp = yaml.safe_load(pathlib.Path(blueprint).read_text()) + phase = next((p for p in bp.get("phases") or [] if p.get("name") == phase_name), None) + if phase is None: + print(f"run-hooks: no phase {phase_name!r}", file=sys.stderr) + return 2 + inputs = {k: v for k, v in json.loads(pathlib.Path(values_path).read_text()).items() if not k.startswith("_")} + + def render(arg: str) -> str: + out = arg.replace("{{ .baseline.dir }}", baseline_dir).replace("{{ .phase.name }}", phase_name) + out = re.sub(r"\{\{ \.inputs\.([A-Za-z0-9_]+) \}\}", lambda m: str(inputs.get(m.group(1), "")), out) + if "{{" in out: + raise SystemExit(f"run-hooks: cannot render {arg!r} — a template this harness does not know") + return out + + for hook in ((phase.get("hooks") or {}).get(slot) or []): + hid = hook.get("id") + if "uses" in hook: + print(f" · {phase_name}/{slot}/{hid}: {hook['uses']} (platform action — skipped offline)") + continue + if hid in skip: + print(f" · {phase_name}/{slot}/{hid}: skipped by the caller") + continue + argv = [render(a) for a in hook.get("run") or []] + print(f" ▸ {phase_name}/{slot}/{hid}") + r = subprocess.run(argv, cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + for line in (r.stdout or "").splitlines()[-6:]: + print(f" {line}") + if r.returncode != 0: + print(f"run-hooks: {phase_name}/{slot}/{hid} exited {r.returncode}", file=sys.stderr) + print(r.stdout, file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/testing/lib/stage-job.py b/testing/lib/stage-job.py new file mode 100755 index 0000000..1f80c10 --- /dev/null +++ b/testing/lib/stage-job.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Stage a job's private tree the way orun's runner does. + + stage-job.py [--shared-deps] + +orun runs every job of a run in an isolated copy of the source checkout, +`.orun/runs///work` (orun internal/runner/workspace.go, +`materializeTree`). What it does with installed dependencies depends on the +composition the component's lane runs: + + default the job installs them itself, so `node_modules` is left out + at every level and the job's install step recreates it + INSIDE the work tree (stack-tectonic < 0.20.0, or a + composition with no lane-scoped install); + --shared-deps a `scope: lane` install ran once in the source checkout + (stack-tectonic >= 0.20.0, orun >= 2.78.2): the TOP-LEVEL + `node_modules` is a SYMLINK to the source tree's, and every + nested one is COPIED with its pnpm symlinks intact — so they + resolve up through that link, OUT of the work tree. + +Either way `.git` and `.orun` are left out, and so are build outputs and +caches (.next, .nuxt, .turbo, .svelte-kit, dist, build, target, .venv, venv, +__pycache__, .terraform, .pytest_cache, .mypy_cache). + +Why a test builds here rather than in a plain checkout: the first live +bootstrap of this baseline died in the --shared-deps layout — Next.js 16's +Turbopack refuses a dependency that resolves outside its project root +("Symlink … points out of the filesystem root") — in a lane that +testing/e2e.test.sh had run green over a plain checkout. +""" +import os +import shutil +import sys + +OUTPUT_DIRS = {".next", ".nuxt", ".turbo", ".svelte-kit", "dist", "build", "target", + ".venv", "venv", "__pycache__", ".terraform", ".pytest_cache", ".mypy_cache"} +SKIP = {".git", ".orun"} + + +def stage(src: str, dst: str, top: bool, shared_deps: bool) -> None: + os.makedirs(dst, exist_ok=True) + for entry in os.scandir(src): + name = entry.name + s, d = entry.path, os.path.join(dst, name) + if name in SKIP: + continue + if entry.is_symlink(): + os.symlink(os.readlink(s), d) + continue + if entry.is_dir(): + if name in OUTPUT_DIRS: + continue + if name == "node_modules": + if not shared_deps: + continue # the job installs its own + if top: + os.symlink(os.path.abspath(s), d) # the lane's one install + else: + shutil.copytree(s, d, symlinks=True) # copied, links intact + continue + stage(s, d, False, shared_deps) + continue + shutil.copy2(s, d) + + +def main() -> int: + args = sys.argv[1:] + shared = "--shared-deps" in args + paths = [a for a in args if a != "--shared-deps"] + if len(paths) != 2: + print("usage: stage-job.py [--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..64f04c8 --- /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 three keys is +# three 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"(/@v)") + + # `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..` 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..420680f --- /dev/null +++ b/testing/phases.test.sh @@ -0,0 +1,411 @@ +#!/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. It is the one-landing shape (cirrus-baseline v22): `01-product` +# places EVERY module and is the one phase that deploys; `02-docs` places +# nothing. The order that used to need separate landings — the R2 bucket +# before the Worker that binds it — is carried by the plan instead, and this +# file checks the edges that carry it: every component that reads a wiring +# document waits, on a merge to main, for the infra component that publishes +# it. Each reader resolves its document in the convergence from the place +# every later run looks, so a green convergence says the document is there — +# no separate check. A module that drifts into another phase, or an edge that +# goes missing, fails at landing time, live, with nothing in this repository +# having looked wrong. +# +# And the shape that keeps a bootstrap fast (orun >= v2.88.0): the run-level +# task set-up runs in the background, each phase finds its task just before +# its landing, each landing checks its commit here (`checks: local`), and the +# convergence watch reads every few seconds. +# +# Adapted from sourceplane/cirrus-baseline's testing/phases.test.sh: the +# narration rules and the hook-only rule are Cirrus's, unchanged. +# +# bash + python3 + PyYAML. No network, no fakes, no credential. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +echo "── repo-blueprint.yaml phases against what the bootstrap runs" +python3 - "$root" <<'PY' +import pathlib, re, sys + +try: + import yaml +except ImportError: + sys.exit("PyYAML is required for the phase contract test (pip install pyyaml)") + +root = pathlib.Path(sys.argv[1]) +problems = [] +def bad(m): problems.append(m) + +bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text()) +phases = bp.get("phases") or [] +if not phases: + sys.exit("repo-blueprint.yaml declares no phases — this check has gone blind") + +PARTITION = { + "01-product": ["ai-deployment", "ai-operations", "cloudflare-r2", "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", "web-tests"], + "02-docs": [], +} +HOOK_ONLY = {"02-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. No phase awaits the +# wiring: the site's deploy resolves it in the convergence (checked below). +PRE = {"01-product": [], "02-docs": []} +POST = { + "01-product": ["retouch", "git-init", "stage", "rebrand", "orun-workspace", "work-tree", + "promotion", "dev-lanes", "restage", "rebrand-verify", + "repo", "link", "secrets", "task", "land"], + "02-docs": ["promotion", "dev-lanes", "render", "task", "land"], +} +AWAIT = {"01-product": ["converge", "verify"], "02-docs": []} + +by_name = {p["name"]: p for p in phases} +names = [p["name"] for p in phases] + +# ── the order IS the execution order ────────────────────────────────────── +if names != sorted(names): + bad(f"phases are not in execution order: {names}. The numbered name IS the " + f"order; a phase out of sequence is a barrier in the wrong place.") +if names != list(PARTITION): + bad(f"phases are {names}; the bootstrap runs {list(PARTITION)}") + +# ── the partition has not drifted ───────────────────────────────────────── +for name, want in PARTITION.items(): + if name not in by_name: + continue + now = sorted(by_name[name].get("modules") or []) + if now != sorted(want): + bad(f"phase {name} no longer places what it placed: gained " + f"{sorted(set(now) - set(want)) or '[]'}, lost {sorted(set(want) - set(now)) or '[]'}") +declared = {m["name"] for m in bp.get("modules") or []} +placed = {m for p in phases for m in (p.get("modules") or [])} +for m in sorted(declared - placed): + bad(f"module {m} is declared and no phase places it") +for 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')})") + +# ── INFRA BEFORE APP: the order the one landing relies on ───────────────── +# Every infra component that lease-publishes a wiring document +# (`secretOutputs: "WIRING_X=wiring"`), and every component that reads one +# (`WIRING_X_` in secretEnv). A reader must wait for its publisher on a +# merge to main — `mode: enforced` — and not on a pull request, which deploys +# nothing (`modeRules` advisory on github-pull-request): a job resolves its +# secrets when it STARTS, so without the edge the first convergence's deploy +# would start before the apply had published the id it binds. +comps = {} +for f in root.rglob("component.yaml"): + if "node_modules" in f.parts: + continue + d = yaml.safe_load(f.read_text()) or {} + comps[(d.get("metadata") or {}).get("name")] = (f.relative_to(root).as_posix(), d.get("spec") or {}) +publishes = {} +for name, (rel, spec) in comps.items(): + outs = str((spec.get("parameters") or {}).get("secretOutputs") or "") + for pair in filter(None, (x.strip() for x in outs.split(","))): + key = pair.split("=", 1)[0] + if key.startswith("WIRING_"): + publishes[key] = name +if not publishes: + bad("no infra component lease-publishes a WIRING_* document — this check has gone blind") +readers = 0 +for name, (rel, spec) in comps.items(): + keys = {re.sub(r"_(DEV|STAGE|PROD)$", "", k) for k in (spec.get("secretEnv") or {}) if k.startswith("WIRING_")} + for key in sorted(keys): + readers += 1 + pub = publishes.get(key) + if not pub: + bad(f"{rel} reads {key}, which no infra component publishes") + continue + edge = next((d for d in spec.get("dependsOn") or [] if d.get("component") == pub), None) + rules = (edge or {}).get("modeRules") or [] + advisory_on_pr = any(r.get("mode") == "advisory" + and ((r.get("when") or {}).get("triggerRef") == "github-pull-request") + for r in rules) + if not edge or edge.get("mode") != "enforced" or not advisory_on_pr: + bad(f"{rel} reads {key} and does not wait for {pub} on a merge to main — declare " + f"dependsOn {pub} with mode: enforced and a modeRules advisory on github-pull-request") + mod = next((m for m in bp.get("modules") or [] if (m.get("from") or "").rstrip("/") == rel.rsplit("/", 1)[0]), None) + pub_mod = next((m["name"] for m in bp.get("modules") or [] + if (m.get("from") or "").rstrip("/") == comps[pub][0].rsplit("/", 1)[0]), None) + if mod and pub_mod and pub_mod not in (mod.get("dependsOn") or []): + bad(f"module {mod['name']} reads {key} and is not placed after {pub_mod} (module dependsOn)") +# …and every document published is one a component in the convergence +# resolves, on stage AND prod, from the place every later run looks (its +# secretEnv: `secret://///WIRING_X`). That read is what +# replaced the `wiring` await: a job resolves its secrets when it starts, +# fail-closed, so a green convergence says every one of them is there. A +# document nothing reads in the convergence would need the await back. +read_from = {} +for name, (rel, spec) in comps.items(): + for env_key, ref in (spec.get("secretEnv") or {}).items(): + m = re.match(r"^secret://[^/]+/[^/]+/(stage|prod)/(WIRING_[A-Z0-9_]+)$", str(ref)) + if m: + read_from.setdefault(m.group(2), set()).add(m.group(1)) +for key in sorted(publishes): + if read_from.get(key, set()) != {"stage", "prod"}: + bad(f"{key} is published and no component resolves it on both stage and prod " + f"(it is read on {sorted(read_from.get(key, set())) or 'none'}) — nothing in the " + f"convergence proves it is there; read it, or await it with orun.secrets/exists@v1") +for p in phases: + for h in hooks_of(p): + if (h.get("uses") or "").startswith("orun.secrets/exists@"): + keys = set((h.get("with") or {}).get("keys") or []) + proven = {k for k in keys if read_from.get(k, set()) >= {"stage", "prod"}} + if proven: + bad(f"phase {p['name']} awaits {sorted(proven)} with orun.secrets/exists@v1, which " + f"the convergence's own lanes already resolve on stage and prod — a second check") + +# ── THE FAST SHAPE (orun >= v2.88.0) ────────────────────────────────────── +# The run-level list is the task set-up, all of it in the background: the +# first phase's provider check, placement, rebrand, repository and secrets +# run while it opens the epic, the milestones and the tasks. +for h in run_hooks: + if not h.get("background"): + bad(f"hooks.preInstantiate {h.get('id')} is not `background: true` — the first phase " + f"waits for it before doing anything, though nothing before its landing reads it") +# No phase keeps a `pre` hook on the task plane: one there waits for the +# whole background list before the phase has done anything. +PLANE = ("orun.task/", "orun.pr/land@") +for p in phases: + for h in ((p.get("hooks") or {}).get("pre") or []): + if (h.get("uses") or "").startswith(PLANE): + bad(f"phase {p['name']} pre hook {h.get('id')} uses the task plane ({h['uses']}) — " + f"move it to `post`, just before the landing") +# Every landing checks its commit here and merges, instead of waiting 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) +print(f" {len(publishes)} wiring document(s), {readers} reader(s), each waiting for its publisher on main") +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..13230a7 --- /dev/null +++ b/testing/placement.test.sh @@ -0,0 +1,384 @@ +#!/usr/bin/env bash +# TIER 1 — the tree is placed, branded, and made to answer. +# +# A real bootstrap is `orun new --run-hooks --resume` against a workspace: it +# places each phase, runs that phase's hooks, lands a pull request and watches +# the convergence. Everything in that sentence except the platform can run +# here, offline, and this file runs it: +# +# 1. the whole blueprint placed in one go — orun runs `validate` and +# `plan --dry-run` inside the produced tree and says so; asserted, because +# a future orun that stopped running them would weaken this tier in silence; +# 2. THE OFFLINE BOOTSTRAP (testing/lib/bootstrap.sh) — both phases placed in +# order onto what the previous one landed, finished by the blueprint's OWN +# `run:` hooks (retouch, rebrand, re-tenant, work-tree strip, the +# deferrals and their restore, the deployment record), each +# landing a commit; +# 3. the product it ends with: branded with no residue — the store's name +# and source link, the Worker and its self-reference binding, the R2 +# bucket names and every secret ref its own — carrying nothing of the +# factory and naming none of it, re-tenanted, its gates restored, its +# record rendered; +# 4. what the product's own CI does with the 01-product merge: `orun plan` +# for a push to main over exactly that commit — INFRA BEFORE APP: the R2 +# bucket applied on stage and prod, each Worker deploy waiting on its own +# environment's apply and nothing else, stage and prod side by side, +# nothing on dev; the R2 root authenticating with the r2-data token and +# the deploy with the workers-deploy one; the build rendering the +# environment's wiring, the Worker, smoke and secret refs the product's +# own. Then the same edge on a pull request, where it is advisory and +# nothing waits; and the 02-docs merge, which plans nothing at all; +# 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 +# Step 4 is the PRODUCT's own plan, so it must be planned by the orun the +# product's CI runs (ci.yml's pin) or newer: an older orun (v2.58.11, the +# bootstrap's floor before v2.88.0) does not apply a dependsOn edge's +# `modeRules`, and would plan a pull request with the site waiting on +# the R2 plan. +pin="$(sed -n 's/^ *version: *v\([0-9.]*\) *$/\1/p' "$root/.github/workflows/ci.yml" | head -1)" +have="$(orun --version | sed -n 's/.*version \([0-9.]*\).*/\1/p')" +python3 -c "import sys; v=lambda s: tuple(map(int, s.split('.'))); sys.exit(0 if v(sys.argv[1]) >= v(sys.argv[2]) else 1)" "$have" "$pin" \ + || { echo "placement.test.sh plans as the product's CI does: run it with orun >= v$pin (ci.yml's pin), not v$have" >&2; exit 1; } + +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 product" +[ "$fails" -eq 0 ] && echo " $n files placed; the repo-scale gate ran" + +# ── 2. the offline bootstrap ─────────────────────────────────────────────── +echo "── the offline bootstrap: both phases, their own hooks, a landing each" +tree="$scratch/$repo" # named as the repository is: orun names the project after it +bootstrap_offline "$root" "$tree" "$values" "$scratch/logs" > "$scratch/bootstrap.log" 2>&1 || { + echo "FAIL: the offline bootstrap stopped" >&2; tail -40 "$scratch/bootstrap.log" >&2; exit 1; } +grep -E '^── ' "$scratch/bootstrap.log" | sed 's/^/ /' +commits="$(git -C "$tree" rev-list --count HEAD)" +[ "$commits" = 2 ] || fail "the bootstrap landed $commits commits, not one per phase (2)" + +# ── 3. the product it ends with ──────────────────────────────────────────── +echo "── the product it produced" +(cd "$tree" && node "$root/tooling/rebrand/rebrand.mjs" --verify --values .rebrand/values.json) > "$scratch/verify.log" 2>&1 \ + || { fail "rebrand --verify found the baseline's identity in the product:"; sed 's/^/ /' "$scratch/verify.log" >&2; } + +python3 - "$tree" "$values" "$root" <<'PY' || fails=$((fails + 1)) +import json, pathlib, re, subprocess, sys +import yaml +tree, values, root = pathlib.Path(sys.argv[1]), json.load(open(sys.argv[2])), pathlib.Path(sys.argv[3]) +problems = [] +def bad(m): problems.append(m) +repo, org, name, sub, ws = (values[k] for k in ("reponame", "githuborg", "productname", "subdomain", "orunWorkspace")) + +tracked = subprocess.run(["git", "ls-files"], cwd=tree, capture_output=True, text=True, check=True).stdout.split() + +# Nothing of the factory, nothing local, exactly the two context pages… +NEVER = (".baseline/", "specs/", "tasks/", "testing/", "hooks/", "docs/phases/", + "tooling/rebrand/", "tooling/bootstrap/", ".github/workflows/baseline.yml", + ".github/workflows/tag.yml", "BOOTSTRAP.md", "repo-blueprint.yaml", "blueprint.yaml") +for p in tracked: + if any(p == n or p.startswith(n) for n in NEVER): + bad(f"{p} is in the product — it is the factory") + if re.search(r"(^|/)(\.env(\.local)?|\.dev\.vars|node_modules|\.orun|\.next|\.open-next|\.terraform)(/|$)|\.tfstate$", p): + bad(f"{p} is in the product — a local or built file") +ai = {p for p in tracked if p.startswith("ai/")} +if ai != {"ai/context/deployment.md", "ai/context/operations.md"}: + bad(f"ai/ in the product is {sorted(ai)}") +# …and no file it carries NAMES the factory: those paths do not exist here. +FACTORY = re.compile(r"repo-blueprint|BOOTSTRAP\.md|(? "$scratch/validate.log" 2>&1 \ + || { fail "orun validate refused the product's intent at 01-product"; tail -10 "$scratch/validate.log" >&2; } +# The first push to main: every file is new, so the changed set is everything +# and the plan is the full one. +(cd "$tree" && orun plan --intent intent.yaml --trigger github-push-main --output "$scratch/plan.json") \ + > "$scratch/plan.log" 2>&1 || { fail "orun plan failed in the product 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"]} +want = {("cloudflare-r2", "stage"), ("cloudflare-r2", "prod"), ("web", "stage"), ("web", "prod")} +if set(jobs) != want: + bad(f"the 01-product merge plans {sorted(jobs)}; it must apply cloudflare-r2 and deploy web on " + f"stage and prod, and nothing else (dev's push lanes are deferred)") + +def refs(j): + return {r["asEnv"]: r["ref"] for r in j.get("secretRefs") or []} +def ours(ref): + return ref.startswith(f"secret://{ws}/") and (f"/{repo}/" in ref or f"project:{repo}" in ref) + +for env in ("stage", "prod"): + r2, web = jobs.get(("cloudflare-r2", env)), jobs.get(("web", env)) + if not r2 or not web: + continue + # INFRA BEFORE APP: the Worker's deploy waits for its own environment's + # R2 apply, and for nothing else — not the other environment, not stage. + if not r2["profile"].endswith(".apply"): + bad(f"cloudflare-r2@{env} plans profile {r2['profile']}, not an apply") + if r2.get("dependsOn"): + bad(f"cloudflare-r2@{env} waits on {r2['dependsOn']} — during the bootstrap stage and prod apply side by side") + if not web["profile"].endswith(".deploy"): + bad(f"web@{env} plans profile {web['profile']}, not a deploy") + if (web.get("dependsOn") or []) != [r2["id"]]: + bad(f"web@{env} waits on {web.get('dependsOn')}; it must wait on {r2['id']} alone (infra before app)") + steps = {s["id"]: s.get("run") or "" for s in web["steps"]} + for need in ("verify-app-structure", "build-app", "deploy", "smoke"): + if need not in steps: + bad(f"web@{env} has no {need} step") + if "tooling/wire/live.mjs" not in steps.get("build-app", "") or "--components cloudflare-r2" not in steps.get("build-app", ""): + bad(f"web@{env}'s build does not render the R2 wiring: {steps.get('build-app','').strip()}") + if f'EFFECTIVE_WORKER_NAME="{repo}-web-{env}"' not in steps.get("deploy", ""): + bad(f"web@{env} deploys a Worker not named {repo}-web-{env}") + if "/api/health" not in steps.get("smoke", ""): + bad(f"web@{env}'s smoke does not check the Worker-answered /api/health") + r = refs(web) + for key in ("CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID", f"WIRING_CLOUDFLARE_R2_{env.upper()}"): + if not ours(r.get(key, "")): + bad(f"web@{env} resolves {key} from {r.get(key) or 'nowhere'} — not the product's workspace and project") + if r.get("CLOUDFLARE_API_TOKEN", "").endswith("/CLOUDFLARE_R2_TOKEN"): + bad(f"web@{env} deploys with the R2 key; the deploy token is workers-deploy's CLOUDFLARE_API_TOKEN") + r = refs(r2) + for key in ("CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID"): + if not ours(r.get(key, "")): + bad(f"cloudflare-r2@{env} resolves {key} from {r.get(key) or 'nowhere'} — not the product's") + if not r.get("CLOUDFLARE_API_TOKEN", "").endswith("/CLOUDFLARE_R2_TOKEN"): + bad(f"cloudflare-r2@{env} authenticates with {r.get('CLOUDFLARE_API_TOKEN')}, not the r2-data key " + f"CLOUDFLARE_R2_TOKEN — workers-deploy carries no R2") +# The lanes say the same: the applies first, each deploy one level down. +level = {l["id"]: l.get("level") for l in plan.get("lanes") or []} +lane_of = {jid: l["id"] for l in plan.get("lanes") or [] for jid in l["jobs"]} +for env in ("stage", "prod"): + k, w = lane_of.get(f"cloudflare-r2.{env}.terraform"), lane_of.get(f"web.{env}.verify-deploy") + if k and w and not (level.get(k) == 0 and level.get(w) == 1): + bad(f"{env}: the R2 lane is level {level.get(k)} and the web lane level {level.get(w)} — want 0 then 1") +if problems: + for p in problems: + print(f" ✕ {p}", file=sys.stderr) + sys.exit(1) +print(" cloudflare-r2 → stage + prod, apply (r2-data key), level 0; web → stage + prod, deploy") +print(" (workers-deploy key), level 1, each waiting on its own environment's apply alone (infra before app);") +print(" Worker, wiring, smoke and secrets the product's own") +PY + +echo "── …the same edge on a pull request: advisory, nothing waits" +git -C "$tree" worktree add -q "$scratch/pr" "$s01" +echo "// a change" >> "$scratch/pr/apps/web/app/[locale]/(marketing)/page.tsx" +echo "# a change" >> "$scratch/pr/infra/terraform/cloudflare-r2/terraform/main.tf" +git -C "$scratch/pr" -c user.email=t@example.invalid -c user.name=t commit -qam "a pull request" +(cd "$scratch/pr" && orun plan --intent intent.yaml --trigger github-pull-request --changed \ + --base "$s01" --head HEAD --output "$scratch/plan-pr.json") > "$scratch/plan-pr.log" 2>&1 \ + || { fail "orun plan failed for a pull request"; tail -15 "$scratch/plan-pr.log" >&2; } +python3 - "$scratch/plan-pr.json" <<'PY' || fails=$((fails + 1)) +import json, sys +plan = json.load(open(sys.argv[1])) +jobs = {(j["component"], j["environment"]): j for j in plan["jobs"]} +problems = [] +for env in ("stage", "prod"): + web, r2 = jobs.get(("web", env)), jobs.get(("cloudflare-r2", env)) + if not web or not r2: + problems.append(f"the pull request plans no web or cloudflare-r2 job on {env}") + continue + if not web["profile"].endswith(".verify") or not r2["profile"].endswith(".plan-only"): + problems.append(f"{env}: a pull request plans {web['profile']} and {r2['profile']} — it must verify and plan only") + if r2["id"] in (web.get("dependsOn") or []): + problems.append(f"web@{env} waits on {r2['id']} on a pull request — the edge must be advisory there") +for p in problems: + print(f" ✕ {p}", file=sys.stderr) +sys.exit(1 if problems else 0) +PY +[ "$fails" -eq 0 ] && echo " web verifies beside the R2 plan on stage and prod; neither waits" +git -C "$tree" worktree remove --force "$scratch/pr" + +echo "── …and the 02-docs merge plans nothing" +(cd "$tree" && orun plan --intent intent.yaml --trigger github-push-main --changed \ + --base "$s01" --head "$s02" --output "$scratch/plan-02.json") > "$scratch/plan-02.log" 2>&1 \ + || { fail "orun plan failed for the 02-docs merge"; tail -15 "$scratch/plan-02.log" >&2; } +jobs02="$(python3 -c "import json,sys;print(len(json.load(open(sys.argv[1]))['jobs']))" "$scratch/plan-02.json" 2>/dev/null || echo '?')" +[ "$jobs02" = 0 ] && echo " 0 jobs: restoring the gates and writing the record redeploys nothing" \ + || fail "the 02-docs merge plans $jobs02 job(s); it touches no component and must plan none" + +# ── 5. a resume over the finished site ──────────────────────────────────── +echo "── --resume over the finished product" +before="$(git -C "$tree" status --porcelain; git -C "$tree" rev-parse HEAD)" +orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" --resume "${sets[@]}" > "$scratch/resume.log" 2>&1 \ + || { fail "--resume did not run"; tail -10 "$scratch/resume.log" >&2; } +after="$(git -C "$tree" status --porcelain; git -C "$tree" rev-parse HEAD)" +[ "$before" = "$after" ] || { fail "--resume changed the finished product:"; git -C "$tree" status --short | head -10 >&2; } +grep -q "SITE_NAME = \"Sam's Tees & Mugs\"" "$tree/apps/web/lib/site.ts" \ + || fail "--resume reverted the product's identity" +[ "$fails" -eq 0 ] && echo " nothing placed again, nothing un-branded" + +[ "$fails" -eq 0 ] || { echo "placement.test.sh: $fails failure(s)" >&2; exit 1; } +echo "placement.test.sh: ok" diff --git a/testing/rebrand.test.sh b/testing/rebrand.test.sh new file mode 100755 index 0000000..f739d8f --- /dev/null +++ b/testing/rebrand.test.sh @@ -0,0 +1,219 @@ +#!/usr/bin/env bash +# THE REBRAND WRITES EACH VALUE ONCE, AND WHAT IT WROTE STAYS WRITTEN. +# +# Drives the real tooling/rebrand/rebrand.mjs over one-file trees and compares +# the file. Each case is a shape this baseline's identity actually takes in the +# tree — the repository link, the site-name seam, the worker name in the +# component and the wrangler config (and the Worker's self-reference binding), +# the R2 bucket names and the terraform `repo` they are built from, the +# placeholder domain, a secret ref — and the survival cases run through three +# passes, so a value an earlier rebrand wrote (a re-run phase re-runs the +# rebrand over everything placed) comes out of every later one unchanged. +# +# Two cases pin what makes a shipped file spell this baseline's slug and its +# code form only where they ARE the identity: the slug in prose IS the slug to +# the rename, and the Pascal form anywhere is residue. The template's own +# words, `Strapi` and `LaunchPad`, are not this identity: cases pin that no +# rule touches them. +# +# The identity is PINNED (fixtures/baseline-identity.strapi-launchpad.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.strapi-launchpad.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-shop","productname":"Acme Shop","productdomain":"shop.acme.dev","githuborg":"acme-inc","subdomain":"acme","orunWorkspace":"ws_79BDXAZQ"}' + +echo "── rebrand: the site's own identity" +check "the repository link names the product's owner and repository" \ + "$acme" README.md \ + 'The source is [github.com/sourceplane/strapi-launchpad](https://github.com/sourceplane/strapi-launchpad).' \ + 'The source is [github.com/acme-inc/acme-shop](https://github.com/acme-inc/acme-shop).' +check "the site-name seam takes the product's name" \ + "$acme" apps/web/lib/site.ts 'export const SITE_NAME = "LaunchPad";' \ + 'export const SITE_NAME = "Acme Shop";' +check "…and stays a valid string for a name with an apostrophe and an ampersand" \ + '{"reponame":"sams-shop","productname":"Sam'"'"'s Tees & Mugs","productdomain":"sam.dev"}' \ + apps/web/lib/site.ts 'export const SITE_NAME = "LaunchPad";' \ + 'export const SITE_NAME = "Sam'"'"'s Tees & Mugs";' +check "the worker name is re-prefixed" \ + "$acme" apps/web/component.yaml 'workerName: strapi-launchpad-web' \ + 'workerName: acme-shop-web' +check "the wrangler config's worker name, the environment token kept" \ + "$acme" apps/web/wrangler.template.jsonc ' "name": "strapi-launchpad-web-__ENV__",' \ + ' "name": "acme-shop-web-__ENV__",' +check "the Worker's self-reference binding names the same Worker" \ + "$acme" apps/web/wrangler.jsonc \ + ' { "binding": "WORKER_SELF_REFERENCE", "service": "strapi-launchpad-web-stage" },' \ + ' { "binding": "WORKER_SELF_REFERENCE", "service": "acme-shop-web-stage" },' +check "the environment URLs: worker name and subdomain" \ + "$acme" intent.yaml ' url: https://strapi-launchpad-web-stage.your-workers-subdomain.workers.dev' \ + ' url: https://acme-shop-web-stage.acme.workers.dev' +check "the R2 root's terraform repo — every bucket name is built on it" \ + "$acme" infra/terraform/cloudflare-r2/terraform/main.tf ' default = "strapi-launchpad"' \ + ' default = "acme-shop"' +check "the per-environment terraform repo parameter" \ + "$acme" intent.yaml ' repo: strapi-launchpad' \ + ' repo: acme-shop' +check "a fixture's bucket name follows the same rule" \ + "$acme" apps/web/wiring.fixture.json ' "r2_bucket_name": "stg-strapi-launchpad-stage"' \ + ' "r2_bucket_name": "stg-acme-shop-stage"' +check "the placeholder domain is the product's domain, not a renamed slug" \ + "$acme" intent.yaml ' BASE_DOMAIN: strapi-launchpad.example.com' \ + ' BASE_DOMAIN: shop.acme.dev' +check "no domain given: the reserved placeholder, for an owner to replace later" \ + '{"reponame":"acme-shop","productname":"Acme Shop","githuborg":"acme-inc","subdomain":"acme"}' \ + intent.yaml ' BASE_DOMAIN: strapi-launchpad.example.com' \ + ' BASE_DOMAIN: acme-shop.example.com' +check "an empty domain is no domain" \ + '{"reponame":"acme-shop","productname":"Acme Shop","productdomain":""}' \ + intent.yaml ' BASE_DOMAIN: strapi-launchpad.example.com' \ + ' BASE_DOMAIN: acme-shop.example.com' +check "the repo slug" \ + "$acme" package.json ' "name": "strapi-launchpad",' \ + ' "name": "acme-shop",' +check "a wiring secret ref names the product's workspace and project" \ + "$acme" apps/web/component.yaml \ + ' WIRING_CLOUDFLARE_R2_STAGE: "secret://strapi-launchpad/strapi-launchpad/stage/WIRING_CLOUDFLARE_R2"' \ + ' WIRING_CLOUDFLARE_R2_STAGE: "secret://ws_79BDXAZQ/acme-shop/stage/WIRING_CLOUDFLARE_R2"' +check "the R2 root's templated token ref too" \ + "$acme" infra/terraform/cloudflare-r2/component.yaml \ + ' CLOUDFLARE_API_TOKEN: "secret://strapi-launchpad/strapi-launchpad/{{ .environment }}/CLOUDFLARE_R2_TOKEN"' \ + ' CLOUDFLARE_API_TOKEN: "secret://ws_79BDXAZQ/acme-shop/{{ .environment }}/CLOUDFLARE_R2_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 the repository link keeps the baseline's owner" \ + '{"reponame":"acme-shop","productname":"Acme Shop","productdomain":"shop.acme.dev"}' \ + README.md 'https://github.com/sourceplane/strapi-launchpad' \ + 'https://github.com/sourceplane/acme-shop' +check "THE HAZARD: in prose the rename takes the slug for the slug" \ + "$acme" apps/web/README.md 'the strapi-launchpad marketing site' \ + 'the acme-shop marketing site' +check "the template's own words are not this identity: Strapi's names are left alone" \ + "$acme" apps/web/lib/strapi/client.ts \ + "import { strapi } from '@strapi/client'; // Strapi's REST API, for LaunchPad" \ + "import { strapi } from '@strapi/client'; // Strapi's REST API, for LaunchPad" +check "…nor is the sample content's LaunchPad, or upstream's strapi/LaunchPad link" \ + "$acme" apps/web/sample/strapi/global.en.json \ + ' "company": "LaunchPad", "href": "https://github.com/strapi/launchpad"' \ + ' "company": "LaunchPad", "href": "https://github.com/strapi/launchpad"' + +echo "── rebrand: a written value is not rewritten, in any later pass" +contains='{"reponame":"strapi-launchpad-2","productname":"LaunchPad 2","productdomain":"strapi-launchpad.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": "strapi-launchpad",' \ + ' "name": "strapi-launchpad-2",' 3 +check "a worker name built on it survives three passes" \ + "$contains" apps/web/component.yaml 'workerName: strapi-launchpad-web' \ + 'workerName: strapi-launchpad-2-web' 3 +check "a bucket name built on it survives three passes" \ + "$contains" apps/web/wiring.fixture.json '"r2_bucket_name": "prod-strapi-launchpad-prod"' \ + '"r2_bucket_name": "prod-strapi-launchpad-2-prod"' 3 +check "a domain containing the baseline's domain survives three passes" \ + "$contains" intent.yaml 'BASE_DOMAIN: strapi-launchpad.example.com' \ + 'BASE_DOMAIN: strapi-launchpad.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 store name containing the baseline's name survives three passes" \ + "$contains" apps/web/lib/site.ts 'export const SITE_NAME = "LaunchPad";' \ + 'export const SITE_NAME = "LaunchPad 2";' 3 +prefixed='{"reponame":"acme-strapi-launchpad","productname":"Sam'"'"'s Tees & Mugs","productdomain":"shop.acme.dev","githuborg":"acme-inc","subdomain":"acme","orunWorkspace":"ws_79BDXAZQ"}' +check "a slug that ENDS in the baseline's slug survives three passes (the e2e fixture's)" \ + "$prefixed" apps/web/wrangler.jsonc '"service": "strapi-launchpad-web-stage"' \ + '"service": "acme-strapi-launchpad-web-stage"' 3 +check "…and so does its bucket name" \ + "$prefixed" apps/web/wiring.fixture.json '"r2_bucket_name": "stg-strapi-launchpad-stage"' \ + '"r2_bucket_name": "stg-acme-strapi-launchpad-stage"' 3 +check "…and, with no domain, its placeholder (which ends in the baseline's domain)" \ + '{"reponame":"acme-strapi-launchpad","productname":"Sam'"'"'s Tees & Mugs","githuborg":"acme-inc","subdomain":"acme"}' \ + intent.yaml ' BASE_DOMAIN: strapi-launchpad.example.com' \ + ' BASE_DOMAIN: acme-strapi-launchpad.example.com' 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": "strapi-launchpad-2"' pass --values +verify "without them it cannot know, and fails" \ + "$contains" package.json '"name": "strapi-launchpad-2"' fail +verify "given the values, a real leftover still fails" \ + "$acme" package.json '"name": "strapi-launchpad"' fail --values +verify "a leftover worker name fails" \ + "$acme" apps/web/wrangler.jsonc '"name": "strapi-launchpad-web-stage",' fail --values +verify "a leftover bucket name fails" \ + "$acme" apps/web/wiring.fixture.json '"r2_bucket_name": "stg-strapi-launchpad-stage"' fail --values +verify "THE HAZARD: the Pascal form anywhere fails (no rule renames it — so nothing may spell it)" \ + "$acme" apps/web/components/banner.tsx 'export function StrapiLaunchpadBanner() {}' fail --values +verify "a clean product passes" \ + "$acme" package.json '"name": "acme-shop"' pass --values +verify "a product whose own name carries the Pascal form passes, given the values" \ + '{"reponame":"acme-shop","productname":"StrapiLaunchpad Outlet","productdomain":"shop.acme.dev"}' \ + apps/web/lib/site.ts 'export const SITE_NAME = "StrapiLaunchpad Outlet";' pass --values +verify "the template's own words are not residue" \ + "$acme" apps/web/next.config.ts 'const STRAPI_URL = process.env.STRAPI_URL; // Strapi, LaunchPad' 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 = "STRAPI_LAUNCHPAD_TOKEN"\n' > "$tmp/apps/web/x.ts" +git -C "$tmp" add -A +if (cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --values .rebrand/values.json --allow-dirty >/dev/null 2>&1); then + echo " ✕ an unrenamable env-var prefix passed the rebrand" >&2; fail=1 +else + echo " ok an unrenamable env-var prefix fails the rebrand, naming the file" +fi +rm -rf "$tmp" + +[ "$fail" -eq 0 ] || exit 1 +echo "rebrand.test.sh: ok" diff --git a/testing/retouch.test.sh b/testing/retouch.test.sh new file mode 100755 index 0000000..1ef5d69 --- /dev/null +++ b/testing/retouch.test.sh @@ -0,0 +1,199 @@ +#!/usr/bin/env bash +# A RE-RUN PHASE HAS SOMETHING TO LAND. +# +# A phase's convergence can fail AFTER its PR merged, and the merge has already +# put every file the phase places on main. orun derives phase state from the +# files, so a retried build sees the phase placed and a forced re-run of it +# lands an EMPTY diff — and the product's CI plans `--changed`, so a component +# whose files did not change in the push does not deploy. The phase's `retouch` +# hook (tooling/bootstrap/retouch.mjs) is what breaks that: one marker line at +# the end of each affected component.yaml, +# +# # orun: redeploy +# +# replaced rather than accumulated, so the landing has a diff and exactly the +# phase's components are in the changed set. The marker is a deploy trigger and +# nothing reads it back; phase state stays derived, never stored. +# +# This drives the real retouch.mjs over a two-component tree, then checks that +# every component the blueprint's retouch hooks name resolves in THIS tree — +# the layout a product is placed with. +# Needs: node. No network. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" +retouch="$root/tooling/bootstrap/retouch.mjs" + +command -v node >/dev/null || { echo "retouch.test.sh needs node" >&2; exit 1; } + +fail=0 +ok() { echo " ok $*"; } +bad() { echo " ✕ $*" >&2; fail=1; } + +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT + +# A product tree with two components in two of the lanes the blueprint places +# into, a test package that shares a directory name with the first (as +# tests/ does with apps/) and must NOT be touched, and the +# hand-written re-trigger line the fleet carried before this tool existed. +mkdir -p "$tmp/apps/alpha" "$tmp/infra/beta" "$tmp/tests/alpha" "$tmp/node_modules/x" +cat > "$tmp/apps/alpha/component.yaml" <<'Y' +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: alpha +spec: + type: cloudflare-worker-turbo + labels: + team: platform +# ci: re-trigger deploy (batch A — runner-starvation recovery 20260622T115650Z) +Y +# No trailing newline on purpose: the tool must add one, and only one. +printf 'apiVersion: sourceplane.io/v1\nkind: Component\nmetadata:\n name: beta\nspec:\n type: terraform' > "$tmp/infra/beta/component.yaml" +printf 'kind: Component\nmetadata:\n name: alpha-tests\n' > "$tmp/tests/alpha/component.yaml" +printf 'kind: Component\nmetadata:\n name: alpha\n' > "$tmp/node_modules/x/component.yaml" +cp "$tmp/apps/alpha/component.yaml" "$tmp/alpha.orig" +cp "$tmp/infra/beta/component.yaml" "$tmp/beta.orig" + +markers() { grep -c '^# orun: redeploy ' "$1" || true; } + +echo "── retouch: one marker, last, replaced not appended" +(cd "$tmp" && ORUN_RUN_ID=run-one node "$retouch" --phase 04-workers --components alpha,beta) > "$tmp/one.log" 2>&1 \ + || { bad "first run failed:"; sed 's/^/ /' "$tmp/one.log" >&2; } +for f in apps/alpha infra/beta; do + [ "$(markers "$tmp/$f/component.yaml")" = 1 ] || bad "$f: $(markers "$tmp/$f/component.yaml") marker lines after one run, want 1" + [ "$(tail -n1 "$tmp/$f/component.yaml")" = "# orun: redeploy 04-workers run-one" ] \ + || bad "$f: last line is '$(tail -n1 "$tmp/$f/component.yaml")'" +done +[ "$(tail -c1 "$tmp/infra/beta/component.yaml" | od -An -c | tr -d ' ')" = '\n' ] \ + || bad "infra/beta: no trailing newline after retouch" +ok "both components carry the marker as their last line" + +(cd "$tmp" && ORUN_RUN_ID=run-two node "$retouch" --phase 04-workers-restore --components alpha,beta) > "$tmp/two.log" 2>&1 \ + || { bad "second run failed:"; sed 's/^/ /' "$tmp/two.log" >&2; } +for f in apps/alpha infra/beta; do + [ "$(markers "$tmp/$f/component.yaml")" = 1 ] || bad "$f: $(markers "$tmp/$f/component.yaml") marker lines after two runs — the marker accumulated" + [ "$(tail -n1 "$tmp/$f/component.yaml")" = "# orun: redeploy 04-workers-restore run-two" ] \ + || bad "$f: second run did not replace the marker: '$(tail -n1 "$tmp/$f/component.yaml")'" +done +grep -q 'replace marker' "$tmp/two.log" || bad "second run did not report a replacement" +ok "a second run replaces the marker (a different phase's too) rather than appending" + +echo "── retouch: every other byte is as it was" +if [ "$(head -n -1 "$tmp/apps/alpha/component.yaml" | cksum)" = "$(cksum < "$tmp/alpha.orig")" ]; then + ok "apps/alpha: the file above the marker is byte-for-byte the original" +else + bad "apps/alpha: bytes above the marker changed" + diff <(head -n -1 "$tmp/apps/alpha/component.yaml") "$tmp/alpha.orig" >&2 || true +fi +if [ "$(head -n -1 "$tmp/infra/beta/component.yaml" | cksum)" = "$(printf '%s\n' "$(cat "$tmp/beta.orig")" | cksum)" ]; then + ok "infra/beta: only a newline was added before the marker" +else + bad "infra/beta: bytes above the marker changed" +fi +grep -q '^# ci: re-trigger deploy' "$tmp/apps/alpha/component.yaml" \ + && ok "the hand-written re-trigger line is left alone" \ + || bad "the hand-written re-trigger line was removed" +[ "$(cat "$tmp/tests/alpha/component.yaml")" = "$(printf 'kind: Component\nmetadata:\n name: alpha-tests\n')" ] \ + && ok "tests/alpha (alpha-tests) was not touched — components resolve by metadata.name" \ + || bad "tests/alpha was touched: a component is its metadata.name, not its directory name" + +echo "── retouch: the same stamp twice is a no-op" +(cd "$tmp" && ORUN_RUN_ID=run-two node "$retouch" --phase 04-workers-restore --components alpha,beta) > "$tmp/again.log" 2>&1 \ + || bad "idempotent re-run failed" +grep -q 'nothing to do' "$tmp/again.log" && ok "re-running with the same stamp reports nothing to do" \ + || bad "re-running with the same stamp did not report a no-op: $(tail -1 "$tmp/again.log")" + +echo "── retouch: the stamp" +(cd "$tmp" && env -u ORUN_RUN_ID ORUN_SESSION_ID=sess-9 node "$retouch" --phase p --components beta) >/dev/null 2>&1 +[ "$(tail -n1 "$tmp/infra/beta/component.yaml")" = "# orun: redeploy p sess-9" ] \ + && ok "ORUN_SESSION_ID stamps when ORUN_RUN_ID is unset" \ + || bad "ORUN_SESSION_ID was not used: '$(tail -n1 "$tmp/infra/beta/component.yaml")'" +(cd "$tmp" && env -u ORUN_RUN_ID -u ORUN_SESSION_ID node "$retouch" --phase p --components beta) >/dev/null 2>&1 +tail -n1 "$tmp/infra/beta/component.yaml" | grep -Eq '^# orun: redeploy p [0-9]{8}T[0-9]{6}Z$' \ + && ok "with neither, a UTC timestamp" \ + || bad "no timestamp stamp: '$(tail -n1 "$tmp/infra/beta/component.yaml")'" + +echo "── retouch: --dry-run writes nothing, --check names what is missing" +before="$(cksum < "$tmp/apps/alpha/component.yaml")" +(cd "$tmp" && ORUN_RUN_ID=dry node "$retouch" --phase p --components alpha --dry-run) > "$tmp/dry.log" 2>&1 \ + || bad "--dry-run failed" +[ "$before" = "$(cksum < "$tmp/apps/alpha/component.yaml")" ] && grep -q 'would replace marker' "$tmp/dry.log" \ + && ok "--dry-run reports the change and leaves the file alone" \ + || bad "--dry-run wrote, or did not say what it would do" + +if (cd "$tmp" && node "$retouch" --phase p --components alpha,gamma --check) > "$tmp/check.log" 2>&1; then + bad "--check passed with gamma absent" +else + grep -q 'gamma' "$tmp/check.log" && ok "--check fails and names gamma" \ + || bad "--check failed without naming the missing component: $(cat "$tmp/check.log")" +fi +if (cd "$tmp" && ORUN_RUN_ID=x node "$retouch" --phase p --components alpha,gamma) > "$tmp/miss.log" 2>&1; then + bad "a run with a missing component succeeded" +else + [ "$(tail -n1 "$tmp/apps/alpha/component.yaml")" != "# orun: redeploy p x" ] \ + && ok "a missing component refuses the whole run before any file is written" \ + || bad "a missing component still wrote the components that exist" +fi +(cd "$tmp" && node "$retouch" --phase p --components alpha,beta --check) >/dev/null 2>&1 \ + && ok "--check passes when every component resolves" || bad "--check failed on a complete set" + +echo "── retouch: --affects reads a task contract" +cat > "$tmp/contract.yaml" <<'Y' +# A contract, as .baseline/tasks/*.TaskContract.yaml are written. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: Two components converge + affects: + - alpha + # a comment between items + - beta + doneWhen: + - convergence green + gates: [] +Y +(cd "$tmp" && ORUN_RUN_ID=via-contract node "$retouch" --phase 05-edge --affects contract.yaml) > "$tmp/aff.log" 2>&1 \ + || { bad "--affects run failed:"; sed 's/^/ /' "$tmp/aff.log" >&2; } +for f in apps/alpha infra/beta; do + [ "$(tail -n1 "$tmp/$f/component.yaml")" = "# orun: redeploy 05-edge via-contract" ] \ + || bad "$f: --affects did not touch it" +done +grep -q '2 of 2' "$tmp/aff.log" && ok "spec.affects named both, and both were touched" \ + || bad "--affects touched the wrong number: $(tail -1 "$tmp/aff.log")" +printf 'spec:\n affects: [alpha, beta]\n' > "$tmp/flow.yaml" +(cd "$tmp" && ORUN_RUN_ID=flow node "$retouch" --phase p --affects flow.yaml --check) >/dev/null 2>&1 \ + && ok 'the flow form `affects: [a, b]` reads too' || bad "the flow form of affects did not read" +printf 'spec:\n goal: nothing\n' > "$tmp/none.yaml" +(cd "$tmp" && node "$retouch" --phase p --affects none.yaml --check) >/dev/null 2>&1 \ + && bad "a contract with no affects passed --check" || ok "a contract with no affects refuses" + +# ── THE BLUEPRINT'S OWN HOOKS RESOLVE IN THIS TREE ───────────────────────── +# Every `retouch` hook in repo-blueprint.yaml names the components a phase +# redeploys, through a contract (.baseline/tasks/) or a list. A product is placed with this +# repository's layout, so each must resolve here — a contract that names a +# component nobody ships, or a component that moved, fails a real bootstrap at +# the landing, an hour in. `{{ .baseline.dir }}` is this checkout. +echo "── the blueprint's retouch hooks, against this tree" +hooks=0 +while IFS= read -r line; do + hooks=$((hooks + 1)) + argv="$(printf '%s' "$line" | sed -e 's/^[[:space:]]*run:[[:space:]]*//' \ + -e "s#{{ \.baseline\.dir }}#$root#g" -e 's#{{ \.phase\.name }}#probe#g')" + if (cd "$root" && node -e ' + const argv = JSON.parse(process.argv[1]); + const { spawnSync } = require("node:child_process"); + const r = spawnSync(argv[0], [...argv.slice(1), "--check"], { stdio: ["ignore", "pipe", "pipe"] }); + process.stdout.write(r.stdout); process.stderr.write(r.stderr); + process.exit(r.status ?? 1); + ' "$argv") > "$tmp/hook.log" 2>&1; then + ok "$(grep -c -- '->' "$tmp/hook.log") component(s): ${argv#*retouch.mjs\", }" + else + bad "a retouch hook does not resolve: $argv"; sed 's/^/ /' "$tmp/hook.log" >&2 + fi +done < <(grep -E '^\s*run: \[.*retouch\.mjs' "$root/repo-blueprint.yaml") +[ "$hooks" -ge 1 ] || bad "only $hooks retouch hook(s) in repo-blueprint.yaml — 01-product lands the deployable product and needs one" + +[ "$fail" -eq 0 ] || exit 1 +echo "retouch.test.sh: ok" diff --git a/testing/wire.test.sh b/testing/wire.test.sh new file mode 100755 index 0000000..293e139 --- /dev/null +++ b/testing/wire.test.sh @@ -0,0 +1,188 @@ +#!/usr/bin/env bash +# THE WIRING PATH — from a Terraform apply to the id in a deployed Worker's +# config — holds end to end, offline. +# +# An infra component lease-publishes a wiring document after its apply +# (`secretOutputs: "WIRING_=wiring"`, the root's `output "wiring"`); a +# deployable names the values it needs as tokens in `wrangler.template.jsonc` +# (`@@wiring(/__ENV__:)@@`), and its build renders `wrangler.jsonc` +# from the document (`tooling/wire/live.mjs`, in the component's +# buildCommand). Four things can drift apart there, and each fails a real +# deploy, late: +# +# 1. a token naming a key the root does not output, or a root that publishes +# nothing — the render fails on the deploy lane; +# 2. the fixture missing an environment the deployable builds for — its +# verify lane fails; +# 3. the committed wrangler.jsonc not being the fixture render — the deploy +# lane's `verify-app-structure` checks the config exists BEFORE the build +# (stack-tectonic's workers-assets composition), so the file is +# committed, and a stale one is what a reader finds; +# 4. the build's render command: a deployed environment must render from +# the real document and refuse to run without it, and a verify-only one +# (`dev`, where no root applies) must render from the fixture. +# +# Every templated deployable in the tree is checked, against the commands +# its own component.yaml declares. +# +# Needs: node, python3 (+PyYAML). No network, no credential. +set -euo pipefail +here="$(cd "$(dirname "$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 + +# Every templated deployable, and what the infra publishes — read once. +python3 - "$root" > "$tmp/facts.json" <<'PY' +import json, pathlib, re, sys +import yaml +root = pathlib.Path(sys.argv[1]) +comps = {} +for f in root.rglob("component.yaml"): + if "node_modules" in f.parts or ".orun" in f.parts: + continue + d = yaml.safe_load(f.read_text()) or {} + comps[(d.get("metadata") or {}).get("name")] = {"dir": f.parent.relative_to(root).as_posix(), "spec": d.get("spec") or {}} +publishers = {} +for name, c in comps.items(): + outs = str((c["spec"].get("parameters") or {}).get("secretOutputs") or "") + for pair in filter(None, (x.strip() for x in outs.split(","))): + key, _, output = pair.partition("=") + if not key.startswith("WIRING_"): + continue + tf = "\n".join(p.read_text() for p in (root / c["dir"]).rglob("*.tf")) + m = re.search(r'output\s+"%s"\s*\{.*?jsonencode\(\{(.*?)\}\)' % re.escape(output), tf, re.S) + keys = re.findall(r"^\s*([A-Za-z0-9_]+)\s*=", m.group(1), re.M) if m else [] + envs = [e["name"] for e in (c["spec"].get("subscribe") or {}).get("environments") or []] + publishers[name] = {"key": key, "output": output, "keys": keys, "envs": envs} +deployables = [] +for name, c in comps.items(): + tpl = root / c["dir"] / "wrangler.template.jsonc" + if not tpl.exists(): + continue + params = c["spec"].get("parameters") or {} + envs = [e["name"] for e in (c["spec"].get("subscribe") or {}).get("environments") or []] + tokens = sorted(set(re.findall(r"@@wiring\(([a-z0-9-]+)/__ENV__:([A-Za-z0-9_]+)\)@@", tpl.read_text()))) + deployables.append({"name": name, "dir": c["dir"], "envs": envs, "tokens": tokens, + "build": params.get("buildCommand") or "", "config": params.get("wranglerConfig") or "", + "secretEnv": sorted((c["spec"].get("secretEnv") or {}).keys())}) +print(json.dumps({"publishers": publishers, "deployables": deployables})) +PY +n="$(python3 -c "import json,sys;print(len(json.load(open(sys.argv[1]))['deployables']))" "$tmp/facts.json")" +[ "$n" -ge 1 ] || { echo "no wrangler.template.jsonc anywhere — this check has gone blind" >&2; exit 1; } + +for i in $(seq 0 $((n - 1))); do + eval "$(python3 - "$tmp/facts.json" "$i" <<'PY' +import json, shlex, sys +d = json.load(open(sys.argv[1]))["deployables"][int(sys.argv[2])] +for k in ("name", "dir", "build", "config"): + print(f"{k}={shlex.quote(d[k])}") +print(f"envs={shlex.quote(' '.join(d['envs']))}") +PY +)" + echo "── $name ($dir)" + + # 1 + 2: every token resolves against what its root outputs, and the + # fixture covers every environment the deployable builds for. + python3 - "$tmp/facts.json" "$i" "$root" <<'PY' && ok "every token names a key its root outputs; the fixture covers every environment, the dev rung included" || fail=1 +import json, pathlib, sys +facts = json.load(open(sys.argv[1])); d = facts["deployables"][int(sys.argv[2])]; root = pathlib.Path(sys.argv[3]) +pubs = facts["publishers"] +fixture = json.loads((root / d["dir"] / "wiring.fixture.json").read_text()) +problems = [] +if not d["tokens"]: + problems.append("wrangler.template.jsonc carries no @@wiring(/__ENV__:)@@ token") +for comp, key in d["tokens"]: + p = pubs.get(comp) + if not p: + problems.append(f"token {comp}:{key} — no infra component {comp} lease-publishes a WIRING_* document") + continue + if key not in p["keys"]: + problems.append(f"token {comp}:{key} — {comp}'s output \"{p['output']}\" has {p['keys']}") + for env in d["envs"]: + if not (fixture.get(f"{comp}/{env}") or {}).get(key): + problems.append(f"the fixture has no {comp}/{env}:{key} — the {env} lane renders it") + for env in p["envs"]: + want = f"{p['key']}_{env.upper()}" + if env in d["envs"] and want not in d["secretEnv"]: + problems.append(f"{env} deploys after {comp} applies there, and secretEnv does not resolve {want}") +for p in problems: + print(f" ✕ {p}", file=sys.stderr) +sys.exit(1 if problems else 0) +PY + + # 3: the committed config is the fixture render. + if [ "$config" != "wrangler.jsonc" ] || [ ! -f "$root/$dir/wrangler.jsonc" ]; then + bad "wranglerConfig is '$config' — the composition checks it exists before the build, so it must be the committed wrangler.jsonc" + else + (cd "$root/$dir" && node "$root/tooling/wire/render.mjs" --template wrangler.template.jsonc \ + --out "$tmp/rendered.jsonc" --map wiring.fixture.json --env stage) >/dev/null + cmp -s "$tmp/rendered.jsonc" "$root/$dir/wrangler.jsonc" \ + && ok "the committed wrangler.jsonc is the fixture render" \ + || { bad "the committed wrangler.jsonc is not the fixture render — run \`pnpm run wire:fixture\` and commit it"; diff "$tmp/rendered.jsonc" "$root/$dir/wrangler.jsonc" | head -10 >&2 || true; } + fi + + # 4: the build's own render command, cut from its buildCommand at the + # first `&&` (the rest is the Next.js build), run in a copy of the app. + render="${build%% && *}" + case "$render" in *tooling/wire/live.mjs*) ;; *) bad "buildCommand does not start by rendering with tooling/wire/live.mjs: $build"; continue ;; esac + rm -rf "$tmp/tree"; mkdir -p "$tmp/tree/$dir" "$tmp/tree/tooling" + cp -r "$root/tooling/wire" "$tmp/tree/tooling/wire" + cp "$root/$dir/wrangler.template.jsonc" "$root/$dir/wiring.fixture.json" "$tmp/tree/$dir/" + run_render() { # ENV [KEY=VALUE…] — the render as the lane runs it, with only the given wiring in env + local env="$1"; shift + (cd "$tmp/tree/$dir" && env -i PATH="$PATH" HOME="$HOME" ORUN_ENVIRONMENT="$env" "$@" bash -c "$render") + } + for env in $envs; do + rm -f "$tmp/tree/$dir/wrangler.jsonc" + docs=(); ids=() + for pair in $(python3 -c " +import json,sys +d=json.load(open(sys.argv[1]))['deployables'][int(sys.argv[2])]; pubs=json.load(open(sys.argv[1]))['publishers'] +for comp in sorted({c for c,_ in d['tokens']}): + if sys.argv[3] in pubs[comp]['envs']: print(pubs[comp]['key']+'_'+sys.argv[3].upper()+'|'+comp) +" "$tmp/facts.json" "$i" "$env"); do + key="${pair%%|*}"; comp="${pair#*|}" + id="e2e$(printf '%s' "$key" | md5sum | cut -c1-29)" + docs+=("$key=$(python3 -c " +import json,sys +d=json.load(open(sys.argv[1]))['deployables'][int(sys.argv[2])] +print(json.dumps({k: sys.argv[3] for c,k in d['tokens'] if c==sys.argv[4]}))" "$tmp/facts.json" "$i" "$id" "$comp")") + ids+=("$id") + done + if [ "${#docs[@]}" -gt 0 ]; then + # A deployed environment: the document wins, and without it the render refuses. + if run_render "$env" "${docs[@]}" > "$tmp/r.log" 2>&1 && grep -q "${ids[0]}" "$tmp/tree/$dir/wrangler.jsonc"; then + ok "$env renders from the published document (${#docs[@]} of them)" + else + bad "$env did not render from the published document"; sed 's/^/ /' "$tmp/r.log" >&2 + fi + rm -f "$tmp/tree/$dir/wrangler.jsonc" + if run_render "$env" > "$tmp/r.log" 2>&1; then + bad "$env rendered with no wiring document — a deploy would ship the fixture's placeholder id" + else + grep -q "${docs[0]%%=*}" "$tmp/r.log" && ok "$env without its document refuses, naming ${docs[0]%%=*}" \ + || { bad "$env refused without naming the missing document"; cat "$tmp/r.log" >&2; } + fi + else + # A verify-only environment: no root applies there, so the fixture. + if run_render "$env" > "$tmp/r.log" 2>&1; then + want="$(python3 -c " +import json,sys +d=json.load(open(sys.argv[1]))['deployables'][int(sys.argv[2])] +fx=json.load(open(sys.argv[3])) +c,k=d['tokens'][0]; print(fx[c+'/'+sys.argv[4]][k])" "$tmp/facts.json" "$i" "$root/$dir/wiring.fixture.json" "$env")" + grep -q "\"$want\"" "$tmp/tree/$dir/wrangler.jsonc" && grep -q 'verify-only' "$tmp/r.log" \ + && ok "$env (verify-only, no root applies) renders from the fixture, and says so" \ + || { bad "$env did not render the fixture's $env values"; cat "$tmp/r.log" >&2; } + else + bad "$env (verify-only) cannot render without a document no root publishes"; sed 's/^/ /' "$tmp/r.log" >&2 + fi + fi + done +done + +[ "$fail" -eq 0 ] || { echo "wire.test.sh: failure(s)" >&2; exit 1; } +echo "wire.test.sh: ok" diff --git a/tooling/bootstrap/dev-lanes.mjs b/tooling/bootstrap/dev-lanes.mjs new file mode 100755 index 0000000..27e4f84 --- /dev/null +++ b/tooling/bootstrap/dev-lanes.mjs @@ -0,0 +1,114 @@ +#!/usr/bin/env node +// The dev verify lanes stay off main's convergences while a product is being +// bootstrapped (zero-dependency). +// +// intent.yaml activates `dev` on `github-push-main` as well as on pull +// requests: every merge to main re-verifies every component (builds, tests) +// on the dev rung beside the stage and prod deploys. That is the right rule +// for a product that is live. During a bootstrap it proves nothing — the +// content comes from a pinned baseline whose own CI already ran it, and +// every phase's pull request is checked by `plan` alone — and it costs the +// one thing a bootstrap's wall-clock is made of: runner slots. The product's +// landing is a Next.js build per deployed environment; a third, on the dev +// rung (and its tests beside it), re-proves what the baseline's own CI +// already proved and competes with stage and prod for the runner pool. +// (Measured on the Cirrus baseline, where this tool comes from: dev took +// eight of eighteen lanes and stage and prod got five each.) +// +// So 01-product defers the trigger and 02-docs, the last landing, puts it +// back, exactly as tooling/bootstrap/promotion.mjs does for prod's gate: +// +// node tooling/bootstrap/dev-lanes.mjs --defer # 01-product, before the first landing +// node tooling/bootstrap/dev-lanes.mjs --restore # 02-docs, the last landing +// node tooling/bootstrap/dev-lanes.mjs --check # prints deferred | active +// +// --defer replaces dev's `- github-push-main` trigger line with one marker +// comment that base64-encodes the exact text removed, so --restore +// reproduces intent.yaml byte-for-byte. Both are idempotent. Pull requests +// keep their dev lanes throughout: only the push-to-main activation moves. +// +// The trigger is deferred, never dropped: a bootstrap that stops before +// 02-docs leaves the marker in intent.yaml, and `--restore` (or a re-run of +// 02-docs) is the whole fix. +import * as fs from "node:fs"; + +const FILE = process.argv.includes("--file") + ? process.argv[process.argv.indexOf("--file") + 1] + : "intent.yaml"; +const MARKER = "@dev-lanes-deferred"; +const TRIGGER = "github-push-main"; + +function usage() { + console.error("usage: dev-lanes.mjs --defer | --restore | --check [--file intent.yaml]"); + process.exit(2); +} + +// The `- github-push-main` line under environments.dev.activation.triggerRefs. +function findDevPushTrigger(text) { + const lines = text.split("\n"); + let inEnvs = false; + let devIndent = -1; + let inDev = false; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (/^environments:\s*$/.test(line)) { + inEnvs = true; + continue; + } + if (!inEnvs) continue; + if (/^\S/.test(line) && line.trim() !== "") break; // left the section + const env = /^(\s+)([A-Za-z0-9_-]+):\s*$/.exec(line); + if (env && (devIndent < 0 || env[1].length <= devIndent)) { + inDev = env[2] === "dev"; + if (inDev) devIndent = env[1].length; + continue; + } + if (!inDev) continue; + if (new RegExp(`^\\s+-\\s+${TRIGGER}\\s*$`).test(line)) return { lines, index: i }; + } + return { lines, index: -1 }; +} + +function defer() { + const text = fs.readFileSync(FILE, "utf8"); + if (text.includes(`# ${MARKER}:`)) { + console.log(`dev-lanes --defer: already deferred in ${FILE}`); + return; + } + const { lines, index } = findDevPushTrigger(text); + if (index < 0) { + console.log(`dev-lanes --defer: dev is not activated on ${TRIGGER} in ${FILE} — nothing to defer`); + return; + } + const original = lines[index]; + const indent = /^(\s*)/.exec(original)[1]; + const b64 = Buffer.from(original, "utf8").toString("base64"); + const marker = `${indent}# ${MARKER}:${b64} (tooling/bootstrap/dev-lanes.mjs --restore puts it back)`; + const out = [...lines.slice(0, index), marker, ...lines.slice(index + 1)].join("\n"); + fs.writeFileSync(FILE, out); + console.log(`dev-lanes --defer: dev's verify lanes stay off main's convergences until --restore (${FILE})`); +} + +function restore() { + const text = fs.readFileSync(FILE, "utf8"); + const re = new RegExp(`^[ \\t]*# ${MARKER}:([A-Za-z0-9+/=]+) \\(tooling/bootstrap/dev-lanes\\.mjs --restore puts it back\\)$`, "m"); + const m = re.exec(text); + if (!m) { + console.log(`dev-lanes --restore: nothing deferred in ${FILE}`); + return; + } + const original = Buffer.from(m[1], "base64").toString("utf8"); + fs.writeFileSync(FILE, text.slice(0, m.index) + original + text.slice(m.index + m[0].length)); + console.log(`dev-lanes --restore: dev verifies every merge to main again (${FILE})`); +} + +function check() { + const text = fs.readFileSync(FILE, "utf8"); + console.log(text.includes(`# ${MARKER}:`) ? "deferred" : "active"); +} + +const mode = process.argv[2]; +if (mode === "--defer") defer(); +else if (mode === "--restore") restore(); +else if (mode === "--check") check(); +else usage(); diff --git a/tooling/bootstrap/promotion.mjs b/tooling/bootstrap/promotion.mjs new file mode 100644 index 0000000..ec8f4f5 --- /dev/null +++ b/tooling/bootstrap/promotion.mjs @@ -0,0 +1,123 @@ +#!/usr/bin/env node +// Stage and prod deploy side by side while a product is being bootstrapped +// (zero-dependency). +// +// intent.yaml gates prod behind stage: `environments.prod.promotion.dependsOn: +// [stage]`, which orun plans as an in-run edge from every prod job to the +// same component's stage job. That is the right rule for a product that is +// live — a change reaches prod only after it deployed to stage. During a +// bootstrap it protects nothing (both environments are empty, and every phase +// is watched to green before the next one starts) and it doubles the length +// of every convergence: each worker's prod deploy waits out its stage deploy. +// +// So 01-product defers the gate and 02-docs, the last landing, puts it back: +// +// node tooling/bootstrap/promotion.mjs --defer # 01-product, before the first landing +// node tooling/bootstrap/promotion.mjs --restore # 02-docs, the last landing +// node tooling/bootstrap/promotion.mjs --check # prints deferred | enforced +// +// --defer replaces the prod `promotion:` block with one marker comment that +// base64-encodes the exact text removed, so --restore reproduces intent.yaml +// byte-for-byte. Both are idempotent. Restoring is a change to intent.yaml's +// `environments` section only, which `orun plan --changed` (intent impact +// `watch`, the default) maps to no component: the landing that restores it +// deploys nothing. +// +// The gate is deferred, never dropped: a bootstrap that stops before 02-docs +// leaves the marker in intent.yaml, and `--restore` (or a re-run of 02-docs) +// is the whole fix. docs/phases/02-docs.md says so. + +import * as fs from "node:fs"; + +const FILE = process.argv.includes("--file") + ? process.argv[process.argv.indexOf("--file") + 1] + : "intent.yaml"; +const MARKER = "@promotion-deferred"; + +function usage() { + console.error("usage: promotion.mjs --defer | --restore | --check [--file intent.yaml]"); + process.exit(2); +} + +// The `promotion:` block of the `prod:` environment: from its `promotion:` +// line up to (not including) the next line indented at or above it. +function findProdPromotion(text) { + const lines = text.split("\n"); + let inEnvs = false; + let prodIndent = -1; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (/^environments:\s*$/.test(line)) { + inEnvs = true; + continue; + } + if (!inEnvs) continue; + if (/^\S/.test(line) && line.trim() !== "") break; // left the section + const prod = /^(\s+)prod:\s*$/.exec(line); + if (prod) { + prodIndent = prod[1].length; + continue; + } + if (prodIndent < 0) continue; + const indent = line.length - line.trimStart().length; + if (line.trim() !== "" && indent <= prodIndent) { + prodIndent = -1; // left prod without finding one + continue; + } + const m = /^(\s+)promotion:\s*$/.exec(line); + if (!m) continue; + const own = m[1].length; + let end = i + 1; + while (end < lines.length) { + const l = lines[end]; + if (l.trim() !== "" && l.length - l.trimStart().length <= own) break; + end++; + } + return { lines, start: i, end, indent: m[1] }; + } + return null; +} + +function defer() { + const text = fs.readFileSync(FILE, "utf8"); + if (text.includes(MARKER)) { + console.log(`promotion --defer: already deferred in ${FILE}`); + return; + } + const found = findProdPromotion(text); + if (!found) { + console.log(`promotion --defer: prod has no promotion block in ${FILE} — nothing to defer`); + return; + } + const { lines, start, end, indent } = found; + const removed = lines.slice(start, end).join("\n"); + const b64 = Buffer.from(removed, "utf8").toString("base64"); + const marker = `${indent}# ${MARKER}:${b64} (tooling/bootstrap/promotion.mjs --restore puts it back)`; + const out = [...lines.slice(0, start), marker, ...lines.slice(end)].join("\n"); + fs.writeFileSync(FILE, out); + console.log(`promotion --defer: prod no longer waits on stage until --restore (${FILE})`); +} + +function restore() { + const text = fs.readFileSync(FILE, "utf8"); + const re = new RegExp(`^[ \\t]*# ${MARKER}:([A-Za-z0-9+/=]+).*$`, "m"); + const m = re.exec(text); + if (!m) { + console.log(`promotion --restore: nothing deferred in ${FILE}`); + return; + } + const original = Buffer.from(m[1], "base64").toString("utf8"); + fs.writeFileSync(FILE, text.slice(0, m.index) + original + text.slice(m.index + m[0].length)); + console.log(`promotion --restore: prod waits on stage again (${FILE})`); +} + +function check() { + const text = fs.readFileSync(FILE, "utf8"); + console.log(text.includes(MARKER) ? "deferred" : "enforced"); +} + +const mode = process.argv[2]; +if (mode === "--defer") defer(); +else if (mode === "--restore") restore(); +else if (mode === "--check") check(); +else usage(); diff --git a/tooling/bootstrap/retouch.mjs b/tooling/bootstrap/retouch.mjs new file mode 100644 index 0000000..6cc76fc --- /dev/null +++ b/tooling/bootstrap/retouch.mjs @@ -0,0 +1,254 @@ +#!/usr/bin/env node +// Give a re-run phase something to land (zero-dependency). +// +// A phase lands as a pull request and is verified by the convergence run that +// follows the merge. When that convergence FAILS — a provider error, a runner +// starved out, a smoke that raced route propagation past its retries — the +// merge has already happened, so every file the phase places is on main. orun +// derives phase state from the files on disk (never from a stored record), so +// a retried build finds the phase placed, and even a forced re-run of it +// produces an EMPTY diff: `orun.pr/land@v1` has nothing to commit, and the +// product's CI (`orun plan --changed`) deploys a component only when one of +// its files changed in the push. Nothing lands, nothing redeploys, and the +// operator is told the phase is fine. +// +// This tool is what the phase's `retouch` hook runs before it stages and +// lands: for each component the phase deploys, it rewrites ONE trailing line +// in that component's `component.yaml`, +// +// # orun: redeploy +// +// replacing the previous marker if there is one (never accumulating), so the +// landing has a diff and exactly those components are in the changed set. The +// same convention was hand-edited before this existed (`# ci: re-trigger +// deploy …` 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 cloudflare-kv,web,web-tests +// +// Options: +// --phase the phase the marker names (required) +// --components a,b,c the components to touch, by `metadata.name` … +// --affects … or read them from a TaskContract's `spec.affects` +// --check resolve every component and exit non-zero naming +// any without a component.yaml; write nothing +// --dry-run print what would change; write nothing +// +// The stamp is ORUN_RUN_ID if set, else ORUN_SESSION_ID, else a UTC timestamp +// (YYYYMMDDTHHMMSSZ) — whichever identifies the run that asked for the deploy. +// +// Runs in the product checkout (the phase hooks' working directory). A +// component is found by the `metadata.name` its component.yaml declares, not +// by directory: `apps/web` and `tests/web` both carry one, and only the +// first is named `web`. + +import * as fs from "node:fs"; +import * as path from "node:path"; + +const MARKER_RE = /^# orun: redeploy \S+ \S+\r?$/; +const SKIP_DIRS = new Set(["node_modules", ".git", ".orun", "dist", ".next", ".open-next", ".turbo"]); +const MAX_DEPTH = 4; + +function usage(msg) { + if (msg) console.error(`retouch: ${msg}`); + console.error( + "usage: retouch.mjs --phase (--components a,b,c | --affects ) [--check] [--dry-run]", + ); + process.exit(2); +} + +function parseArgs(argv) { + const opts = { phase: null, components: null, affects: null, check: false, dryRun: false }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + const next = () => { + if (i + 1 >= argv.length) usage(`${a} needs a value`); + return argv[++i]; + }; + if (a === "--phase") opts.phase = next(); + else if (a === "--components") opts.components = next(); + else if (a === "--affects") opts.affects = next(); + else if (a === "--check") opts.check = true; + else if (a === "--dry-run") opts.dryRun = true; + else if (a === "-h" || a === "--help") usage(); + else usage(`unknown argument ${a}`); + } + if (!opts.phase) usage("--phase is required"); + if (/\s/.test(opts.phase)) usage("--phase must be a single token"); + if (!opts.components && !opts.affects) usage("one of --components or --affects is required"); + if (opts.components && opts.affects) usage("--components and --affects are exclusive"); + return opts; +} + +// `spec.affects` from a TaskContract, with a reader small enough to need no +// YAML dependency: the contracts are a flat mapping with one block sequence. +// Accepts the block form (`affects:` then `- name` lines indented under it) +// and the flow form (`affects: [a, b]`). +function readAffects(file) { + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch (e) { + console.error(`retouch: cannot read ${file}: ${e.message}`); + process.exit(1); + } + const lines = text.split(/\r?\n/); + const names = []; + for (let i = 0; i < lines.length; i++) { + const m = /^(\s*)affects:\s*(.*?)\s*$/.exec(lines[i]); + if (!m) continue; + const indent = m[1].length; + const inline = m[2].replace(/\s+#.*$/, ""); + if (inline.startsWith("[")) { + const body = inline.replace(/^\[/, "").replace(/\]\s*$/, ""); + for (const part of body.split(",")) { + const v = part.trim().replace(/^["']|["']$/g, ""); + if (v) names.push(v); + } + break; + } + for (let j = i + 1; j < lines.length; j++) { + const line = lines[j]; + if (/^\s*(#.*)?$/.test(line)) continue; + const lead = /^(\s*)/.exec(line)[1].length; + if (lead <= indent) break; + const item = /^\s*-\s*(.+?)\s*$/.exec(line); + if (!item) break; + names.push(item[1].replace(/\s+#.*$/, "").replace(/^["']|["']$/g, "")); + } + break; + } + if (names.length === 0) { + console.error(`retouch: ${file} declares no spec.affects — nothing to touch`); + process.exit(1); + } + return names; +} + +// `metadata.name` from a component.yaml, read the same minimal way. +function componentName(file) { + const lines = fs.readFileSync(file, "utf8").split(/\r?\n/); + for (let i = 0; i < lines.length; i++) { + const m = /^(\s*)metadata:\s*$/.exec(lines[i]); + if (!m) continue; + const indent = m[1].length; + for (let j = i + 1; j < lines.length; j++) { + const line = lines[j]; + if (/^\s*(#.*)?$/.test(line)) continue; + const lead = /^(\s*)/.exec(line)[1].length; + if (lead <= indent) break; + const nm = /^\s*name:\s*(.+?)\s*$/.exec(line); + if (nm && lead === indent + 2) return nm[1].replace(/^["']|["']$/g, ""); + } + } + return null; +} + +// Every component.yaml in the tree, by the name it declares. +function indexComponents(root) { + const byName = new Map(); + const walk = (dir, depth) => { + let entries; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const ent of entries) { + const full = path.join(dir, ent.name); + if (ent.isDirectory()) { + if (SKIP_DIRS.has(ent.name) || depth >= MAX_DEPTH) continue; + walk(full, depth + 1); + } else if (ent.name === "component.yaml") { + const name = componentName(full); + if (!name) continue; + const rel = path.relative(root, full); + if (byName.has(name)) { + console.error( + `retouch: two component.yaml files declare metadata.name ${name}: ${byName.get(name)} and ${rel}`, + ); + process.exit(1); + } + byName.set(name, rel); + } + } + }; + walk(root, 0); + return byName; +} + +function stamp() { + for (const key of ["ORUN_RUN_ID", "ORUN_SESSION_ID"]) { + const v = (process.env[key] || "").trim(); + if (v) return v.replace(/\s+/g, "-"); + } + return new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z"); +} + +// The file with exactly one marker line, last, and a trailing newline. Every +// other byte is kept as it was. +function retouched(text, marker) { + const hadTrailingNewline = text.endsWith("\n"); + const lines = text.split("\n"); + if (hadTrailingNewline) lines.pop(); + const kept = lines.filter((l) => !MARKER_RE.test(l)); + // A file that was only a marker, or empty, still ends up valid. + const body = kept.length ? kept.join("\n") + "\n" : ""; + return body + marker + "\n"; +} + +function main() { + const opts = parseArgs(process.argv.slice(2)); + const root = process.cwd(); + const wanted = opts.components + ? opts.components.split(",").map((s) => s.trim()).filter(Boolean) + : readAffects(opts.affects); + if (wanted.length === 0) usage("no components named"); + + const index = indexComponents(root); + const missing = wanted.filter((n) => !index.has(n)); + if (missing.length) { + console.error( + `retouch: no component.yaml declares metadata.name for: ${missing.join(", ")} (looked under ${root})`, + ); + process.exit(1); + } + if (opts.check) { + for (const n of wanted) console.log(`retouch --check: ${n} -> ${index.get(n)}`); + console.log(`retouch --check: ${wanted.length} component(s) resolve.`); + return; + } + + const marker = `# orun: redeploy ${opts.phase} ${stamp()}`; + const verb = opts.dryRun ? "would" : ""; + let changed = 0; + for (const n of wanted) { + const rel = index.get(n); + const file = path.join(root, rel); + const before = fs.readFileSync(file, "utf8"); + const after = retouched(before, marker); + const had = before.split("\n").some((l) => MARKER_RE.test(l)); + if (after === before) { + console.log(`retouch: ${rel}: unchanged (marker already ${marker.slice(2)})`); + continue; + } + if (!opts.dryRun) fs.writeFileSync(file, after); + changed++; + console.log(`retouch: ${rel}: ${verb ? "would " : ""}${had ? "replace" : "add"} marker`); + } + console.log( + opts.dryRun + ? `retouch --dry-run: ${changed} of ${wanted.length} file(s) would change; nothing written.` + : changed > 0 + ? `retouch: ${changed} of ${wanted.length} component.yaml file(s) marked "${marker.slice(2)}" — the landing has a diff.` + : `retouch: nothing to do (every marker already current).`, + ); +} + +main(); diff --git a/tooling/bootstrap/work-tree.mjs b/tooling/bootstrap/work-tree.mjs new file mode 100644 index 0000000..ad48ba6 --- /dev/null +++ b/tooling/bootstrap/work-tree.mjs @@ -0,0 +1,73 @@ +#!/usr/bin/env node +// A product carries no work tree of the baseline's (zero-dependency). +// +// This repository's intent.yaml declares where ITS work lives: +// +// work: +// epics: specs/epics +// tasks: tasks +// sync: on-merge +// +// and `orun plan` on main reconciles that tree into the workspace's work +// plane. A product built from this baseline has neither directory — `specs/` and +// `tasks/` are the factory's, and the leak gate keeps them out — and its +// bootstrap work is opened on the platform by the build itself. Left in, the +// block would point the product's every plan at two directories that do not +// exist. +// +// So 01-product removes it from the product's copy, before the first landing: +// +// node tooling/bootstrap/work-tree.mjs --strip # 01-product +// node tooling/bootstrap/work-tree.mjs --check # prints declared | absent +// +// The block removed is the top-level `work:` key with everything indented +// under it, and the comment lines directly above it that belong to it. It is +// not put back: a product that wants a work tree declares its own. Idempotent. +import * as fs from "node:fs"; + +const FILE = process.argv.includes("--file") + ? process.argv[process.argv.indexOf("--file") + 1] + : "intent.yaml"; + +function usage() { + console.error("usage: work-tree.mjs --strip | --check [--file intent.yaml]"); + process.exit(2); +} + +function findWork(lines) { + const start = lines.findIndex((l) => /^work:\s*(#.*)?$/.test(l)); + if (start < 0) return null; + let end = start + 1; + while (end < lines.length && (lines[end].trim() === "" || /^\s/.test(lines[end]))) end++; + // Trailing blank lines belong to the gap before the next key, not the block. + while (end > start + 1 && lines[end - 1].trim() === "") end--; + // Its own comment: the contiguous `#` lines directly above it. + let from = start; + while (from > 0 && /^#/.test(lines[from - 1])) from--; + return { from, end }; +} + +function strip() { + const text = fs.readFileSync(FILE, "utf8"); + const lines = text.split("\n"); + const found = findWork(lines); + if (!found) { + console.log(`work-tree --strip: ${FILE} declares no work tree — nothing to do`); + return; + } + let { from, end } = found; + // Drop one of the blank lines that separated it from its neighbours. + if (end < lines.length && lines[end].trim() === "" && from > 0 && lines[from - 1].trim() === "") end++; + fs.writeFileSync(FILE, [...lines.slice(0, from), ...lines.slice(end)].join("\n")); + console.log(`work-tree --strip: removed the baseline's work tree from ${FILE}`); +} + +function check() { + const lines = fs.readFileSync(FILE, "utf8").split("\n"); + console.log(findWork(lines) ? "declared" : "absent"); +} + +const mode = process.argv[2]; +if (mode === "--strip") strip(); +else if (mode === "--check") check(); +else usage(); diff --git a/tooling/rebrand/rebrand.mjs b/tooling/rebrand/rebrand.mjs new file mode 100644 index 0000000..72b10e3 --- /dev/null +++ b/tooling/rebrand/rebrand.mjs @@ -0,0 +1,472 @@ +#!/usr/bin/env node +// Rebrand renamer for the strapi-launchpad baseline (zero-dependency). +// +// This repository is a baseline: a product is instantiated from it, branded, +// and deployed as somebody's own marketing site. This script rewrites every +// *instance identity* literal in the product tree — repo slug (which also +// names the R2 bucket names, the Worker's self-reference binding and the +// secret project), the site's display name, its source-repository link, 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). +// +// This baseline's slug, `strapi-launchpad`, is spelled only where it IS the +// identity: the repo-slug rule would rewrite it anywhere else into the +// product's slug. The template's own words — `Strapi` (its packages, the CMS +// it reads) and `LaunchPad` in the sample content — are not this identity +// and no rule touches them. +// +// The engine is generic; the identity is not. Everything specific to this +// tree is `.baseline/identity.json` (and the defaults below, which must equal +// it) plus the SITE_NAME seam in apps/web/lib/site.ts. +// +// 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 .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 [--dry-run] | --verify [--values ]"); + 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 ` 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 site's source link +const BASELINE_IDENTITY_FILE = + arg("baseline-identity") ?? + path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".baseline", "identity.json"); +const BASELINE_DEFAULTS = { + slug: "strapi-launchpad", + pascal: "StrapiLaunchpad", + productName: "LaunchPad", + domain: "strapi-launchpad.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 store goes live on workers.dev and an +// owner sets a domain later. Until then the reserved placeholder +// `.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://///` 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. +const PROTECTED = [ + /https:\/\/orun-api\.sourceplane\.ai/g, // orun state backend + /sourceplane\.io/g, // manifest apiVersion, owned by the orun tooling + /[A-Za-z0-9._%+-]+@sourceplane\.ai/g, // company mailboxes +]; +const MASK = (i, j) => `\u0000REBRAND_PROTECTED_${i}_${j}\u0000`; + +// ── Substituted values are opaque ────────────────────────────── +// +// The rules run in sequence over one buffer. 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`, 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 (`-`, the +// base being its `apps//` 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 links (the README and the docs). + // Before the repo-slug rule, which would otherwise rename only its tail + // and leave the link pointing at the baseline's owner. + [`github.com/${baseline.githubOwner}/${baseline.slug}`, `github.com/${githuborg}/${reponame}`, "source repository link"], + // The product domain wherever it is the product's (BASE_DOMAIN, docs). + // Before the repo-slug rule: the placeholder domain starts with the slug. + [baseline.domain, productdomain, "product domain"], + // The workers.dev subdomain (component parameters, build origin, intent + // environment URLs, docs). + [baseline.subdomain, subdomain, "workers.dev subdomain"], + ]; +} + +function regexPairs(files) { + const list = [ + // The display-name seam. JSON.stringify writes a valid TS string for any + // name the card's pattern admits (apostrophes and ampersands included). + { + re: new RegExp(`SITE_NAME = "${rx(baseline.productName)}"`, "g"), + replacement: () => `SITE_NAME = ${JSON.stringify(productname)}`, + label: "site name seam", + }, + // Secret refs: `secret:////…`. 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 `-` 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 +]; + +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" +}