diff --git a/.baseline/product/README.md b/.baseline/product/README.md index 4cb3fd4..d9b72d7 100644 --- a/.baseline/product/README.md +++ b/.baseline/product/README.md @@ -26,7 +26,8 @@ and how to operate it is in | The todo store: the visitor's list in one httpOnly cookie | `apps/web/src/data/todos.ts` | | The header and its navigation | `apps/web/src/components/Header.tsx` | | Workers build and deploy contract | `apps/web/vite.config.ts`, `apps/web/wrangler.jsonc`, `apps/web/component.yaml` | -| Tests (the site's name, the todo store) | `apps/web/src/**/*.test.ts` (vitest) | +| The Worker's entry, and who may frame the site | `apps/web/src/server.ts`, `apps/web/src/lib/framing.ts` | +| Tests (the site's name, the todo store, the framing policy) | `apps/web/src/**/*.test.ts` (vitest) | ## Getting started @@ -73,6 +74,26 @@ Cloudflare token and account id are brokered per run from the workspace's Cloudflare connection; nothing provider-shaped is stored in the repository or in GitHub. +**Before the site goes live.** A site whose code was built before its +Cloudflare account was connected deploys nothing yet: `intent.yaml` carries +a `# @deploys-deferred:…` marker where stage's and prod's +`- github-push-main` trigger goes, so a merge to `main` plans dev's verify +lane (the site built and dry-deployed) and nothing else, and its CI stays +green. Going live — connecting Cloudflare and running the build's live +stage — puts both lines back, writes your account's workers.dev subdomain +where a placeholder stood in for it, and deploys. + +**Who may frame the site.** On stage, every page the Worker renders says +who may show it in a frame: `Content-Security-Policy: frame-ancestors 'self' +https://orun-agent-web-stage.oruncloud.workers.dev +https://orun-agent-web-prod.oruncloud.workers.dev http://localhost:*` — +orun.work's preview pane, which shows the stage deploy, and orun.work run +locally. Prod sends no policy. The list is one map per environment in +`apps/web/src/lib/framing.ts`: edit it and merge, and the next deploy of +that environment sends it. (Each deploy lane tells its build which +environment it is for, as `DEPLOY_ENV`; `component.yaml` names the +variable.) + **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 diff --git a/.baseline/tasks/01-product.TaskContract.yaml b/.baseline/tasks/01-product.TaskContract.yaml deleted file mode 100644 index bc965e9..0000000 --- a/.baseline/tasks/01-product.TaskContract.yaml +++ /dev/null @@ -1,25 +0,0 @@ -# Task contract template for the 01-product landing. -# Unbound to a key on purpose: `orun.task/ensure@v1` seals and attaches it to -# the key the allocator issues. It lives under `.baseline/`, not `tasks/`, -# because `tasks/` is this repository's own work tree (`intent.yaml` `work:`), -# where an unkeyed contract is an error. gates: [] is a DECLARATION — merge -# alone finishes this task; the main convergence is the gate the bootstrap -# watches, not one the plane observes as a PR check. -# -# The whole site in one landing. `affects` names COMPONENTS, by -# metadata.name: the phase's retouch hook reads this list to decide which -# component.yaml files get the redeploy marker, so the deploy set and the task -# plane's statement of the work are one list. The site is one component — its -# test runs inside it (vitest in apps/web), so there is no separate test -# package to redeploy. -apiVersion: orun.io/v1 -kind: TaskContract -spec: - goal: The site's repository is born and linked, the whole site lands in one pull request, and one convergence builds it with Cloudflare's Vite plugin and deploys it to stage and prod, its tests green - affects: - - web - doneWhen: - - repo pushed, main pinned as default, workspace linked (orun cloud link) - - main convergence green (build, deploy and smoke on stage and prod) - - the home page answers on both workers.dev URLs - gates: [] diff --git a/.baseline/tasks/01-scaffold.TaskContract.yaml b/.baseline/tasks/01-scaffold.TaskContract.yaml new file mode 100644 index 0000000..d51d44f --- /dev/null +++ b/.baseline/tasks/01-scaffold.TaskContract.yaml @@ -0,0 +1,23 @@ +# Task contract template for the 01-scaffold 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; nothing deploys, so there is no convergence for +# the plane to observe. +# +# The whole site in one landing, GitHub only: the scaffold stage of a build +# that splits at a declared stage (blueprint.yaml `spec.stages`). `affects` +# names COMPONENTS, by metadata.name — the site is one component, and its test +# runs inside it (vitest in apps/web). +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The site's repository is born and linked, and the whole site lands in one pull request with its deploy lanes parked, so CI on main checks it and deploys nothing until the site goes live + affects: + - web + doneWhen: + - repo pushed, main pinned as default, workspace linked (orun cloud link) + - the whole site on main, branded, intent.yaml's stage and prod push activation deferred + - main's run green, planning no deploy + gates: [] diff --git a/.baseline/tasks/02-live.TaskContract.yaml b/.baseline/tasks/02-live.TaskContract.yaml new file mode 100644 index 0000000..cfed72d --- /dev/null +++ b/.baseline/tasks/02-live.TaskContract.yaml @@ -0,0 +1,19 @@ +# Task contract template for the 02-live landing. See 01-scaffold's header. +# +# The live stage: what 01-scaffold landed, deployed. `affects` names +# COMPONENTS, by metadata.name: the phase's retouch hook reads this list to +# decide which component.yaml files get the redeploy marker, so the deploy set +# and the task plane's statement of the work are one list. gates: [] — the +# main convergence is the gate the bootstrap watches, not one the plane +# observes as a PR check. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The site is bound to its Cloudflare account's workers.dev subdomain, its deploy credentials are minted from the workspace's connection, and one convergence builds it with Cloudflare's Vite plugin and deploys it to stage and prod + affects: + - web + doneWhen: + - no placeholder subdomain left in the site; CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID exist + - main convergence green (build, deploy and smoke on stage and prod) + - the home page answers on both workers.dev URLs + gates: [] diff --git a/.baseline/tasks/03-docs.TaskContract.yaml b/.baseline/tasks/03-docs.TaskContract.yaml index c8f2ba1..28a7f55 100644 --- a/.baseline/tasks/03-docs.TaskContract.yaml +++ b/.baseline/tasks/03-docs.TaskContract.yaml @@ -1,4 +1,4 @@ -# Task contract template for the 03-docs landing. See 01-product's header. +# Task contract template for the 03-docs landing. See 01-scaffold's header. apiVersion: orun.io/v1 kind: TaskContract spec: diff --git a/.github/workflows/baseline.yml b/.github/workflows/baseline.yml index 420017c..4e4e3db 100644 --- a/.github/workflows/baseline.yml +++ b/.github/workflows/baseline.yml @@ -41,11 +41,11 @@ jobs: # 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) + - name: Contract tests (manifest, phases, coverage, rebrand, retouch, bootstrap-defer, subdomain) run: | set -euo pipefail python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml - for t in manifest phases coverage rebrand retouch bootstrap-defer; do + for t in manifest phases coverage rebrand retouch bootstrap-defer subdomain; do echo "── $t" bash "testing/$t.test.sh" done @@ -65,8 +65,8 @@ jobs: # registry, compiles every `when` and narration template, and writes # nothing. Then the leak gate (what a site would carry) and the placement # tier (the offline bootstrap: every phase placed and finished by the - # blueprint's own hooks, then the site's own `orun plan` for the 01-product - # merge). + # blueprint's own hooks, then the site's own `orun plan` for each landing's + # merge; and a code-only build stopped after 01-scaffold, taken live later). blueprint: runs-on: ubuntu-latest steps: diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md index d41117c..04c235f 100644 --- a/BOOTSTRAP.md +++ b/BOOTSTRAP.md @@ -1,52 +1,74 @@ # BOOTSTRAP — a new site from this baseline, in phases How to go from **nothing** to a **TanStack Start site live on stage and prod, -documented**, with ONE provider consent. +documented**, with ONE provider consent — or, with no provider at all yet, to +the site's **code**, in its own repository, ready to go live later. 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 four minutes** — an estimate summed from the -phases (3 + 1) until a bootstrap measures it. The shape: the task set-up in -the background while ONE landing is placed, branded and checked in the box -(`orun validate` and `orun plan`, no runner waited for), one TanStack Start -build per environment (seconds, not minutes — the long poles are the -installs, the runners and a first deploy's workers.dev route), stage and prod -deployed side by side, then a short docs landing, checked the same way, that -restores the promotion gate. It is unmeasured: no live bootstrap of this -baseline has run yet. The sibling site baselines measured 7m07s–8m43s from -the console's Build over three landings; `01-product` dropped one landing and -the Checks waits (cirrus-baseline baseline-v22's shape), and orun v2.88.0's +brokered secrets, the programme and the two stages a build may stop between, +and `testing/manifest.test.sh` holds it to what the build document does. + +**Two stages** (`blueprint.yaml` `spec.stages`): the **scaffold**, +`01-scaffold`, needs GitHub only — the whole site placed, branded and landed +in a new repository, its deploy lanes parked so CI on `main` is green and +deploys nothing; the **live** stage, `02-live`, needs Cloudflare — the +workers.dev subdomain bound, the deploy credentials minted, the lanes put +back, one landing deployed to stage and prod, watched and probed. Then +`03-docs` records it. A build runs all three unless told to stop after the +scaffold, which is what an account with no Cloudflare connection gets: a +**code-only** site. + +Target wall-clock: **about five minutes** for a full build — an estimate +summed from the phases (1 + 3 + 1) until a bootstrap measures it. The shape: +the task set-up in the background while the scaffold's landing is placed, +branded and checked in the box (`orun validate` and `orun plan`, no runner +waited for) and merged with nothing to deploy; then the live landing, whose +merge builds the site once per environment (seconds, not minutes — the long +poles are the installs, the runners and a first deploy's workers.dev route) +and deploys stage and prod side by side; then a short docs landing, checked +the same way, that restores the promotion gate. It is unmeasured: no live +bootstrap of this baseline has run yet. The sibling site baselines measured +7m07s–8m43s from the console's Build over three landings; the one-landing +shape this replaced (`baseline-v1`'s `01-product`, cirrus-baseline +baseline-v22's) dropped a landing and the Checks waits, and orun v2.88.0's fast shape took about a minute out of turso-starter's measured build — the -same minute is assumed here. +same minute is assumed here. The split pays for one landing back (the +scaffold's: about a minute) and nothing else: its merge deploys nothing, so +no convergence is waited on twice. ## 0. What you need - GitHub org access (repository creation) and a machine with `git`, `node` (≥ 22), `pnpm` (10.12.1), `python3` with PyYAML, `curl`, and the `orun` CLI **≥ v2.88.0** — the floor for RUNNING the bootstrap (the phase overlay, - landings that commit per phase, `githubOwner` on the doctor probe, a probe - deferred for a project not yet created, `from: workspace`, the deploy - credentials minted in one `secrets` reconcile, the task set-up run in the - background (`background: true`), and landings checked in the box before - they merge (`checks: local`)). The site's own `ci.yml` pins its lanes - separately (v2.78.4). -- A Cloudflare account (the free plan is enough for one Worker with static - assets) and its **Account API token** with Workers Scripts Write (the - console's Connect recipe lists the exact permission groups). It is the ONLY - provider credential this baseline needs. + landings that commit per phase, a probe deferred until the phase that + needs it, `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`)). A code-only site taken live **in the container that + built its scaffold** also needs the orun that reads `lateBound` (v2.90.0): + older ones refuse the real subdomain as an input conflict with the + placeholder they recorded (a fresh container has no record, and works on + the floor). The site's own `ci.yml` pins its lanes separately (v2.78.4). +- For the live stage: a Cloudflare account (the free plan is enough for one + Worker with static assets) and its **Account API token** with Workers + Scripts Write (the console's Connect recipe lists the exact permission + groups). It is the ONLY provider credential this baseline needs, and the + scaffold stage does not need it at all. - An Orun Cloud workspace for the site — `orunWorkspace`, or the workspace the build runs in (ORUN_WORKSPACE) when that is unset — with an **admin-role API key** for headless runs (secret writes below admin are masked as `not_found`). - **The repository allow-listed in the workspace** (console → Settings → Git - repos), unless the credential can write links. `01-product`'s `link` step - stops and names the fix if it is not. + repos), unless the credential can write links. `01-scaffold`'s `link` step + stops and names the fix if it is not — it is the build's GitHub check: a + linked repository is one the platform sees through the GitHub App, and the + scaffold asks for no connection row (a repository in orun.work's managed + GitHub org has none in the workspace). ## 1. One command: `--resume` @@ -71,6 +93,26 @@ with `orun baseline new --from bst_…`, never asks for it: the platform reads it from the workspace's Cloudflare connection, the same one the deploy token is minted from. Only a hand-run build like this one passes it. +**Code only, then live.** With no Cloudflare account yet, stop after the +scaffold and leave the subdomain out — it is **late-bound**, and the tree +carries the placeholder `your-workers-subdomain` until the site goes live: + +```bash +orun new --blueprint repo-blueprint.yaml \ + --out ~/sites/acme-notes --run-hooks --until 01-scaffold \ + --set reponame=acme-notes --set productname="Acme Notes" \ + --set githuborg=acme-inc --set orunWorkspace=ws_XXXXXXXX +``` + +The repository, its CI (dev's verify lane on every merge; every lane on a +pull request) and its pull requests all work; nothing deploys. To go live, +run the same `--resume` command as above, with the account's `subdomain`: +it finds `01-scaffold` placed and runs `02-live` and `03-docs`. (This is what +the platform's go-live does: a resume with no stop.) Only a run that stops +before the last phase may keep the placeholder — the orun that reads +`lateBound` refuses any other before it writes a byte, and `02-live`'s +`subdomain` hook refuses it on any orun. + **`--run-hooks` is the difference between placing files and bootstrapping a site.** Without it `orun new` writes the tree and stops: no repository, no landing, no convergence watch, no probe. That is deliberate — it is what @@ -84,17 +126,21 @@ phase whose files are present but branded derives as `drifted`, and ## 1b. Or phase by phase -| phase | what it lands | verified by | -|---|---|---| -| `01-product` | the repository, created and linked; the brokered Cloudflare secrets; then the whole site in one PR — intent, CI, tooling, identity, `apps/web` (the site and its tests) | its commit validated and planned in the box (as the PR and as the merge), then merged; the convergence green (build, deploy, smoke) and both workers.dev URLs answering | -| `03-docs` | `ai/context/deployment.md` from probed facts; prod's promotion gate and dev's push lanes restored | the render's own probes, recorded; the commit checked in the box and merged | +| stage | phase | what it lands | verified by | +|---|---|---|---| +| scaffold | `01-scaffold` | the repository, created and linked; then the whole site in one PR — intent, CI, tooling, identity, `apps/web` (the site and its tests) — with stage's and prod's deploy lanes parked | its commit validated and planned in the box (as the PR and as the merge), then merged; main's run plans dev's verify lane and deploys nothing | +| live | `02-live` | the workers.dev subdomain bound; the deploy lanes put back; the brokered Cloudflare secrets; one PR whose merge deploys | the convergence green (build, deploy, smoke) and both workers.dev URLs answering | +| | `03-docs` | `ai/context/deployment.md` from probed facts; prod's promotion gate and dev's push lanes restored | the render's own probes, recorded; the commit checked in the box and merged | ```bash orun new --blueprint repo-blueprint.yaml --out ~/sites/acme-notes --run-hooks \ - --phase 01-product --values ~/acme-notes.values.yaml -# … then 03-docs + --until 01-scaffold --values ~/acme-notes.values.yaml +# … then --phase 02-live (with the subdomain), then --phase 03-docs ``` +The first phase is selected with `--until`: it selects the same one phase, and +it is the selection that may run without the late-bound subdomain. + Every later phase reads the identity back from `.rebrand/values.json` in the placed tree, but the blueprint's **required** inputs — `reponame`, `productname`, `githuborg` — are validated before anything runs, so pass them @@ -109,7 +155,7 @@ The full guide, one page per phase: [docs/phases/README.md](docs/phases/README.m |---|---| | `--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 | +| `--until ` | places every phase through that one and stops — `--until 01-scaffold` is a code-only build | What lands in the site is PRODUCT-ONLY: the app (its tests inside it), its CI, its tooling, its README and its two context pages. None of this @@ -140,7 +186,7 @@ orun new --blueprint repo-blueprint.yaml \ | requirement | detail | |---|---| -| `GITHUB_TOKEN` | fine-grained PAT: **read** on this repository; on the SITE's repository **contents write**, **pull-requests write**, **actions read+write** (`orun.run/watch@v1` resumes runs with `gh run rerun`), **checks read**; **repository create** on the owner if `01-product` creates it (or pre-create it — supported) | +| `GITHUB_TOKEN` | fine-grained PAT: **read** on this repository; on the SITE's repository **contents write**, **pull-requests write**, **actions read+write** (`orun.run/watch@v1` resumes runs with `gh run rerun`), **checks read**; **repository create** on the owner if `01-scaffold` 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 | @@ -149,6 +195,15 @@ orun new --blueprint repo-blueprint.yaml \ - **Write**: the pages are `apps/web/src/routes/` (TanStack Router writes `src/routeTree.gen.ts` from them); the site's name is `apps/web/src/lib/site.ts`. Every merge to `main` redeploys. +- **Framing**: the stage Worker sends `Content-Security-Policy: + frame-ancestors 'self' https://orun-agent-web-stage.oruncloud.workers.dev + https://orun-agent-web-prod.oruncloud.workers.dev http://localhost:*`, so + orun.work's preview pane (and orun.work run locally) can show the stage + deploy in an iframe; prod and dev send no policy. The list is one map in + `apps/web/src/lib/framing.ts`, per environment; each lane's build is told + its environment (`DEPLOY_ENV`, `environmentBuildVar` in + `apps/web/component.yaml`), so a change reaches an environment with its + next deploy. - **The todos**: each visitor's list lives in their own httpOnly cookie (`apps/web/src/data/todos.ts`), so the site depends on no third party. To share a list across devices, swap the cookie for a KV namespace. @@ -165,7 +220,7 @@ orun new --blueprint repo-blueprint.yaml \ each runs locally the same way: ```bash -for t in manifest phases coverage rebrand retouch bootstrap-defer; do bash testing/$t.test.sh; done +for t in manifest phases coverage rebrand retouch bootstrap-defer subdomain; do bash testing/$t.test.sh; done bash testing/leak.test.sh # needs orun bash testing/placement.test.sh # needs orun, node, pnpm: the offline bootstrap bash testing/e2e.test.sh # + network for pnpm: the site built, dry-deployed and served @@ -174,8 +229,11 @@ bash testing/e2e.test.sh # + network for pnpm: the site built, dry-deplo The offline bootstrap (`testing/lib/bootstrap.sh`) places every phase in order and finishes each with the blueprint's OWN `run:` hooks — read out of `repo-blueprint.yaml`, not transcribed — so the rebrand, the re-tenant, the -deferrals and their restore, the retouch marker and the deployment record -all run exactly as a real bootstrap runs them. Only the +deferrals and their restore, the subdomain bound, the retouch marker and the +deployment record all run exactly as a real bootstrap runs them. The +placement tier runs it twice: a full build, and a code-only one stopped after +`01-scaffold` with no subdomain and taken live later — which must end on the +full build's tree, byte for byte. Only the platform's typed actions (task, repo, link, land, watch, probe, reconcile) are stood in for, a landing becoming a commit. @@ -199,17 +257,20 @@ at the tag and refuses the whole catalogue if it 404s. | 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` stops at `link` | the repository is not linked to the workspace and the credential cannot link it. Allow-list it (console → Settings → Git repos) and re-run the phase | -| `01-product` waits on the `providers` probe, then stops | Cloudflare is not connected. Connect it (console → Integrations), then re-run the phase — the probe is a wait, not a failure | +| `01-scaffold` stops at `link` | the repository is not linked to the workspace and the credential cannot link it — or the GitHub App is not installed on `githuborg`. Install it (console → Integrations → GitHub), allow-list the repo (console → Settings → Git repos) and re-run the phase | +| `02-live` waits on the `providers` probe, then stops | Cloudflare is not connected. Connect it (console → Integrations), then re-run — the probe is a wait, not a failure, and the site's code is already on `main` | +| A code-only site deploys nothing after a merge | expected: `intent.yaml` carries two `# @deploys-deferred:…` markers until `02-live` restores them. A manual deploy of stage or prod is refused (`environment stage is not activated by trigger github-push-main`) for the same reason | +| `subdomain --bind: … was given the placeholder` (or orun: `Only a run --until stops before the build's last phase … may keep a placeholder`) | the run reaches `02-live` with no workers.dev subdomain. Pass `--set subdomain=…`, or stop with `--until 01-scaffold` | +| `input conflict … subdomain: recorded "your-workers-subdomain", given "acme"` | a code-only site taken live in the container that built it, on an orun older than v2.90.0. Use v2.90.0, or a fresh container (the record is `.orun/`, which no checkout carries) | | Secret WRITE fails `not_found` while listings work | the API key's role is below admin; re-mint it with the admin role | -| Deploy lane: Authentication error (10000) | the connection's token lacks Workers Scripts Write; re-issue it, re-connect, re-run `01-product` | +| Deploy lane: Authentication error (10000) | the connection's token lacks Workers Scripts Write; re-issue it, re-connect, re-run `02-live` | | `land` stops: `the landing's own check failed — orun plan for …` | the site's tree does not plan — the line after it is orun's own error (an unknown component type, a composition that does not resolve). Nothing was pushed. Fix the tree (or the baseline) and re-run the phase | | `land` waits on CI after all | the site's repository requires a status check on `main` (branch protection or a ruleset), so GitHub refused the early merge; the landing waits for the check as a `checks: ci` landing would, then merges | -| Convergence failed AFTER the PR merged; re-running lands nothing | expected on its own — the files are on main. Re-run the phase (`--phase 01-product`, `--redo 01-product`, or the console's Retry): its `retouch` hook gives the landing a diff and the site redeploys | -| The site's `intent.yaml` says `workspace: ws_SET_ME` | `orunWorkspace` was empty and the build ran outside a workspace; set it and re-run `01-product` | -| A bootstrap stopped before `03-docs`; prod no longer waits on stage | the gate is deferred, not dropped: run `03-docs`, or `node tooling/bootstrap/promotion.mjs --restore --file /intent.yaml` | +| Convergence failed AFTER the PR merged; re-running lands nothing | expected on its own — the files are on main. Re-run the phase (`--phase 02-live`, `--redo 02-live`, or the console's Retry): its `retouch` hook gives the landing a diff and the site redeploys | +| The site's `intent.yaml` says `workspace: ws_SET_ME` | `orunWorkspace` was empty and the build ran outside a workspace; set it and re-run `01-scaffold` | +| A bootstrap stopped before `03-docs`; prod no longer waits on stage | the gate is deferred, not dropped: run `03-docs`, or `node tooling/bootstrap/promotion.mjs --restore --file /intent.yaml` (and `dev-lanes.mjs --restore`) | | `✕ input "productname" is required` | all three required inputs (`reponame`, `productname`, `githuborg`) must be set on every invocation, single-phase ones included | | `unknown flag: --phase`, `has no parameter "checks"`, `has no parameter "secrets"` or another parse error in the blueprint | the CLI is below the v2.88.0 floor | -| `01-product` lanes fail in `build-app` resolving a dependency | the site's intent no longer pins stack-tectonic 0.19.0. 0.20.0's lane-scoped install links each job's node_modules out of its staged tree; this site's Vite build has not been tried there, a Next.js sibling's did not build there, and the pin keeps the install the e2e tier proves. `intent.yaml` says why | -| `01-product`'s convergence reported green, then `verify` got 404 from both URLs | a second workflow ran on the push to main and the watch took its run. Only `ci.yml` may run on a push to main, and a site carries no other workflow (`testing/coverage.test.sh` holds the rule); read the CI run on main for the real result | +| `02-live` lanes fail in `build-app` resolving a dependency | the site's intent no longer pins stack-tectonic 0.19.0. 0.20.0's lane-scoped install links each job's node_modules out of its staged tree; this site's Vite build has not been tried there, a Next.js sibling's did not build there, and the pin keeps the install the e2e tier proves. `intent.yaml` says why | +| `02-live`'s convergence reported green, then `verify` got 404 from both URLs | a second workflow ran on the push to main and the watch took its run. Only `ci.yml` may run on a push to main, and a site carries no other workflow (`testing/coverage.test.sh` holds the rule); read the CI run on main for the real result | +| orun.work's preview pane opens the stage URL in a new tab instead of framing it | the stage Worker sends no `frame-ancestors` naming orun.work: the deploy predates this baseline's framing policy, or `DEPLOY_ENV` did not reach the build (`turbo.json`'s `env`, the component's `environmentBuildVar`). `curl -sI ` shows the header | diff --git a/README.md b/README.md index ff0b9af..e4bd07c 100644 --- a/README.md +++ b/README.md @@ -29,12 +29,21 @@ orun new --blueprint repo-blueprint.yaml --out ~/sites/acme-notes --run-hooks -- ``` Or, once the platform's registry lists it, from the Orun console (Baselines → -`tanstack-start` → Build). Two phases — `01-product` (the repository -created, then the whole site in one pull request, deployed to stage and prod -and smoke-tested) and `03-docs` (the live deployment recorded) — each landing -one pull request in the new repository. **[BOOTSTRAP.md](BOOTSTRAP.md)** is -the operator guide; [docs/phases/](docs/phases/README.md) has a page per -phase. +`tanstack-start` → Build), or from orun.work. Three phases, in two stages, +each landing one pull request in the new repository: + +| stage | phase | needs | lands | +|---|---|---|---| +| scaffold | `01-scaffold` | GitHub | the repository created and linked, then the whole site in one pull request, its deploy lanes parked — CI on `main` is green and deploys nothing | +| live | `02-live` | Cloudflare | the workers.dev subdomain bound, the deploy credentials minted, the lanes put back — deployed to stage and prod and smoke-tested | +| | `03-docs` | — | the live deployment recorded, the promotion gate put back | + +A build with no Cloudflare connection stops after the scaffold +(`--until 01-scaffold`) and the site is **code only**; a later build takes it +live (`--resume` with the account's `subdomain`). The card declares the split +(`blueprint.yaml` `spec.stages`) and the one input that waits for it +(`subdomain`, `lateBound`). **[BOOTSTRAP.md](BOOTSTRAP.md)** is the operator +guide; [docs/phases/](docs/phases/README.md) has a page per phase. The new repository receives the **site only** — the app and its tests, its CI, its tooling, a README of its own and its operating contract — renamed @@ -47,10 +56,10 @@ repository's machinery ships. | 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 bootstrap's helpers (deferrals — the deploy lanes, prod's gate, dev's lanes — the late-bound subdomain, redeploy marker, work-tree strip) | `tooling/bootstrap/` | | The deployment-record renderer | `hooks/render-deployment-docs.sh` | | The site's README and context pack | `.baseline/product/README.md`, `ai/context/` | -| The baseline's tests: contract, leak, offline bootstrap, end to end | `testing/`, `.github/workflows/baseline.yml` | +| The baseline's tests: contract, leak, offline bootstrap (full and code-only), end to end | `testing/`, `.github/workflows/baseline.yml` | | Cutting a `baseline-vN` tag | `.github/workflows/tag.yml` | ## What is here (the site) @@ -63,7 +72,8 @@ repository's machinery ships. | The todo store: the visitor's list in one httpOnly cookie | `apps/web/src/data/todos.ts` | | The header and its navigation | `apps/web/src/components/Header.tsx` | | Vite plugins, Worker config, deploy contract | `apps/web/vite.config.ts`, `apps/web/wrangler.jsonc`, `apps/web/component.yaml` | -| Tests (the site's name, the todo store) | `apps/web/src/**/*.test.ts` | +| The Worker's entry: TanStack Start's handler, plus who may frame the site (on stage: orun.work's preview pane) | `apps/web/src/server.ts`, `apps/web/src/lib/framing.ts` | +| Tests (the site's name, the todo store, the framing policy) | `apps/web/src/**/*.test.ts` | ## Getting started @@ -90,9 +100,24 @@ while keeping the demo's point: a GET server function read in a loader, a POST one that changes what it reads. To share a list across devices, swap the cookie for a KV namespace. +**Framing.** The stage Worker answers every page it renders with +`Content-Security-Policy: frame-ancestors 'self' +https://orun-agent-web-stage.oruncloud.workers.dev +https://orun-agent-web-prod.oruncloud.workers.dev http://localhost:*` — +orun.work's preview pane shows a site's stage deploy in an iframe, and +`localhost` on any port is orun.work run for its development. Prod and dev +send no policy, so they frame exactly as before. The list is a map per +environment in `apps/web/src/lib/framing.ts`; change it there. The Worker +knows its environment because each deploy lane exports `DEPLOY_ENV` to its +build (`environmentBuildVar` in `component.yaml`, passed through by +`apps/web/turbo.json`), and `vite.config.ts` writes it into the bundle; a +local build or `vite dev` names none and sends no policy +(`DEPLOY_ENV=stage pnpm build` builds the stage Worker). + One Worker config, `apps/web/wrangler.jsonc`, serves both sides: the Vite -plugin reads it (with the source entry, TanStack Start's -`@tanstack/react-start/server-entry`, named in `vite.config.ts`), and it +plugin reads it (with the source entry, `src/server.ts` — TanStack Start's +`@tanstack/react-start/server-entry` with the framing policy — named in +`vite.config.ts`), and it describes the BUILT Worker — `dist/server/index.js` and its chunks, uploaded as built, and `dist/client` as Static Assets — for the deploy lane's `wrangler deploy --config wrangler.jsonc`, which never reads the build's own @@ -115,6 +140,6 @@ dry-run deploys of both upload the same modules. | Workflow | What it runs | Ships to a site | |---|---|---| -| `ci.yml` | the Orun pipeline, and the only workflow a site carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the site built and dry-deployed per environment; they do not typecheck, lint or run the tests), except the bootstrap's own landings (`orun/BASE-*`), where `plan` alone is the check; a merge deploys stage → prod. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does. A manual run (Orunbase's Deploy button, or Run workflow on `main`) plans the environment and components it names under the push-to-main trigger, so they deploy as a merge deploys them | yes | +| `ci.yml` | the Orun pipeline, and the only workflow a site carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the site built and dry-deployed per environment; they do not typecheck, lint or run the tests), except the bootstrap's own landings (`orun/BASE-*`), where `plan` alone is the check; a merge deploys stage → prod (until a site goes live, its deploy lanes are parked and a merge verifies on dev and deploys nothing). It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does. A manual run (Orunbase's Deploy button, or Run workflow on `main`) plans the environment and components it names under the push-to-main trigger, so they deploy as a merge deploys them | yes | | `baseline.yml` | the baseline's own tiers: contract tests, the blueprint read by the pinned orun, the leak gate, the offline bootstrap, the site installed, type-checked, linted, tested, built, dry-deployed and served (`testing/e2e.test.sh`, before every tag) | no | | `tag.yml` | cuts a `baseline-vN` tag (manual) | no | diff --git a/ai/context/current.md b/ai/context/current.md index 194f693..f5575cf 100644 --- a/ai/context/current.md +++ b/ai/context/current.md @@ -13,15 +13,19 @@ Start 1.169, deployed as one Cloudflare Worker + Static Assets through Cloudflare's Vite plugin — TanStack Start's own Cloudflare target. The todos live in each visitor's own httpOnly cookie. Packaged as an Orun baseline: `orun new --blueprint repo-blueprint.yaml` builds a new site in its own -repository and takes it to live on stage and prod in one landing -(`01-product`), then records what went live (`03-docs`). +repository in two stages — the code landed with GitHub alone (`01-scaffold`, +its deploy lanes parked), then live on stage and prod with Cloudflare +(`02-live`) — then records what went live (`03-docs`). A build with no +Cloudflare connection stops after the scaffold (a code-only site) and goes +live later; the card declares the split (`spec.stages`) for orun.work. +On stage, the Worker lets orun.work's preview pane frame it. ## Release | | | |---|---| -| Latest tag | `baseline-v1` (TS-3) | -| Proven live | No. Everything short of the platform is proven offline in Baseline CI (risk TS-A). The card's 4 minutes is an estimate | +| Latest tag | `baseline-v1` (TS-3); TS-4 — the two-stage build and stage framing — is on `main` for `baseline-v2` | +| Proven live | No. Everything short of the platform is proven offline in Baseline CI (risk TS-A). The card's 5 minutes is an estimate | ## Where to read @@ -35,5 +39,9 @@ repository and takes it to live on stage and prod in one landing ## Next -1. Bootstrap one site from `baseline-v1` against a workspace and record its - timings in place of the estimate (closes TS-A). +1. Cut `baseline-v2` and move the registry row to it (`tag`, + `expectedMinutes: 5`); the registry reads the card change as + `needs-review` (programme, stages, late-bound inputs). +2. Bootstrap one site from it against a workspace — code only, then live — + and record its timings on stage in place of the estimate (closes TS-A; + orun.work offers the baseline to apps only after that measurement). diff --git a/ai/context/decisions.md b/ai/context/decisions.md index 88e4a4f..dd1bb20 100644 --- a/ai/context/decisions.md +++ b/ai/context/decisions.md @@ -14,6 +14,11 @@ reads in order. | 6 | The site's name is one seam, `src/lib/site.ts`, read by the root route's `` | The rename rewrites one line, written so that any name stays a valid string | IMPLEMENTATION-STATUS | | 7 | The template's own `biome.json`, run as `biome lint`, and the code made to pass it (button types, keys, hook dependencies) | Upstream ships the config but never ran it; formatting stays upstream's | IMPLEMENTATION-STATUS | | 8 | The devtools stay in production, as upstream | The template's behaviour; removing them is one line for an owner | risk TS-E | -| 9 | One landing (`01-product`) then the record (`03-docs`); every bootstrap landing is checked in the box (`checks: local`) | A landing has a fixed cost; the convergence on `main` builds and smoke-tests the site anyway | `repo-blueprint.yaml` | +| 9 | ~~One landing (`01-product`) then the record (`03-docs`)~~ — superseded by 12; every bootstrap landing is checked in the box (`checks: local`) | A landing has a fixed cost; the convergence on `main` builds and smoke-tests the site anyway | `repo-blueprint.yaml` | | 10 | stack-tectonic 0.19.0 | The layout the end-to-end tier proves; one job per lane gains nothing from a shared install | risk TS-H | | 11 | The workers.dev subdomain is read from the Cloudflare connection, and the console asks for no domain | It has one right answer; a domain is an owner's step after the site is live | `blueprint.yaml` | +| 12 | Two stages: `01-scaffold` (GitHub only: the whole site in one landing, deploy lanes parked) and `02-live` (Cloudflare: subdomain bound, credentials minted, lanes restored, one landing deployed and probed), then `03-docs`; declared as `spec.stages` | An account with no Cloudflare connection still gets its code (orun.work's code-only app); a full build pays one landing more and ends on the same tree | `repo-blueprint.yaml`, saas-orun-work WA-D8/WA-D9 | +| 13 | The scaffold parks stage's and prod's push activation (`deploys.mjs`) and leaves dev's: a merge plans dev's verify lane | orun refuses a push plan no environment answers, so parking all three turns `main` red; dev verifying is the design's "plan and verify lanes only". `promotion` and `dev-lanes` move to `02-live`, the landing they speed up | `tooling/bootstrap/deploys.mjs` | +| 14 | `subdomain` is late-bound on both card and build; `02-live` binds it with a hook over every tracked file (`subdomain.mjs`), refusing the placeholder and a move to another account | A resume does not place the scaffold's files again, so only a hook in the live stage can replace what the scaffold wrote; a targeted rewrite does not re-run the rebrand over code someone has since written | `tooling/bootstrap/subdomain.mjs` | +| 15 | No GitHub connection probe in the scaffold; the `link` check is the GitHub gate | A repository in orun.work's managed GitHub org is linked through a platform connection the workspace's connection list never shows, so a probe would wait out ten minutes on a ready build | `repo-blueprint.yaml` | +| 16 | Stage's framing policy is a `frame-ancestors` header set by the Worker's entry from a per-environment map, the environment written in at build time (`DEPLOY_ENV`, the composition's `environmentBuildVar`) | One Worker config serves both environments, so the Worker cannot tell them apart at run time; the lane builds per environment anyway. Static Assets' `_headers` would miss every rendered page | `apps/web/src/lib/framing.ts` | diff --git a/ai/context/open-risks.md b/ai/context/open-risks.md index 0755300..dedc657 100644 --- a/ai/context/open-risks.md +++ b/ai/context/open-risks.md @@ -7,7 +7,10 @@ only what is still live, so it should be short. | ID | Risk | State | What closes it | |---|---|---|---| -| TS-A | No live bootstrap yet: the repository created and linked, the Cloudflare token minted, a real `wrangler deploy` and the probes are unproven | OPEN | One bootstrap from `baseline-v1` against a workspace | +| TS-A | No live bootstrap yet: the repository created and linked, the Cloudflare token minted, a real `wrangler deploy` and the probes are unproven — nor the two-stage build's code-only stop and later go-live | OPEN | One bootstrap from `baseline-v2` against a workspace, code only then live, timed on stage | +| TS-J | Going live later needs the site's checkout as the build's `--out`: `02-live` requires `01-scaffold` derived from the tree and lands from its git. A fresh, empty `--out` re-places the scaffold instead, and its landing is refused once `main` holds files the baseline does not (a code-only app's own work) | OPEN | The platform's go-live runs in a checkout of the app's `main` | +| TS-K | Going live in the container that built the scaffold needs orun v2.90.0 (late-bound inputs); older ones refuse the real subdomain against the recorded placeholder | OPEN | v2.90.0 released and the runner's | +| TS-L | Stage's `frame-ancestors` list narrows framing from any origin (no header) to the listed ones: orun.work served from any other origin — a custom domain — cannot frame a stage site until it is listed and that site's stage redeploys | OPEN | orun.work's final origins in `apps/web/src/lib/framing.ts` before sites depend on them | Accepted, and worth knowing before you change them: TS-B (`wrangler.jsonc` is the built Worker, held to the Vite plugin's output by the end-to-end diff --git a/ai/context/operations.md b/ai/context/operations.md index ababc51..8c1ebb7 100644 --- a/ai/context/operations.md +++ b/ai/context/operations.md @@ -67,6 +67,22 @@ Caveats that matter: redeploys nothing on its own. Land it with a change under `apps/web`. - A visitor's todos are theirs alone and live in their browser: clearing cookies clears the list, and nothing server-side can read or restore it. +- **Code only until it goes live.** If `intent.yaml` carries + `# @deploys-deferred:…` markers under `stage` and `prod`, the site was + built before its Cloudflare account was connected: merges plan dev's verify + lane and deploy nothing, and a manual deploy of stage or prod is refused + (`environment … is not activated by trigger github-push-main`). The + build's live stage puts the triggers back, binds the account's workers.dev + subdomain and deploys; do not restore them by hand without the deploy + credentials it mints. +- **Who may frame the site.** On stage, every response the Worker renders + carries `Content-Security-Policy: frame-ancestors …` naming the origins + that may show it in an iframe (orun.work's preview pane among them); prod + and dev send none. The list is `apps/web/src/lib/framing.ts`, one entry + per environment. The Worker knows its environment from `DEPLOY_ENV`, + which each deploy lane exports to its build (`environmentBuildVar` in + `apps/web/component.yaml`): a build by hand names none and sends no + policy. ## Secrets model @@ -99,6 +115,7 @@ orun integrations list --org <ws> --json && orun cloud check --org <ws> | deploy a change | merge to `main`; watch the run; failed lanes → `gh run rerun --failed` | | deploy by hand | Orunbase's Deploy button, or `gh workflow run ci.yml --ref main -f environment=<env> [-f component=<a,b>]` — the named components (blank: every one) run in that environment as a merge runs them; started off `main` it is refused | | redeploy without a change | edit the last line of `apps/web/component.yaml` (`# orun: redeploy <reason> <stamp>`) and merge — it is a deploy trigger, nothing reads it | +| change who may frame the site | edit `FRAME_ANCESTORS` in `apps/web/src/lib/framing.ts` (CSP source expressions, per environment) and merge; each environment sends it from its next deploy | | serve a custom domain | attach it to the Worker in Cloudflare (README, "Custom domain"), then replace the placeholder `tanstack-start.example.com` in `intent.yaml`'s `BASE_DOMAIN` (dev, stage and prod) with it; nothing else changes | | share todos across devices | swap the cookie in `apps/web/src/routes/demo/start.server-funcs.tsx` (`readTodos`, `setCookie`) for a KV namespace bound in `wrangler.jsonc` | | add a runtime secret | `orun secrets set <KEY> --org <ws> --env <env>` | diff --git a/apps/web/README.md b/apps/web/README.md index ee4ebdb..d8a3bfb 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -17,9 +17,20 @@ TanStack Start's own Cloudflare target: The site's name — every page's `<title>` — is in `src/lib/site.ts`. +Who may show the site in a frame is in `src/lib/framing.ts`, per environment: +on **stage**, every response the Worker renders carries +`Content-Security-Policy: frame-ancestors 'self' +https://orun-agent-web-stage.oruncloud.workers.dev +https://orun-agent-web-prod.oruncloud.workers.dev http://localhost:*` +(orun.work's preview pane, and orun.work run locally); prod, dev and a local +build send none. The Worker's entry, `src/server.ts`, adds it to TanStack +Start's own handler; the build learns its environment from `DEPLOY_ENV`, +which each deploy lane exports (`environmentBuildVar` in `component.yaml`). + ```bash pnpm dev # vite dev on http://localhost:3000 (the server runs in workerd) pnpm build # vite build → dist/server (the Worker) + dist/client (Static Assets) +DEPLOY_ENV=stage pnpm build # … the stage Worker, with stage's framing policy pnpm preview # wrangler dev over the built Worker pnpm test # vitest ``` @@ -36,7 +47,7 @@ template's `examples/tanstack-start`: | File | What changed | | --- | --- | | `package.json` | Nitro out, `@cloudflare/vite-plugin` and wrangler in; TanStack Start 1.133 → 1.169 with Vite 8, `@vitejs/plugin-react` 6 and vitest 5; Biome as the lint; unused packages dropped | -| `vite.config.ts` | Cloudflare's Vite plugin in place of Nitro; Vite's own tsconfig paths in place of `vite-tsconfig-paths` | +| `vite.config.ts` | Cloudflare's Vite plugin in place of Nitro, its Worker entry `src/server.ts`; Vite's own tsconfig paths in place of `vite-tsconfig-paths`; `DEPLOY_ENV` written into the bundle | | `src/routes/__root.tsx` | the `<title>` read from `src/lib/site.ts` | | `src/routes/demo/start.server-funcs.tsx` | the todos kept in the visitor's cookie instead of `todos.json` (`node:fs`); `.validator`, 1.169's name for `.inputValidator`; a refused todo says why | | `src/routes/demo/start.ssr.spa-mode.tsx` | the list's element type, which 1.169 infers more narrowly | @@ -44,5 +55,6 @@ template's `examples/tanstack-start`: | `src/styles.css` | Tailwind's sources named (`source("./")`), so the server build cannot read the client build's output into a different stylesheet | | `src/routeTree.gen.ts` | regenerated by 1.169's router generator | -Added: `wrangler.jsonc`, `vitest.config.ts`, `component.yaml`, `docs/`, -`src/lib/site.ts`, `src/data/todos.ts` and the tests beside them. +Added: `wrangler.jsonc`, `vitest.config.ts`, `component.yaml`, `turbo.json`, +`docs/`, `src/server.ts`, `src/lib/site.ts`, `src/lib/framing.ts`, +`src/data/todos.ts` and the tests beside them. diff --git a/apps/web/component.yaml b/apps/web/component.yaml index f46df0a..5623e03 100644 --- a/apps/web/component.yaml +++ b/apps/web/component.yaml @@ -46,6 +46,12 @@ spec: appDir: . turboFilter: '@app/web' + # The build learns which environment it deploys to: the lane exports + # DEPLOY_ENV=<dev|stage|prod> before buildCommand, and the Worker reads + # it to send stage's framing policy (src/lib/framing.ts) on stage alone. + # turbo.json passes it to the build (and keys the cache on it). + environmentBuildVar: DEPLOY_ENV + # The committed config: worker name, compatibility date and flags, and # the Worker as `vite build` leaves it — the server bundle and its chunks # uploaded as built, the browser's files as Static Assets. The deploy runs diff --git a/apps/web/src/lib/framing.test.ts b/apps/web/src/lib/framing.test.ts new file mode 100644 index 0000000..1806771 --- /dev/null +++ b/apps/web/src/lib/framing.test.ts @@ -0,0 +1,87 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' +import { DEPLOY_ENV, FRAME_ANCESTORS, frameAncestorsPolicy, withFramingPolicy } from './framing' + +// orun.work's preview pane frames a site's stage deploy, from these origins. +const ORUN_WORK = [ + 'https://orun-agent-web-stage.oruncloud.workers.dev', + 'https://orun-agent-web-prod.oruncloud.workers.dev', +] + +describe('who may frame the site', () => { + it('on stage: itself, orun.work on stage and prod, and orun.work run locally', () => { + expect(frameAncestorsPolicy('stage')).toBe( + `frame-ancestors 'self' ${ORUN_WORK.join(' ')} http://localhost:*`, + ) + }) + + it('on prod, dev and a build that names no environment: no policy at all', () => { + for (const environment of ['prod', 'dev', '']) { + expect(frameAncestorsPolicy(environment)).toBeNull() + } + }) + + it('reads only its own entries, never one an object inherits', () => { + expect(frameAncestorsPolicy('constructor')).toBeNull() + expect(frameAncestorsPolicy('toString')).toBeNull() + }) + + it('lists only source expressions a browser accepts in frame-ancestors', () => { + const source = /^('self'|'none'|https?:\/\/[a-z0-9.-]+(:(\d+|\*))?)$/ + for (const sources of Object.values(FRAME_ANCESTORS)) { + for (const s of sources) expect(s).toMatch(source) + } + }) + + it('outside a deploy build, the environment is empty', () => { + expect(DEPLOY_ENV).toBe('') + }) +}) + +describe('a response, with the policy added', () => { + it('stage: the header is added, and the response is otherwise the one rendered', async () => { + const rendered = new Response('<p>hi</p>', { status: 404, headers: { 'content-type': 'text/html' } }) + const out = withFramingPolicy(rendered, 'stage') + expect(out.status).toBe(404) + expect(out.headers.get('content-type')).toBe('text/html') + expect(out.headers.get('content-security-policy')).toBe(frameAncestorsPolicy('stage')) + expect(await out.text()).toBe('<p>hi</p>') + }) + + it('prod: the very response, untouched', () => { + const rendered = new Response('ok') + expect(withFramingPolicy(rendered, 'prod')).toBe(rendered) + expect(rendered.headers.has('content-security-policy')).toBe(false) + }) + + it('a policy the response already carries is kept beside it', () => { + const rendered = new Response('ok', { headers: { 'content-security-policy': "default-src 'self'" } }) + const header = withFramingPolicy(rendered, 'stage').headers.get('content-security-policy') + expect(header).toBe(`default-src 'self', ${frameAncestorsPolicy('stage')}`) + }) + + it('a response with immutable headers is copied, not refused', async () => { + const rendered = Response.redirect('https://example.com/elsewhere', 302) + const out = withFramingPolicy(rendered, 'stage') + expect(out.status).toBe(302) + expect(out.headers.get('location')).toBe('https://example.com/elsewhere') + expect(out.headers.get('content-security-policy')).toBe(frameAncestorsPolicy('stage')) + }) +}) + +describe('the Worker', () => { + it('renders every response through the policy (src/server.ts is its entry)', () => { + const server = readFileSync(new URL('../server.ts', import.meta.url), 'utf8') + expect(server).toContain('withFramingPolicy(await handler.fetch(request))') + const vite = readFileSync(new URL('../../vite.config.ts', import.meta.url), 'utf8') + expect(vite).toContain("main: './src/server.ts'") + expect(vite).toContain('__DEPLOY_ENV__: JSON.stringify(process.env.DEPLOY_ENV') + }) + + it('learns its environment from the deploy lane (component.yaml names DEPLOY_ENV)', () => { + const component = readFileSync(new URL('../../component.yaml', import.meta.url), 'utf8') + expect(component).toMatch(/^ {4}environmentBuildVar: DEPLOY_ENV$/m) + const turbo = JSON.parse(readFileSync(new URL('../../turbo.json', import.meta.url), 'utf8')) + expect(turbo.tasks.build.env).toContain('DEPLOY_ENV') + }) +}) diff --git a/apps/web/src/lib/framing.ts b/apps/web/src/lib/framing.ts new file mode 100644 index 0000000..f71d844 --- /dev/null +++ b/apps/web/src/lib/framing.ts @@ -0,0 +1,69 @@ +// Who may show this site inside a frame, per environment. +// +// A page that says nothing about framing can be framed by any origin. This +// site says it on STAGE, and only there: every response the Worker renders +// for the stage environment carries +// +// Content-Security-Policy: frame-ancestors <the sources below> +// +// so the origins allowed to frame it are a list in the code rather than a +// browser default, and a later change that adds `X-Frame-Options` cannot +// silently take the permission away (a browser that reads `frame-ancestors` +// ignores `X-Frame-Options`). +// +// Stage is listed for orun.work, the app builder: its preview pane shows a +// site's stage deploy in an iframe. Prod and every other environment send +// no such header, so they are framed (or not) exactly as before. +// +// TO CHANGE WHO MAY FRAME THE SITE, edit this map: one entry per environment, +// each a list of CSP source expressions (an origin, `'self'`, `'none'`, or a +// scheme/host/port pattern such as `http://localhost:*`). An environment that +// is not a key here sends no header. The build tells the Worker which +// environment it is (`DEPLOY_ENV`, see below), so the change reaches an +// environment with its next deploy. +export const FRAME_ANCESTORS: Readonly<Record<string, readonly string[]>> = { + stage: [ + "'self'", + // orun.work's preview pane, on its stage and prod deploys. + 'https://orun-agent-web-stage.oruncloud.workers.dev', + 'https://orun-agent-web-prod.oruncloud.workers.dev', + // orun.work run locally, for its development: any port. + 'http://localhost:*', + ], +} + +// The environment this Worker was BUILT for. The deploy lane exports +// `DEPLOY_ENV` to the build (`environmentBuildVar` in component.yaml) and +// vite.config.ts writes it into the server bundle as `__DEPLOY_ENV__`. Every +// environment's lane runs its own build, so the stage Worker knows it is +// stage. Empty for a build that names none: `vite dev`, the unit tests, a +// build by hand. +declare const __DEPLOY_ENV__: string | undefined +export const DEPLOY_ENV: string = typeof __DEPLOY_ENV__ === 'string' ? __DEPLOY_ENV__ : '' + +/** The `Content-Security-Policy` value for an environment, or null for none. */ +export function frameAncestorsPolicy(environment: string): string | null { + if (!Object.hasOwn(FRAME_ANCESTORS, environment)) return null + const sources = FRAME_ANCESTORS[environment] ?? [] + return sources.length > 0 ? `frame-ancestors ${sources.join(' ')}` : null +} + +/** + * The response, with the environment's framing policy added. Appended rather + * than set, so a policy the response already carries is kept: a browser + * enforces every `Content-Security-Policy` header it receives. + */ +export function withFramingPolicy(response: Response, environment: string = DEPLOY_ENV): Response { + const policy = frameAncestorsPolicy(environment) + if (!policy) return response + try { + response.headers.append('Content-Security-Policy', policy) + return response + } catch { + // A response whose headers are immutable (one passed through from a + // fetch): copy it, then add the header to the copy. + const copy = new Response(response.body, response) + copy.headers.append('Content-Security-Policy', policy) + return copy + } +} diff --git a/apps/web/src/server.ts b/apps/web/src/server.ts new file mode 100644 index 0000000..4b7c220 --- /dev/null +++ b/apps/web/src/server.ts @@ -0,0 +1,15 @@ +// The Worker's entry: TanStack Start's own request handler, with this site's +// framing policy on every response it renders (src/lib/framing.ts — on stage, +// the origins that may show the site in a frame; elsewhere, nothing added). +// +// vite.config.ts names this file as the Worker's source entry, for `vite dev` +// and `vite build` alike. The browser's static files never reach it: Static +// Assets answer them before the Worker runs. +import handler, { createServerEntry } from '@tanstack/react-start/server-entry' +import { withFramingPolicy } from './lib/framing' + +export default createServerEntry({ + async fetch(request) { + return withFramingPolicy(await handler.fetch(request)) + }, +}) diff --git a/apps/web/turbo.json b/apps/web/turbo.json index e3f33ba..36f67d2 100644 --- a/apps/web/turbo.json +++ b/apps/web/turbo.json @@ -4,6 +4,7 @@ "tasks": { "build": { "dependsOn": ["^build"], + "env": ["DEPLOY_ENV"], "outputs": ["dist/**"] }, "test": { diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 7a30505..0b5e999 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -15,14 +15,25 @@ import { defineConfig } from 'vite' // named here instead of in that file's `main`, and the plugin's build warns // once that the file's `no_bundle` and `rules` are ignored under Vite: they // are for the deploy, which uploads the build's modules as they are. +// +// The source entry is src/server.ts: TanStack Start's own handler +// (`@tanstack/react-start/server-entry`), with the site's framing policy on +// every response (src/lib/framing.ts). export default defineConfig({ // tsconfig.json's `@/*` paths: Vite 8 resolves them itself (the template's // vite-tsconfig-paths plugin is redundant on it, and Vite says so). resolve: { tsconfigPaths: true }, + // The environment this build deploys to, written into the bundle: the + // deploy lane exports DEPLOY_ENV to its build (`environmentBuildVar` in + // component.yaml), and src/lib/framing.ts reads it to decide who may frame + // the site. Empty when nothing names one (`vite dev`, a build by hand). + define: { + __DEPLOY_ENV__: JSON.stringify(process.env.DEPLOY_ENV ?? ''), + }, plugins: [ cloudflare({ viteEnvironment: { name: 'ssr' }, - config: { main: '@tanstack/react-start/server-entry' }, + config: { main: './src/server.ts' }, }), tailwindcss(), tanstackStart(), diff --git a/blueprint.yaml b/blueprint.yaml index 358b5e0..710a1a1 100644 --- a/blueprint.yaml +++ b/blueprint.yaml @@ -23,8 +23,8 @@ metadata: route, and the three SSR modes (full, data-only and SPA), built by Cloudflare's Vite plugin — TanStack Start's own Cloudflare target — into one Worker with Static Assets, and CI that deploys it to stage and prod on - merge. One provider, one consent, one token, one landing. Live in about - four minutes. + merge. The code lands with GitHub alone; Cloudflare — one provider, one + consent, one token — takes it live. Live in about five minutes. tags: [tanstack, tanstack-start, react, vite, cloudflare, starter] spec: source: @@ -49,11 +49,13 @@ spec: - Live on stage and prod - Every merge redeploys, smoke-tested - Its own CI from the first phase + - Code first — without Cloudflare yet, the code lands and nothing deploys 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. + # Cloudflare is the only provider connection a bootstrap needs, and only + # its LIVE stage needs it (`stages` below): the scaffold lands the code + # with GitHub alone. GitHub arrives as the App installation plus the repo + # link, not as a connection row. integrations: [github, cloudflare] apiKeyRole: admin # secret writes need the admin floor @@ -96,7 +98,7 @@ spec: # READ FROM THE CLOUDFLARE CONNECTION, not asked. The subdomain belongs # to the account the same way its id does, and there is exactly one # right answer — a typed one could only be wrong, and wrong showed up - # after deploy, in the deploy's smoke, 01-product's probes and the + # after deploy, in the deploy's smoke, the live stage's probes and the # verify URL below. The integration reads it from Cloudflare at connect # and on its hourly health check; the bootstrap door fills this input # from the connection the build is BOUND to, the same one @@ -105,9 +107,15 @@ spec: # with no workers.dev subdomain refuses the build at the door, naming # the fix, before anything is created. from: connection.cloudflare.workersSubdomain + # LATE-BOUND: a build that stops after the scaffold stage has no + # Cloudflare connection to read it from, and runs without it — the + # scaffold brands the placeholder `your-workers-subdomain`, and the live + # stage binds the real value (02-live's `subdomain` hook) before + # anything deploys. repo-blueprint.yaml marks the input the same way. + lateBound: true # ── PREVIEW ONLY. repo-blueprint.yaml's `orun.integrations/reconcile@v1` - # hook mints these, brokered, during 01-product. ────────────────────────── + # hook mints these, brokered, during 02-live — the live stage. ─────────── # Transcribed from that hook's own `secrets:` list (each key and its # `template:`), so testing/manifest.test.sh compares this list to the # document that mints them. The console renders them read-only: no @@ -132,17 +140,42 @@ spec: epicSlug: tanstack-start-baselining # = repo-blueprint.yaml's `epicSlug` default epicName: "TanStack Start baselining — {productname}" milestones: - - name: 01-product + - name: 01-scaffold + - name: 02-live - name: 03-docs bootstrap: # THE BUILD DOCUMENT. There is no umbrella workflow and no agent brief: # every phase is declared in it and orun runs it. blueprint: repo-blueprint.yaml - # Summed from the phases' expectedMinutes (3 + 1). An estimate until a - # bootstrap of this shape measures it. - expectedMinutes: 4 + # Summed from the phases' expectedMinutes (1 + 3 + 1), a full build: both + # stages, then the record. An estimate until a bootstrap of this shape + # measures it on stage. + expectedMinutes: 5 tokenChannel: ORUN_TOKEN_FILE # how a runner hands over its refreshed token + + # ── WHERE A BUILD MAY STOP (saas-orun-work WA5) ────────────────────────── + # Phase names of repo-blueprint.yaml, which testing/manifest.test.sh holds + # them to: two different declared phases, scaffold before live. + # + # scaffold — the last phase that needs GitHub only. The site's code placed, + # branded and landed in a new, linked repository, its deploy lanes + # parked: CI on main is green and deploys nothing. A build with `until: + # scaffold` stops after it, so an account with no Cloudflare connection + # still gets its code (a CODE-ONLY app). + # live — the phase that needs `requires.integrations` (Cloudflare): the + # subdomain bound, the deploy credentials minted, the deploy lanes put + # back, one landing deployed to stage and prod, watched and probed. A + # later build runs it for a code-only app. + # + # A build with no stop runs both, then 03-docs, in one go. + stages: + scaffold: 01-scaffold + live: 02-live + + # The stage and prod URLs: once live, stage is the app's preview — its + # Worker lets orun.work's preview pane frame it (apps/web's + # src/lib/framing.ts) — and prod its live link. verify: urls: - "https://{reponame}-web-{env}.{subdomain}.workers.dev" diff --git a/docs/phases/01-product.md b/docs/phases/01-product.md deleted file mode 100644 index 3bd47b9..0000000 --- a/docs/phases/01-product.md +++ /dev/null @@ -1,78 +0,0 @@ -# 01-product — the site, built in one landing - -**Places** the whole tree: the root manifests (`intent.yaml`, `package.json`, -the pnpm workspace and lockfile, `turbo.json`), -`.github/workflows` (`ci.yml` — the baseline's own `baseline.yml` and -`tag.yml` are ignored), the shared TypeScript/ESLint -config and the wrangler renderer, the site's README and its two context -pages, the identity file `.rebrand/values.json`, `.gitkeep` files for the -four discovery roots, and `apps/web` — the TanStack Start site, its -Cloudflare Vite plugin build, its deploy contract and its tests (vitest, run -inside the app). - -**Requires** both connections live — GitHub (the App installation on -`githuborg`) and Cloudflare — probed, waited for up to ten minutes each, so a -consent can be clicked while it waits. The platform sees a pull request only -through the installation on the account that owns the repository, so the -probe runs before anything is created. - -## What runs - -The run's task set-up — the epic, both milestones, both tasks — runs in the -background from the start (`background: true`), so every hook up to `task` -runs beside it; `task` is the first that waits for it. - -| hook | what it does | -|---|---| -| `retouch` | the redeploy marker on `apps/web/component.yaml` (`.baseline/tasks/01-product.TaskContract.yaml`'s `affects`) | -| `git-init`, `git-stage` | the rebrand enumerates with `git ls-files`, so the tree is a staged repo first | -| `rebrand` | renames the baseline's identity to the site's over the whole tree (`tooling/rebrand/rebrand.mjs`) | -| `orun-workspace` | writes the site's workspace into `intent.yaml` (`ws_SET_ME` if there is none — loud, not silent) | -| `work-tree` | removes the baseline's own `work:` block from `intent.yaml` — `specs/` and `tasks/` do not ship | -| `promotion` | defers prod's wait on stage until `03-docs` (both environments deploy side by side) | -| `dev-lanes` | keeps dev's verify lanes off main's convergences until `03-docs` | -| `git-restage`, `rebrand-verify` | refuses the landing if any baseline identity is left | -| `repo` | `orun.repo/ensure@v1` — creates `githuborg/reponame` (private unless `repoPrivate=false`) | -| `link` | `orun cloud link` (best effort) then `orun cloud check` — an unlinked repo stops here | -| `secrets` | `orun.integrations/reconcile@v1`, both keys in one hook, created side by side: `CLOUDFLARE_API_TOKEN` from the `workers-deploy` template (Workers Scripts, the site's deploy); `CLOUDFLARE_ACCOUNT_ID`, the connection fact | -| `task` | finds the phase's task (opened by the run-level list) and yields its key — waiting, if it must, for the background set-up | -| `land` | one PR bound to the task, its commit checked in the box first (`checks: local`: `orun validate`, then `orun plan` as the PR and as the merge would plan it, under a second); merged without waiting for the PR's CI | -| `converge` (await) | `orun.run/watch@v1` on the merge commit's run, read every 5 s; resumes it up to three times | -| `verify` (await) | `orun.http/probe@v1` on both workers.dev URLs | - -## What the convergence does - -`orun plan --changed` plans `web` on stage and prod (deploy) and — dev's push -activation being deferred — nothing on dev. Each deploy lane installs the -workspace inside its own job tree, builds with `vite build` (Cloudflare's -Vite plugin writes `dist/server/index.js` and its chunks, and the browser's -files in `dist/client`, where `wrangler.jsonc`'s `main` and -`assets.directory` say), checks the build output, deploys -`<reponame>-web-<env>` with `wrangler deploy --config wrangler.jsonc`, and -smoke-tests it: the home page must carry the nav's server-functions link, -the API route must answer its JSON, and an unknown path must be TanStack -Router's not-found page with a 404, rendered by the Worker. Stage and prod -deploy side by side (this phase deferred the promotion gate). - -## Verified - -The repository exists and is linked to the workspace, the convergence run for -the merge commit is green, and -`https://<reponame>-web-{stage,prod}.<subdomain>.workers.dev` answer. - -## Troubleshooting - -| symptom | cause → fix | -|---|---| -| parks on `waiting for github for <org>` | the workspace's GitHub connection is to another account. Connect the App installation on `<org>` (console → Integrations → GitHub), then `--resume` | -| parks on the `providers` probe for cloudflare | Cloudflare is not connected to the workspace. Connect it (console → Integrations → Cloudflare, paste the Account API token) | -| `link` fails: `… is not linked to workspace` | the credential cannot write links and the platform has not linked the repo. Allow-list it (console → Settings → Git repos) and re-run the phase | -| `land`: `the landing's own check failed — orun plan for …` | the placed tree does not plan; the next line is orun's error. Nothing was pushed. Fix it and re-run the phase | -| `rebrand-verify` lists leftovers | a file carries an identity form no rule renames. Add a rule to `tooling/rebrand/rebrand.mjs` (and a case to `testing/rebrand.test.sh`) | -| `intent.yaml` says `workspace: ws_SET_ME` | `orunWorkspace` was empty and the build ran outside a workspace. Set it and re-run | -| deploy lane: `secret resolution failed … CLOUDFLARE_API_TOKEN` | the reconcile did not run or minted against a revoked connection. Re-connect and re-run the phase; the reconcile re-mints only what is missing | -| deploy lane: Authentication error (10000) | the connection's token lacks Workers Scripts Write. Re-issue it with the permission groups the console's Connect recipe lists | -| smoke fails right after the FIRST deploy | workers.dev route propagation; the composition retries the first deploy and the smoke with backoff (stack-tectonic ≥ 0.19.0). A convergence resume clears what is left | -| `build-app` fails resolving a dependency, or `wrangler` is not found | the job's install did not run inside its tree. The site's `intent.yaml` pins stack-tectonic 0.19.0, where it does; a bump changes the install's layout — `intent.yaml`'s comment says why it is pinned | -| the watch says green, the probe says 404 | another workflow ran on the push and the watch took its run. Only `ci.yml` may run on a push to main | -| re-run lands nothing | the hooks did not run (`--run-hooks`), or the contract names no component — `node tooling/bootstrap/retouch.mjs --check --affects .baseline/tasks/01-product.TaskContract.yaml` in the site's tree says which | diff --git a/docs/phases/01-scaffold.md b/docs/phases/01-scaffold.md new file mode 100644 index 0000000..cf472d0 --- /dev/null +++ b/docs/phases/01-scaffold.md @@ -0,0 +1,82 @@ +# 01-scaffold — the site's code, landed + +The **scaffold stage** (`blueprint.yaml` `spec.stages.scaffold`): everything +that needs GitHub and nothing else. A build that stops here +(`--until 01-scaffold`; the platform's `until: scaffold`) leaves a +**code-only** site: its repository, its CI and its pull requests' checks all +work, and nothing is deployed anywhere. + +**Places** the whole tree: the root manifests (`intent.yaml`, `package.json`, +the pnpm workspace and lockfile, `turbo.json`), +`.github/workflows` (`ci.yml` — the baseline's own `baseline.yml` and +`tag.yml` are ignored), the shared TypeScript/ESLint +config and the wrangler renderer, the site's README and its two context +pages, the identity file `.rebrand/values.json`, `.gitkeep` files for the +four discovery roots, and `apps/web` — the TanStack Start site, its +Cloudflare Vite plugin build, its deploy contract and its tests (vitest, run +inside the app). + +**Requires** nothing a probe can see. GitHub is proven by the repository's +link to the workspace, which `link` checks before the landing: the platform +sees a pull request only through the GitHub App installation on the account +that owns the repository, and a linked repository is one it sees. (A +connection probe would read the workspace's own connection list, which never +shows the platform connection a repository in orun.work's managed GitHub org +is linked through.) Cloudflare is `02-live`'s to ask for. + +The subdomain is late-bound: without one (a code-only build), the identity +file and the tree carry the placeholder `your-workers-subdomain`, and +`02-live` binds the real value before anything deploys. + +## What runs + +The run's task set-up — the epic, the three milestones, the three 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 | +|---|---| +| `git-init`, `git-stage` | the rebrand enumerates with `git ls-files`, so the tree is a staged repo first | +| `rebrand` | renames the baseline's identity to the site's over the whole tree (`tooling/rebrand/rebrand.mjs`) | +| `orun-workspace` | writes the site's workspace into `intent.yaml` (`ws_SET_ME` if there is none — loud, not silent) | +| `work-tree` | removes the baseline's own `work:` block from `intent.yaml` — `specs/` and `tasks/` do not ship | +| `deploys` | parks stage's and prod's activation on a push to `main` until `02-live` (`tooling/bootstrap/deploys.mjs`) — a merge plans dev's verify lane and deploys nothing | +| `git-restage`, `rebrand-verify` | refuses the landing if any baseline identity is left | +| `repo` | `orun.repo/ensure@v1` — creates `githuborg/reponame` (private unless `repoPrivate=false`), or finds it | +| `link` | `orun cloud link` (best effort) then `orun cloud check` — an unlinked repo stops here | +| `task` | finds the phase's task (opened by the run-level list) and yields its key — waiting, if it must, for the background set-up | +| `land` | one PR bound to the task, its commit checked in the box first (`checks: local`: `orun validate`, then `orun plan` as the PR and as the merge would plan it, under a second); merged without waiting for the PR's CI | + +Nothing is awaited: the merge deploys nothing, so there is no convergence to +watch. + +## What CI on main does with it + +`orun plan --changed` for the merge plans `web` on **dev** with the verify +profile — the site built and dry-deployed, no credential — and nothing on +stage or prod, whose push activation is parked. The run is green and deploys +nothing. Parking all three would not do: orun refuses a push plan that no +environment answers, and the run would be red. + +Every later merge of a code-only site is the same, and every pull request +runs the verify lanes on dev, stage and prod. A manual deploy (Orunbase's +Deploy button, or **Run workflow** with an environment) of stage or prod is +refused by `orun plan` — `environment stage is not activated by trigger +github-push-main` — until `02-live` has run: there is no credential to deploy +with. + +## Verified + +The repository exists and is linked to the workspace, and the site is on +`main`, branded. The landing's own check planned the merge before it was +pushed. + +## Troubleshooting + +| symptom | cause → fix | +|---|---| +| `link` fails: `… is not linked to workspace` | the credential cannot write links and the platform has not linked the repo — or the GitHub App is not installed on `githuborg`. Install it (console → Integrations → GitHub), allow-list the repo (console → Settings → Git repos) and re-run the phase | +| `land`: `the landing's own check failed — orun plan for …` | the placed tree does not plan; the next line is orun's error. Nothing was pushed. Fix it and re-run the phase | +| `rebrand-verify` lists leftovers | a file carries an identity form no rule renames. Add a rule to `tooling/rebrand/rebrand.mjs` (and a case to `testing/rebrand.test.sh`) | +| `intent.yaml` says `workspace: ws_SET_ME` | `orunWorkspace` was empty and the build ran outside a workspace. Set it and re-run | +| the site deploys nothing after a merge | expected while it is code only: `intent.yaml` carries two `# @deploys-deferred:…` markers. Run `02-live` | diff --git a/docs/phases/02-live.md b/docs/phases/02-live.md new file mode 100644 index 0000000..4a54fdb --- /dev/null +++ b/docs/phases/02-live.md @@ -0,0 +1,77 @@ +# 02-live — the site, live on stage and prod + +The **live stage** (`blueprint.yaml` `spec.stages.live`): everything that +needs Cloudflare. A build with a Cloudflare connection runs it straight after +`01-scaffold`; a code-only site runs it whenever its account connects one +(`--resume`, which finds `01-scaffold` placed and runs what follows). + +**Places** nothing. Its work is hooks: it takes what `01-scaffold` landed +live in one landing, whose convergence deploys the site to stage and prod. + +**Requires** `01-scaffold` placed, and the Cloudflare connection live — +probed, and waited for up to ten minutes so a consent can be clicked while it +waits. The probe is asked once before the run's first phase and, if +Cloudflare is not there yet, again just before this one, so a build that has +no connection still lands its code first. + +**Needs** the real workers.dev subdomain (`subdomain`, a late-bound input): a +console or orun.work build reads it from the Cloudflare connection; a +hand-run build passes `--set subdomain=…`. It may differ from the placeholder +a code-only scaffold recorded — that is what late-bound means — and the +`subdomain` hook refuses the placeholder itself. + +## What runs + +| hook | what it does | +|---|---| +| `subdomain` | binds the account's workers.dev subdomain where the placeholder stands: `apps/web/component.yaml` (the smoke's URL), `intent.yaml`'s environment URLs, `ai/context/operations.md`, and `.rebrand/values.json` last (`tooling/bootstrap/subdomain.mjs`). A site built with it from the start changes nothing; a site bound to another subdomain is refused (another account) | +| `deploys` | puts back stage's and prod's activation on a push to `main` | +| `promotion` | defers prod's wait on stage until `03-docs` (both environments deploy side by side) | +| `dev-lanes` | keeps dev's verify lane off main's convergences until `03-docs` | +| `retouch` | the redeploy marker on `apps/web/component.yaml` (`.baseline/tasks/02-live.TaskContract.yaml`'s `affects`) — the landing changes the component, so its merge deploys it, on the first run and on a re-run alike | +| `secrets` | `orun.integrations/reconcile@v1`, both keys in one hook, created side by side: `CLOUDFLARE_API_TOKEN` from the `workers-deploy` template (Workers Scripts, the site's deploy); `CLOUDFLARE_ACCOUNT_ID`, the connection fact. Keys that exist are kept | +| `task` | finds the phase's task and yields its key | +| `land` | one PR bound to the task, its commit checked in the box (`checks: local`) and merged without waiting for the PR's CI | +| `converge` (await) | `orun.run/watch@v1` on the merge commit's run, read every 5 s; resumes it up to three times | +| `verify` (await) | `orun.http/probe@v1` on both workers.dev URLs | + +## What the convergence does + +`orun plan --changed` plans `web` on stage and prod (deploy) and — dev's push +activation being deferred — nothing on dev. Each deploy lane installs the +workspace inside its own job tree, builds with `vite build` (Cloudflare's +Vite plugin writes `dist/server/index.js` and its chunks, and the browser's +files in `dist/client`, where `wrangler.jsonc`'s `main` and +`assets.directory` say), checks the build output, deploys +`<reponame>-web-<env>` with `wrangler deploy --config wrangler.jsonc`, and +smoke-tests it: the home page must carry the nav's server-functions link, +the API route must answer its JSON, and an unknown path must be TanStack +Router's not-found page with a 404, rendered by the Worker. Stage and prod +deploy side by side (this phase deferred the promotion gate). + +Each lane's build is told its environment (`DEPLOY_ENV`, the component's +`environmentBuildVar`), and the stage Worker sends +`Content-Security-Policy: frame-ancestors` naming the origins that may frame +it — orun.work's preview pane among them (`apps/web/src/lib/framing.ts`). +Prod sends none. + +## Verified + +The convergence run for the merge commit is green, and +`https://<reponame>-web-{stage,prod}.<subdomain>.workers.dev` answer. + +## Troubleshooting + +| symptom | cause → fix | +|---|---| +| parks on the `providers` probe for cloudflare | Cloudflare is not connected to the workspace. Connect it (console → Integrations → Cloudflare, paste the Account API token); the site's code is already on main | +| `subdomain --bind: … was given the placeholder` | the build had no workers.dev subdomain. A console or orun.work build reads it from the connection — the account has none until one is set up in Cloudflare (Workers & Pages); a hand-run build passes `--set subdomain=…` | +| `subdomain --bind: this site is bound to … and was given …` | the build is bound to another Cloudflare account than the one the site was taken live on. Build with the original connection; moving a site between accounts is not a bootstrap step | +| `input conflict … subdomain: recorded "your-workers-subdomain"` | the live stage ran in the container that ran the scaffold, on an orun that predates late-bound inputs. Use an orun that reads `lateBound`, or a fresh container (the record is `.orun/`, which no checkout carries) | +| deploy lane: `secret resolution failed … CLOUDFLARE_API_TOKEN` | the reconcile did not run or minted against a revoked connection. Re-connect and re-run the phase; the reconcile re-mints only what is missing | +| deploy lane: Authentication error (10000) | the connection's token lacks Workers Scripts Write. Re-issue it with the permission groups the console's Connect recipe lists | +| smoke fails right after the FIRST deploy | workers.dev route propagation; the composition retries the first deploy and the smoke with backoff (stack-tectonic ≥ 0.19.0). A convergence resume clears what is left | +| `build-app` fails resolving a dependency, or `wrangler` is not found | the job's install did not run inside its tree. The site's `intent.yaml` pins stack-tectonic 0.19.0, where it does; a bump changes the install's layout — `intent.yaml`'s comment says why it is pinned | +| the watch says green, the probe says 404 | another workflow ran on the push and the watch took its run. Only `ci.yml` may run on a push to main | +| the convergence failed AFTER the PR merged | the files are on main. Re-run the phase (`--phase 02-live`, `--redo 02-live` under `--resume`, or the console's Retry): `retouch` gives the landing a new diff and the site redeploys | +| re-run lands nothing | the hooks did not run (`--run-hooks`), or the contract names no component — `node tooling/bootstrap/retouch.mjs --check --affects .baseline/tasks/02-live.TaskContract.yaml` in the site's tree says which | diff --git a/docs/phases/03-docs.md b/docs/phases/03-docs.md index cabe694..9b9b590 100644 --- a/docs/phases/03-docs.md +++ b/docs/phases/03-docs.md @@ -1,11 +1,11 @@ # 03-docs — the deployment, recorded -**Places** nothing. Its work is hooks: it records what `01-product` built, from -probed facts rather than from what the blueprint intended, and it puts back -the two things `01-product` deferred for the bootstrap's sake. +**Places** nothing. Its work is hooks: it records what `02-live` deployed, +from probed facts rather than from what the blueprint intended, and it puts +back the two things `02-live` deferred for the bootstrap's sake. -**Requires** `01-product` placed. (A hook-only phase derives as `unknown`, so no -phase may require this one.) +**Requires** `01-scaffold` placed. (`02-live` is hook-only too and derives as +`unknown`, so neither may be required; `--resume` runs `02-live` before this.) ## What runs @@ -29,11 +29,17 @@ orun new --blueprint repo-blueprint.yaml --out <site-checkout> \ ## 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: +After `02-live` — a build that ran the live stage alone, say — the promotion +gate and dev's push activation stay deferred: `intent.yaml` carries a +`# @promotion-deferred:…` and a `# @dev-lanes-deferred:…` marker. The site is +live and deploys on every merge, but prod does not wait on stage. Running this +phase restores both, or by hand from the baseline checkout: ```bash node tooling/bootstrap/promotion.mjs --restore --file <site>/intent.yaml node tooling/bootstrap/dev-lanes.mjs --restore --file <site>/intent.yaml ``` + +A code-only site (stopped after `01-scaffold`) carries neither: its only +markers are stage's and prod's `# @deploys-deferred:…`, which `02-live` +restores when the site goes live. diff --git a/docs/phases/README.md b/docs/phases/README.md index e7a0c1b..c262772 100644 --- a/docs/phases/README.md +++ b/docs/phases/README.md @@ -1,18 +1,42 @@ -# The phases — one blueprint, two selections - -`repo-blueprint.yaml` declares two phases that take a site from **nothing** -to **live on stage and prod, documented**: one landing builds the whole site, -one records it. Run them one at a time with -`--phase <name>`, or the whole sequence unattended with `--resume`. There is -no umbrella workflow and no per-phase document: a phase is a selection on one -artifact, which is what makes running one alone, months later, from a fresh -container the same operation as running them all. - -The site phase follows the contract every deploying phase does: - -> **place its modules → brand them → check them in the box and land them as -> one pull request → watch the convergence that merge triggers -> (auto-resumed) → verify the outcome over HTTP.** +# The phases — one blueprint, two stages, three selections + +`repo-blueprint.yaml` declares three phases that take a site from **nothing** +to **live on stage and prod, documented**: one landing places the whole site +with GitHub alone, one takes it live on Cloudflare, one records it. Run them +one at a time with `--phase <name>`, stop after the code with +`--until 01-scaffold`, or run 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. + +## Two stages + +The build splits where its needs change, and the card says where +(`blueprint.yaml` `spec.stages`): + +| stage | phase | needs | leaves | +|---|---|---|---| +| **scaffold** | [`01-scaffold`](01-scaffold.md) | GitHub only | the site's code on `main` in its own linked repository; its deploy lanes parked, so CI on `main` is green and deploys nothing | +| **live** | [`02-live`](02-live.md) | Cloudflare (the card's `requires.integrations`) | the site live on stage and prod, smoke-tested and probed | + +A build with a Cloudflare connection runs both, then `03-docs`, in one go — +and ends exactly where the one-landing shape (`baseline-v1`'s `01-product`) +did. A build without one stops after the scaffold (`--until 01-scaffold`; +the platform's `until: scaffold`) and the site is **code only**: its +repository, CI and pull-request checks all work and nothing is deployed. A +later build goes live: `--resume` finds `01-scaffold` placed and runs +`02-live` and `03-docs`. + +The workers.dev subdomain is the one **late-bound** input: it belongs to the +Cloudflare account, so a code-only build runs without it (the tree carries +the placeholder `your-workers-subdomain`), and `02-live` binds the real value +before anything deploys. + +The deploying phase follows the contract every deploying phase does: + +> **land the change as one pull request, checked in the box → 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 @@ -25,24 +49,26 @@ site's repository is wherever `--out` points. The phase number is the EXECUTION order, and each phase's `requires.phases` states it in the document: the engine refuses a phase whose predecessor is not -placed, and names it. +placed, and names it. `02-live` and `03-docs` place no files, so the tree +cannot answer for them (`unknown`): both require `01-scaffold`, and +`--resume` always runs them again — every hook in both is idempotent. Every landing is a pull request on a branch named for its task (`orun/BASE-<n>-<phase>`), checked before it is pushed: `orun validate`, then `orun plan` as the pull request and as the merge would plan it, in the box, in under a second (`checks: local`). Then it merges; nothing waits for the PR's CI. On those branches `ci.yml` runs `plan` only and skips the lanes, -because the merge runs them on main a minute later, for real, and that -convergence is what the phase watches. The site carries no other workflow: -the baseline's own CI (Tier 2) installs, renders the fixtures, type-checks, -lints, tests and builds this tree before a tag is cut, and every later pull -request in the site runs `ci.yml`'s verify lanes (built and dry-deployed per -environment; they do not lint or run the tests). - -| phase | lands | verified by | -|---|---|---| -| [`01-product`](01-product.md) | **the GitHub repo created**, then the WHOLE site in one PR: intent, CI, tooling, identity, `apps/web` (the site and its tests) — one convergence deploys it to stage and prod side by side | repo workspace-linked, convergence green (build, deploy, smoke) + both URLs answer | -| [`03-docs`](03-docs.md) | the live-deployment record; the promotion gate and dev lanes put back | committed manifest matches probed reality | +because the merge runs them on main moments later, for real. The site carries +no other workflow: the baseline's own CI (Tier 2) installs, renders the +fixtures, type-checks, lints, tests and builds this tree before a tag is cut, +and every later pull request in the site runs `ci.yml`'s verify lanes (built +and dry-deployed per environment; they do not lint or run the tests). + +| phase | lands | what main's CI does with it | verified by | +|---|---|---|---| +| [`01-scaffold`](01-scaffold.md) | **the GitHub repo created**, then the WHOLE site in one PR: intent, CI, tooling, identity, `apps/web` (the site and its tests) — stage's and prod's deploy lanes parked | dev's verify lane; nothing deployed | repo workspace-linked; the landing's own plan | +| [`02-live`](02-live.md) | the subdomain bound, the deploy lanes put back, the deploy credentials minted; one PR whose merge deploys | the site deployed to stage and prod side by side, smoke-tested | convergence green (build, deploy, smoke) + both URLs answer | +| [`03-docs`](03-docs.md) | the live-deployment record; the promotion gate and dev lanes put back | nothing (no component changed) | committed manifest matches probed reality | There is no custom-domain phase. Attaching a domain to a Worker needs zone permissions the platform's brokered `workers-deploy` token does not carry, so @@ -53,7 +79,7 @@ the placeholder until then. ## Inputs -`01-product` takes the site's identity once and writes it into the repo +`01-scaffold` takes the site's identity once and writes it into the repo (`.rebrand/values.json`); every later phase reads it back from the placed tree. But the blueprint's **required** inputs — `reponame`, `productname`, `githuborg` — are validated before any phase runs, so they must be supplied @@ -65,11 +91,12 @@ than repeating `--set`. into `BASE_DOMAIN`, for an owner to replace when they attach a domain (the site's README, "Custom domain"). Pass it only for a site that already has its domain. - - `subdomain` — the workers.dev subdomain of the Cloudflare account you - deploy into. It is in every URL the phases probe and the deploy's smoke + deploy into. It is in every URL `02-live` probes and the deploy's smoke fetches. A console or `--from bst_…` build reads it from the Cloudflare - connection; pass it only for a hand-run build. + connection; pass it only for a hand-run build. LATE-BOUND: a code-only + build (`--until 01-scaffold`) runs without it, and the run that goes live + must pass it. - `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. @@ -79,9 +106,15 @@ than repeating `--set`. - `repoPrivate` (default `true`) — the repository's visibility at creation. ```bash +# the code only — GitHub, no Cloudflare orun new --blueprint repo-blueprint.yaml \ - --out $HOME/sites/acme-notes --run-hooks --phase 01-product \ + --out $HOME/sites/acme-notes --run-hooks --until 01-scaffold \ --values ~/acme-notes.values.yaml + +# … later, live: the rest, with the account's subdomain +orun new --blueprint repo-blueprint.yaml \ + --out $HOME/sites/acme-notes --run-hooks --resume \ + --values ~/acme-notes.values.yaml --set subdomain=acme ``` Drop `--run-hooks` (or add `--status`) to preview. Without it a phase places @@ -90,17 +123,17 @@ which is exactly what makes a dry instantiation of this baseline possible in CI with no workspace and no provider (`testing/placement.test.sh`, `testing/e2e.test.sh`). -## What 01-product does after it places +## What 01-scaffold does after it places Placement writes the baseline's files as they are here. Before the phase lands, its `post` hooks make them the site's: -1. `retouch` — one `# orun: redeploy <phase> <stamp>` line - at the end of each component.yaml its task contract names, so a re-run - after a failed convergence still has a diff to land and redeploys exactly - those components. -2. `rebrand` → `rebrand --verify` — the identity rename over the whole tree, +1. `rebrand` → `rebrand --verify` — the identity rename over the whole tree, then a sweep that fails on any of this baseline's identity left behind. +2. `orun-workspace`, `work-tree` — the site's workspace in, the baseline's + work tree out. +3. `deploys` — stage's and prod's push-to-main activation parked, so the + merge deploys nothing. The baseline's complete lockfile ships as it is: it carries no identity, and the lanes install it with `--frozen-lockfile`, as the baseline's own CI does @@ -108,11 +141,15 @@ on this exact tree before a tag. ## When a phase fails -- **Before it lands** (a probe that timed out, a rebrand residue, a refused - link, a tree the landing's own `orun plan` refuses): nothing was merged. - Fix what the message names and re-run the phase. -- **After it lands** (the convergence went red): the files are on main. +- **Before it lands** (a refused link, a rebrand residue, a probe that timed + out, the placeholder subdomain, a tree the landing's own `orun plan` + refuses): nothing was merged. Fix what the message names and re-run the + phase. +- **After `02-live` 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 + the phase (`--phase 02-live`, `--redo 02-live` under `--resume`, or the console's Retry): its `retouch` hook gives the landing a diff and the component redeploys. +- **A build that stops before `03-docs`**: the site is live and deploys on + every merge, but prod does not wait on stage and dev does not verify + merges until `03-docs` runs ([03-docs.md](03-docs.md)). diff --git a/intent.yaml b/intent.yaml index 46e9397..baed9be 100644 --- a/intent.yaml +++ b/intent.yaml @@ -72,7 +72,7 @@ discovery: # # THIS BLOCK IS THE BASELINE'S OWN. A site built from this baseline has no # `specs/` and no `tasks/` (its bootstrap work lives on the platform), so -# 01-product removes the block, and this comment with it, from the +# 01-scaffold removes the block, and this comment with it, from the # product's copy (tooling/bootstrap/work-tree.mjs). work: epics: specs/epics diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml index 6894ff3..ff757e8 100644 --- a/repo-blueprint.yaml +++ b/repo-blueprint.yaml @@ -8,11 +8,13 @@ metadata: server functions in each visitor's cookie, an API route and the three SSR modes, built by Cloudflare's Vite plugin onto Cloudflare Workers + Static Assets) and - take it from nothing to live on stage and prod in one landing, then record - it. Run one at a time with `--phase <name>` or the whole sequence with - `--resume`; see docs/phases/README.md for the contract every phase - follows, and BOOTSTRAP.md for the operator checklist no script can - perform. + take it from nothing to live on stage and prod in two stages: the code, + landed with GitHub alone (01-scaffold), then the site deployed and probed + once Cloudflare is there (02-live), then the record. Run one at a time + with `--phase <name>`, stop after the code with `--until 01-scaffold`, or + run 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 @@ -51,19 +53,32 @@ inputs: required: true description: >- GitHub owner the site's repository is created under — and the owner in - the source link the site's nav carries. 01-product waits for the App - installation on THIS owner before it creates anything: the platform - learns of a pull request only through the installation on the account - that owns the repository. + the source link the site's nav carries. The platform learns of a pull + request only through the GitHub App installation on the account that + owns the repository, so 01-scaffold's `link` hook stops before the + landing unless the repository is linked to the workspace through it. subdomain: type: string default: "your-workers-subdomain" + # LATE-BOUND (saas-orun-work WA5): it belongs to the Cloudflare account, + # which a build that stops after 01-scaffold does not have yet. Such a + # build runs without it — the default above is the placeholder the + # scaffold brands into the tree — and the run that goes live supplies the + # real value: orun's "a resumed run reuses what the product was built + # with" rule exempts a late-bound input, so it may differ from what the + # scaffold recorded. 02-live's `subdomain` hook binds it into the tree + # and refuses the placeholder before anything deploys. An orun that + # predates the flag ignores it (and a fresh container has no record to + # differ from). + lateBound: true description: >- The workers.dev subdomain of the Cloudflare account the site deploys into — its URLs, the smoke, the probes. A console or `--from bst_…` build gets it from the workspace's Cloudflare connection (blueprint.yaml declares `from: connection.cloudflare.workersSubdomain`); - pass it with --set only for a hand-run build. + pass it with --set only for a hand-run build. Needed by 02-live, not + before: a code-only build (`--until 01-scaffold`) leaves the + placeholder, and 02-live binds the real value. repoPrivate: type: boolean default: true @@ -80,7 +95,7 @@ inputs: from: workspace description: >- Orun Cloud workspace (ws_…) for the site's remote state. Unset, it is - the workspace the build runs in; with none anywhere, 01-product writes + the workspace the build runs in; with none anywhere, 01-scaffold writes a placeholder that fails loudly rather than silently claiming another tenant's workspace. epicSlug: @@ -288,12 +303,16 @@ modules: # new milestone after the last, and a task naming a milestone the epic does # not have yet would create it out of order. # +# A build that stops after 01-scaffold (a code-only app) opens all three +# milestones and tasks too: the plane then says what is left to do, and the +# build that goes live later finds them by the same identities. +# # 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. +# Nothing a phase does before its landing reads the task plane — the +# placement, the rebrand, the repository, the secrets — so the whole list runs +# beside 01-scaffold 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, @@ -314,10 +333,10 @@ hooks: description: >- Everything the TanStack Start template builds for {{ .inputs.productname }} in {{ .inputs.githuborg }}/{{ .inputs.reponame }}: - the repository, its CI and the site live on stage and prod in one - landing, then the record of what went live. One milestone per phase, - in the order the phases run; one task per landing, each bound to the - pull request that lands it. + the repository and the site's code in one landing, then the site + live on stage and prod in a second, 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 @@ -325,9 +344,20 @@ hooks: with: kind: milestone epic: "{{ .inputs.epicSlug }}" - name: 01-product + name: 01-scaffold exitCriteria: - repository created under {{ .inputs.githuborg }} and linked to the workspace + - the whole site on main, branded, its deploy lanes parked + - CI on main green, deploying nothing + - id: m02 + uses: orun.task/ensure@v1 + background: true + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 02-live + exitCriteria: + - the deploy credentials minted from the workspace's Cloudflare connection - the site built and deployed on stage and prod, its smoke green - the home page answers on both workers.dev URLs - id: m03 @@ -346,16 +376,32 @@ hooks: with: kind: task epic: "{{ .inputs.epicSlug }}" - milestone: 01-product - name: "Build the site in one landing" + milestone: 01-scaffold + name: "Land the site's code" brief: >- Create {{ .inputs.githuborg }}/{{ .inputs.reponame }} and land the whole site as one pull request — intent, CI, tooling, the identity, - the site and its tests, branded as {{ .inputs.productname }} — then - see the convergence build it with Cloudflare's Vite plugin and - deploy it to stage and prod, smoke-tested over HTTP. + the site and its tests, branded as {{ .inputs.productname }} — with + its deploy lanes parked, so CI on main builds nothing it cannot + deploy and deploys nothing. GitHub only: no provider is needed yet. + prefix: BASE + contract: .baseline/tasks/01-scaffold.TaskContract.yaml + - id: t02 + uses: orun.task/ensure@v1 + background: true + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 02-live + name: "Take the site live" + brief: >- + Bind the site to its Cloudflare account's workers.dev subdomain, mint + the deploy credentials from the workspace's Cloudflare connection, + put the deploy lanes back, and see the convergence build the site + with Cloudflare's Vite plugin and deploy it to stage and prod, + smoke-tested over HTTP. prefix: BASE - contract: .baseline/tasks/01-product.TaskContract.yaml + contract: .baseline/tasks/02-live.TaskContract.yaml - id: t03 uses: orun.task/ensure@v1 background: true @@ -382,67 +428,61 @@ hooks: # the task plane's milestones carry. A dependency may never point forward # across a phase boundary; orun refuses the blueprint if one does. # -# ONE LANDING BUILDS THE SITE (cirrus-baseline baseline-v22's shape). A landing -# has a fixed cost however small it is — place, open a PR, wait for its -# checks, merge, wait for the convergence to start — and the bootstrap used to -# pay it three times: the scaffold, the site, the record. Nothing in the -# scaffold/site split was order the plan could not carry itself: the site's -# build reads the tooling from the same tree, and the convergence on main is -# what deploys it either way. So 01-product places the whole tree, brands it -# and lands it as one pull request, and its convergence deploys the site to -# stage and prod. 03-docs stays a landing of its own because it records what -# went live and puts back the two bootstrap deferrals. The numbering keeps its -# gap so the names stay the identities the task plane and `--phase` use. +# TWO STAGES (saas-orun-work WA5; blueprint.yaml's `spec.stages`). The build +# splits where its needs change: +# +# SCAFFOLD — 01-scaffold, GitHub only. The whole tree placed, branded and +# landed as one pull request, the repository created and linked — with +# the deploy lanes parked (tooling/bootstrap/deploys.mjs), so the merge's +# CI on main plans dev's verify lane and nothing else: green, and nothing +# deployed. An app with no Cloudflare connection stops here +# (`--until 01-scaffold`, the platform's `until: scaffold`) and is CODE +# ONLY: its repository, its CI and its pull requests' verify lanes all +# work; nothing runs anywhere. +# LIVE — 02-live, Cloudflare. The workers.dev subdomain bound (a late-bound +# input), the deploy lanes put back, the deploy credentials minted, one +# landing whose convergence deploys the site to stage and prod, watched +# to green and probed. A build with a connection runs it straight after +# the scaffold; a code-only app runs it later (`--resume`, which finds +# 01-scaffold placed and runs what follows). # -# One phase places NO modules: `03-docs` is hooks only. It is a phase because -# it is a separately landable unit with its own task and its own PR. +# A FULL BUILD ENDS EXACTLY WHERE THE ONE-LANDING SHAPE DID (baseline-v1's +# 01-product): the same tree on main, live on stage and prod, recorded, its +# gates restored. It pays for one more landing — the scaffold's — and nothing +# else: the scaffold's merge deploys nothing, so no convergence is waited on +# twice, and the live landing's convergence is the one 01-product watched. +# +# Only 01-scaffold places modules: 02-live and 03-docs are hooks only. Each +# is a phase because it is a separately landable unit with its own task and +# its own PR. A hook-only phase derives as `unknown` (the +# tree cannot answer for a landing or a deployment), so `--resume` always +# runs it again — every hook in both is idempotent — and no phase may +# REQUIRE one: both require 01-scaffold, the phase whose files say it ran. phases: - - name: 01-product - title: The site, built in one landing - description: The whole tree — manifests, tooling, CI, the identity and the site — branded, landed as one pull request, and deployed to stage and prod by one convergence. - # An estimate, not a measurement of this shape: a minute under the 4 it - # was, for what v2.88.0 takes out of the wait — the task set-up in the - # background, the landing checked here instead of by a runner's `plan`, - # the watch reading every 5 s instead of 40 (about a minute on - # turso-starter's measured build). The rest is the merge's convergence: - # the site's Vite build, deploy and smoke, stage and prod side by side. - expectedMinutes: 3 + - name: 01-scaffold + title: The site's code, landed + description: The whole tree — manifests, tooling, CI, the identity and the site — branded and landed as one pull request in a new repository, its deploy lanes parked, so CI on main is green and deploys nothing. Needs GitHub only. + # An estimate, not a measurement: the placement and the rebrand, the + # repository created and linked, the task found, the commit checked here + # and merged. Nothing is built or waited on: the merge's CI plans a verify + # lane and deploys nothing, and nothing watches it. + expectedMinutes: 1 narrate: - start: "Creating the repository and landing the whole site in one pull request — intent, CI, tooling, the welcome page, the server-function todos, the API route and the SSR demos. Then one convergence builds it with Cloudflare's Vite plugin and deploys it to stage and prod side by side. Usually about {{ .meta.expectedMinutes }} minutes." - await: "The site is building and deploying on both environments. A first deploy waits on its workers.dev route; nothing is stuck." - done: "{{ .inputs.reponame }} is live on stage and prod — {{ .meta.files }} files on main, branded as {{ .inputs.productname }}. That took {{ .meta.elapsed }}." - failed: "The site did not come up. The failing lane above names the step — the build, the deploy or the smoke — and a provider error is in its log." + start: "Creating the repository and landing the whole site in one pull request — intent, CI, tooling, the welcome page, the server-function todos, the API route and the SSR demos — with its deploy lanes parked until the site has somewhere to deploy to. Usually about {{ .meta.expectedMinutes }} minute." + done: "{{ .inputs.reponame }}'s code is on main — {{ .meta.files }} files, branded as {{ .inputs.productname }}. Its CI checks every change and deploys nothing yet. That took {{ .meta.elapsed }}." + failed: "The site's code did not land. The step above names what stopped it — the rebrand, the repository, its link to the workspace, or the landing's own check — and nothing was merged." modules: [ai-deployment, ai-operations, discovery-roots, github-workflows, rebrand-values, root-gitignore, root-intent, root-package-json, root-pnpm-lock, root-pnpm-workspace, root-readme, root-turbo, tooling-eslint, tooling-tsconfig, tooling-wire, vscode, web] - # THE PLATFORM MUST BE ABLE TO SEE THE REPOSITORY BEFORE IT EXISTS. Every - # phase lands a pull request that files under its task, and the platform - # learns of a PR only through the GitHub App installation on the account - # that OWNS the repository. So the owner's connection is asked for here, - # before a repository is created, and waited for like any other consent. - # And the Cloudflare connection, which the deploy credentials below are - # minted from — asked for here too, since this phase is the one that - # deploys. `requires.probe` asks reality what a lock file cannot: are both - # connections live right now? - requires: - probe: - - id: providers - uses: orun.doctor/check@v1 - with: - providers: [github, cloudflare] - githubOwner: "{{ .inputs.githuborg }}" - waitSeconds: 600 - pollSeconds: 20 + # GITHUB ONLY, AND NOT AS A CONNECTION ROW. The platform learns of a pull + # request only through the GitHub App installation on the account that + # OWNS the repository, and the proof of that is the repository's link to + # the workspace — which `link` below checks before anything lands. There + # is no `requires.probe` for GitHub: a connection probe reads the + # workspace's own connection list, and a repository orun.work keeps in its + # managed GitHub org is linked through a platform connection that list + # never shows, so the probe would wait out its ten minutes on a build that + # is ready. Cloudflare is 02-live's to ask for. hooks: post: - # A RE-RUN PHASE MUST HAVE SOMETHING TO LAND. A convergence can fail - # AFTER its PR merged, and the merge has already put every file this - # phase places on main; orun derives phase state from the tree, so a - # forced re-run lands an EMPTY diff while the site's CI plans - # `--changed`. So the phase rewrites ONE trailing marker line in each - # component.yaml its contract names — `# orun: redeploy <phase> - # <stamp>` — and the landing has a diff. The marker is a deploy - # trigger, not state: nothing reads it back. - - id: retouch - run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/retouch.mjs", "--phase", "{{ .phase.name }}", "--affects", "{{ .baseline.dir }}/.baseline/tasks/01-product.TaskContract.yaml"] # The identity chain. rebrand.mjs enumerates the tree with # `git ls-files`, so the output has to be a git repository with a # populated index BEFORE it runs. `git add -A` only stages; the landing @@ -456,8 +496,8 @@ phases: # 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. + # tenant's workspace on every remote op. The value travels through + # .rebrand/values.json, which the identity chain already reads. - id: orun-workspace run: - node @@ -486,19 +526,17 @@ phases: # every plan at two directories that do not exist. - id: work-tree run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/work-tree.mjs", "--strip"] - # STAGE AND PROD DEPLOY SIDE BY SIDE UNTIL THE BOOTSTRAP IS DONE. The - # promotion gate makes prod wait out stage's deploy; during a - # bootstrap both are empty and the landing is watched to green, so it - # protects nothing and doubles the convergence. Deferred here, - # restored by 03-docs. tooling/bootstrap/promotion.mjs. - - id: promotion - run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/promotion.mjs", "--defer"] - # DEV'S VERIFY LANES STAY OFF MAIN UNTIL THE BOOTSTRAP IS DONE, by the - # same mechanism: a third TanStack Start build on every merge proves nothing - # the baseline's own CI did not. Pull requests keep their dev lanes. - # tooling/bootstrap/dev-lanes.mjs. - - id: dev-lanes - run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/dev-lanes.mjs", "--defer"] + # THE DEPLOY LANES ARE PARKED UNTIL THE SITE GOES LIVE. Stage and prod + # deploy on every merge to main; until 02-live has minted the deploy + # credentials there is nothing to deploy with, and a code-only app + # would go red on every merge. So their push-to-main activation is + # deferred here and restored by 02-live; dev keeps its own, so a merge + # still plans (orun refuses a push plan no environment answers) and + # runs dev's verify lane — the site built and dry-deployed, no + # credential. Pull requests keep every verify lane. + # tooling/bootstrap/deploys.mjs. + - id: deploys + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/deploys.mjs", "--defer"] # Re-stage so `git ls-files` and `rebrand --verify` see the rewritten tree. - id: git-restage run: ["git", "add", "-A"] @@ -513,12 +551,13 @@ phases: 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. + # or the platform never sees its pull requests and the site's own CI + # cannot reach the platform: every 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 @@ -532,6 +571,112 @@ phases: - link - "{{ .inputs.orunWorkspace }}" - "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" + # 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: "Land the site's code" + prefix: BASE + contract: .baseline/tasks/01-scaffold.TaskContract.yaml + # THE SITE IS A PULL REQUEST THAT IS CHECKED, THEN MERGED — checked + # HERE (`checks: local`, orun >= v2.88.0): `orun validate`, then + # `orun plan` as the pull request and as the merge to main plan it, + # on the commit, before it is pushed. That is what the PR's `plan` + # job checks (the intent, every component and every composition + # resolve), plus the merge's own plan, in under a second instead of a + # runner's ~25 s. A tree that fails is never pushed. The PR's CI still + # runs (`plan` alone on a bootstrap branch, `orun/BASE-…`, ci.yml); + # nothing waits for it. The merge's run on main plans dev's verify + # lane and deploys nothing, so there is no convergence to await: the + # phase is done when the code is on main. + - id: land + uses: orun.pr/land@v1 + narrate: "The site's code is merged into main." + with: + task: "{{ .phase.hooks.task.outputs.key }}" + epic: "{{ .inputs.epicSlug }}" + branchSlug: "{{ .phase.name }}" + title: "feat: {{ .inputs.productname }}, the whole site from the TanStack Start template" + checks: local + + # Places nothing: it takes what 01-scaffold landed live. Its needs are the + # card's `requires.integrations` beyond GitHub — Cloudflare — so this is + # the first phase that asks for it. + - name: 02-live + title: The site, live on stage and prod + description: The site bound to its Cloudflare account's workers.dev subdomain, its deploy credentials minted, its deploy lanes put back, and one landing whose convergence deploys it to stage and prod, watched and probed. + # An estimate, not a measurement of this shape: what baseline-v1's + # 01-product took for its landing and convergence, less the placement now + # in 01-scaffold — the merge's convergence is the site's Vite build, + # deploy and smoke, stage and prod side by side, watched every 5 s. + expectedMinutes: 3 + narrate: + start: "Taking the site live: minting its deploy credentials from the Cloudflare connection and landing one pull request whose convergence builds the site with Cloudflare's Vite plugin and deploys it to stage and prod side by side. Usually about {{ .meta.expectedMinutes }} minutes." + await: "The site is building and deploying on both environments. A first deploy waits on its workers.dev route; nothing is stuck." + done: "{{ .inputs.reponame }} is live on stage and prod at {{ .inputs.subdomain }}.workers.dev. That took {{ .meta.elapsed }}." + failed: "The site did not come up. The failing step above names what stopped it — the subdomain, the credentials, or the convergence's build, deploy or smoke — and a provider error is in its log." + modules: [] + # The code must be on main, and Cloudflare connected. `requires.probe` + # asks reality what a lock file cannot: is the connection live right now? + # Asked once before the run's first phase and, if it is not, again just + # before this one, waiting up to ten minutes for a consent — so a build + # that has no connection yet still lands its code first. + requires: + phases: [01-scaffold] + probe: + - id: providers + uses: orun.doctor/check@v1 + with: + providers: [cloudflare] + waitSeconds: 600 + pollSeconds: 20 + hooks: + post: + # THE LATE-BOUND INPUT, BOUND. A code-only app's tree carries the + # placeholder subdomain; the run that goes live knows the account's + # real one and writes it where the placeholder stands — the + # component's smoke URL, intent.yaml's environment URLs, the operating + # contract, `.rebrand/values.json`. Refuses the placeholder itself: + # every URL below is built from it. A build that ran both stages at + # once already carries the real value, and this changes nothing. + # tooling/bootstrap/subdomain.mjs. + - id: subdomain + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/subdomain.mjs", "--bind", "{{ .inputs.subdomain }}"] + # The deploy lanes 01-scaffold parked: stage and prod deploy on a + # merge to main again, starting with this landing's. + - id: deploys + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/deploys.mjs", "--restore"] + # STAGE AND PROD DEPLOY SIDE BY SIDE UNTIL THE BOOTSTRAP IS DONE. The + # promotion gate makes prod wait out stage's deploy; during a + # bootstrap both are empty and the landing is watched to green, so it + # protects nothing and doubles the convergence. Deferred here, + # restored by 03-docs. tooling/bootstrap/promotion.mjs. + - id: promotion + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/promotion.mjs", "--defer"] + # DEV'S VERIFY LANES STAY OFF MAIN UNTIL THE BOOTSTRAP IS DONE, by the + # same mechanism: a third TanStack Start build beside the two deploys + # proves nothing the baseline's own CI did not, and competes with them + # for runners. Pull requests keep their dev lanes; 03-docs restores + # the push activation. tooling/bootstrap/dev-lanes.mjs. + - id: dev-lanes + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/dev-lanes.mjs", "--defer"] + # THIS LANDING MUST DEPLOY THE SITE, and a re-run must too. Restoring + # the lanes changes only intent.yaml's `environments`, which `orun + # plan --changed` maps to no component — and after a convergence + # that failed AFTER its PR merged, a forced re-run would land an + # EMPTY diff. So the phase rewrites ONE trailing marker line in each + # component.yaml its contract names — `# orun: redeploy <phase> + # <stamp>` — and the landing's merge plans those components on stage + # and prod. 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/02-live.TaskContract.yaml"] # 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 @@ -539,8 +684,7 @@ phases: # `workers-deploy` is the site's deploy (Workers Scripts); the account # id is a connection fact. The deploy lane binds both keys (the # workers-assets composition's `secretBindings`). Keys that already - # exist are kept. After the link, before the landing whose convergence - # uses them. + # exist are kept. Before the landing whose convergence uses them. - id: secrets uses: orun.integrations/reconcile@v1 with: @@ -548,38 +692,26 @@ phases: secrets: - { key: CLOUDFLARE_API_TOKEN, template: workers-deploy } - { key: CLOUDFLARE_ACCOUNT_ID, template: account-id } - # The task this landing closes, and its key. The run-level list above - # opens it in the background; this is the first hook that needs it, - # so it is the one that waits for that list (orun >= v2.88.0) — every - # hook before it ran while the task plane was still being set up. - id: task uses: orun.task/ensure@v1 with: kind: task epic: "{{ .inputs.epicSlug }}" milestone: "{{ .phase.name }}" - name: "Build the site in one landing" + name: "Take the site live" prefix: BASE - contract: .baseline/tasks/01-product.TaskContract.yaml - # THE SITE IS A PULL REQUEST THAT IS CHECKED, THEN MERGED — checked - # HERE (`checks: local`, orun >= v2.88.0): `orun validate`, then - # `orun plan` as the pull request and as the merge to main plan it, - # on the commit, before it is pushed. That is what the PR's `plan` - # job checks (the intent, every component and every composition - # resolve), plus the merge's own plan, in under a second instead of a - # runner's ~25 s. A tree that fails is never pushed. The PR's CI still - # runs (`plan` alone on a bootstrap branch, `orun/BASE-…`, ci.yml); - # nothing waits for it. The merge runs the site's build, deploy and - # smoke on main moments later, for real, and that convergence is what - # `await` watches to green. + contract: .baseline/tasks/02-live.TaskContract.yaml + # Checked here and merged, as 01-scaffold's landing is. The merge runs + # the site's build, deploy and smoke on main moments later, for real, + # and that convergence is what `await` watches to green. - id: land uses: orun.pr/land@v1 - narrate: "The site is merged into main." + narrate: "The site's deploy is merged into main." with: task: "{{ .phase.hooks.task.outputs.key }}" epic: "{{ .inputs.epicSlug }}" branchSlug: "{{ .phase.name }}" - title: "feat: {{ .inputs.productname }}, the whole site from the TanStack Start template" + title: "feat: {{ .inputs.productname }}, live on stage and prod" checks: local await: - id: converge @@ -587,7 +719,8 @@ phases: narrate: "The site built, deployed and passed its smoke, and the convergence run came back green." with: # The run for the commit THIS landing merged — the branch's newest - # run, read the moment the merge returns, may be another push's. + # run, read the moment the merge returns, may be another push's + # (01-scaffold's merge, moments earlier, has a run of its own). sha: "{{ .phase.hooks.land.outputs.mergeSha }}" repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 @@ -603,7 +736,7 @@ phases: - "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 + # Places nothing. It records what 02-live deployed, 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. @@ -618,11 +751,13 @@ phases: 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: [] + # 01-scaffold, not 02-live: a hook-only phase derives as `unknown`, and a + # requirement on one fails closed. `--resume` runs 02-live before this. requires: - phases: [01-product] + phases: [01-scaffold] hooks: post: - # THE SITE GOES LIVE WITH ITS PROMOTION GATE. 01-product deferred + # THE SITE GOES LIVE WITH ITS PROMOTION GATE. 02-live 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 @@ -630,7 +765,7 @@ phases: # 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). + # And dev verifies every merge to main again (02-live deferred it). - id: dev-lanes run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/dev-lanes.mjs", "--restore"] - id: render @@ -644,7 +779,7 @@ phases: name: "Record the live deployment" prefix: BASE contract: .baseline/tasks/03-docs.TaskContract.yaml - # Checked here and merged, as 01-product's landing is; nothing here + # Checked here and merged, as the other landings are; nothing here # builds. - id: land uses: orun.pr/land@v1 diff --git a/specs/epics/README.md b/specs/epics/README.md index 4058bd8..5d45ec1 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 | |------|---------|--------|------------| -| [`tanstack-start/`](./tanstack-start/) | **TS** | ✅ Shipped (`baseline-v1`); not yet live | Vercel's TanStack Start template — the welcome page, server-function todos kept in the visitor's cookie, an API route and the three SSR modes — on Cloudflare Workers + Static Assets via Cloudflare's Vite plugin, and an Orun baseline that instantiates it in one landing (TS2) | +| [`tanstack-start/`](./tanstack-start/) | **TS** | ✅ Shipped (`baseline-v1`; TS3 on `main` for `baseline-v2`); not yet live | Vercel's TanStack Start template — the welcome page, server-function todos kept in the visitor's cookie, an API route and the three SSR modes — on Cloudflare Workers + Static Assets via Cloudflare's Vite plugin, and an Orun baseline that instantiates it — the code with GitHub alone, then live with Cloudflare (TS2, TS3) | As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`. diff --git a/specs/epics/tanstack-start/IMPLEMENTATION-STATUS.md b/specs/epics/tanstack-start/IMPLEMENTATION-STATUS.md index 819cab7..e222cb2 100644 --- a/specs/epics/tanstack-start/IMPLEMENTATION-STATUS.md +++ b/specs/epics/tanstack-start/IMPLEMENTATION-STATUS.md @@ -5,6 +5,7 @@ | TS0 — the spec | ✅ | TS-1 | | TS1 — TanStack Start on Workers | ✅ | TS-2 | | TS2 — a baseline | ✅ | TS-3, tagged `baseline-v1` | +| TS3 — scaffold, then live | ✅ on `main` | TS-4, to be tagged `baseline-v2` | ## Departures from the upstream template @@ -37,3 +38,46 @@ from the browser; the drawer's SSR sub-menu is collapsed by default. The Worker: 1 360.69 KiB, 304.58 KiB gzipped, inside Workers Free's 3 MiB (`wrangler deploy --dry-run`, the same from `wrangler.jsonc` and from the plugin's `dist/server/wrangler.json`). + +## TS3 — scaffold, then live (as built) + +- **Three phases, two stages.** `01-scaffold` (GitHub only) places the whole + tree, brands it, parks stage's and prod's push activation and lands it; + `02-live` (Cloudflare) binds the subdomain, restores the lanes, defers the + promotion gate and dev's push lanes, retouches `web`, mints the two keys, + lands, watches and probes; `03-docs` restores the gate and dev's lanes and + records. The card's `spec.stages` is `{scaffold: 01-scaffold, live: + 02-live}`; `expectedMinutes` 5 (1 + 3 + 1), an estimate. +- **Dev keeps its push activation in the scaffold.** orun refuses a push plan + that no environment answers (`trigger binding "github-push-main" matched, + but no environment references it`), so parking all three would turn `main` + red; with dev left on, a code-only site's merge plans dev's verify lane — no + credential — and nothing else. `promotion` and `dev-lanes` moved to + `02-live`, the landing whose convergence they shorten. +- **The late-bound subdomain is bound by a hook.** A resume does not place + `01-scaffold`'s files again, so `02-live`'s `subdomain` hook rewrites the + placeholder as a whole DNS label in every tracked file, `.rebrand/values.json` + last, refusing the placeholder itself and a move from one real subdomain to + another. `03-docs` renders the record from the bound identity file. +- **No GitHub connection probe.** The scaffold's GitHub gate is `link` + (`orun cloud check`): a managed-GitHub repository is linked through a + platform connection the workspace's list never shows, so a `github` + doctor probe would time out on a ready build. Cloudflare is probed by + `02-live` alone, deferred to just before it when it is missing at the start. +- **Framing.** `apps/web/src/server.ts` is the Worker's entry (named in + `vite.config.ts` in place of `@tanstack/react-start/server-entry`, which it + wraps); `src/lib/framing.ts` holds the per-environment `frame-ancestors` + map — on stage `'self'`, orun.work's stage and prod origins and + `http://localhost:*`. The environment is written in at build time: + the component's `environmentBuildVar: DEPLOY_ENV` (stack-tectonic 0.19.0 + exports it to `build-app`), passed by `apps/web/turbo.json`'s `env`, and + `define`d as `__DEPLOY_ENV__`. The Worker grew by about 1 KiB (1 361.86 KiB, + 305.45 KiB gzipped). +- **Proven offline.** A full build ends on `baseline-v1`'s tree but for the + framing files and the redeploy marker's phase; its three merges plan dev's + verify lane, then the deploy to stage and prod side by side, then nothing; + a code-only build (`--until 01-scaffold`, no subdomain) taken live later + ends on the full build's tree byte for byte. Also run against orun v2.90.0 + (late-bound inputs), which refuses a run past the scaffold that would keep + the placeholder. + diff --git a/specs/epics/tanstack-start/README.md b/specs/epics/tanstack-start/README.md index 9c33cfa..2dd2962 100644 --- a/specs/epics/tanstack-start/README.md +++ b/specs/epics/tanstack-start/README.md @@ -11,7 +11,7 @@ somebody else's site in one landing.** | | | |---|---| -| Status | ✅ Shipped (`baseline-v1`) — proven offline in Baseline CI; not yet live (risk TS-A) | +| Status | ✅ Shipped (`baseline-v1`); TS3, the two-stage build, on `main` for `baseline-v2` — proven offline in Baseline CI; not yet live (risk TS-A) | | Upstream | [vercel/vercel › examples/tanstack-start](https://github.com/vercel/vercel/tree/main/examples/tanstack-start), at `84878e5` — Apache-2.0 | | Reference | [sveltekit-boilerplate](https://github.com/sourceplane/sveltekit-boilerplate) (the Vite-built Worker + Static Assets scaffolding, and the cookie-kept todos) | | Key | `TS` | @@ -34,3 +34,4 @@ somebody else's site in one landing.** | TS0 — the spec | the repository, its intent, CI, tooling and spec index; this doc set | TS-1 | | TS1 — TanStack Start on Workers | the template in `apps/web` on Cloudflare's Vite plugin, the cookie-kept todos, its tests, the README | TS-2 | | TS2 — a baseline | the console card, the build document, the context pack and the baseline's tests | TS-3 | +| TS3 — scaffold, then live | the build split at a declared stage (`01-scaffold` with GitHub alone, `02-live` with Cloudflare), the late-bound subdomain, and the stage Worker framable by orun.work (saas-orun-work WA5) | TS-4 | diff --git a/specs/epics/tanstack-start/epic.yaml b/specs/epics/tanstack-start/epic.yaml index 5fb9308..a29085f 100644 --- a/specs/epics/tanstack-start/epic.yaml +++ b/specs/epics/tanstack-start/epic.yaml @@ -28,3 +28,10 @@ spec: - "a site built from it carries the site only, renamed throughout to its own name, repository and Worker" - "Baseline CI is green: contract tests, generated component docs, the blueprint read by the pinned orun, the leak gate, the offline bootstrap and the end-to-end tier — the stage lane's steps in a staged job tree, the committed Worker config held to the one the Vite plugin writes, the Worker smoke-tested and walked" tasks: [TS-3] + - name: "TS3 — scaffold, then live" + exitCriteria: + - "the build splits at a declared stage: 01-scaffold lands the whole site with GitHub alone, its deploy lanes parked, and main's CI is green and deploys nothing; 02-live binds the late-bound subdomain, mints the Cloudflare credentials, restores the lanes and deploys to stage and prod; 03-docs records it" + - "the card declares spec.stages {scaffold: 01-scaffold, live: 02-live} and subdomain lateBound, and Orunbase's manifest parser accepts it" + - "a full build ends on baseline-v1's tree; a code-only build taken live later ends on the full build's, byte for byte" + - "the stage Worker sends a frame-ancestors policy naming orun.work's origins; prod sends none" + tasks: [TS-4] diff --git a/specs/epics/tanstack-start/implementation-plan.md b/specs/epics/tanstack-start/implementation-plan.md index 2bbbd1c..04d7e45 100644 --- a/specs/epics/tanstack-start/implementation-plan.md +++ b/specs/epics/tanstack-start/implementation-plan.md @@ -42,3 +42,20 @@ Worker config to the Vite plugin's, and walking every route of the staged Worker, the server functions called as the browser calls them (`testing/lib/serverfn-payload.mjs`). Done when every Baseline CI tier is green; tagged `baseline-v1`. + +## TS3 — scaffold, then live (TS-4) + +orun.work (saas-orun-work WA5) builds an app from this baseline in two +stages, and an account with no Cloudflare connection stops after the first. +So the one landing splits where its needs change: `01-scaffold` places, +brands and lands the whole site with GitHub alone, parking stage's and prod's +push activation (`tooling/bootstrap/deploys.mjs`) so main's CI is green and +deploys nothing; `02-live` binds the late-bound workers.dev subdomain +(`tooling/bootstrap/subdomain.mjs`), restores the lanes, mints the Cloudflare +credentials and lands the deploy, watched and probed; `03-docs` records it. +The card declares `spec.stages` and `lateBound: true` on `subdomain`; the +stage Worker sends a `frame-ancestors` policy naming orun.work's origins. +Done when every Baseline CI tier is green — a full build ending on +`baseline-v1`'s tree, a code-only build taken live later ending on the full +build's — and Orunbase's manifest parser reads the card; tagged +`baseline-v2`. diff --git a/specs/epics/tanstack-start/risks-and-open-questions.md b/specs/epics/tanstack-start/risks-and-open-questions.md index 64e68c2..671f913 100644 --- a/specs/epics/tanstack-start/risks-and-open-questions.md +++ b/specs/epics/tanstack-start/risks-and-open-questions.md @@ -2,7 +2,7 @@ | ID | Risk | State | |---|---|---| -| TS-A | No live bootstrap yet: the repository created and linked, the Cloudflare token minted, a real `wrangler deploy` and the probes are unproven | OPEN — one bootstrap from `baseline-v1` against a workspace closes it | +| TS-A | No live bootstrap yet: the repository created and linked, the Cloudflare token minted, a real `wrangler deploy` and the probes are unproven — nor the two-stage build's code-only stop and later go-live (TS3) | OPEN — one bootstrap from `baseline-v2` against a workspace, code only then live, timed on stage, closes it | | TS-B | The committed `wrangler.jsonc` describes the Worker the Vite plugin builds; a plugin release that changes its output (the entry's path, the module rule, the assets directory) would leave the deploy pointing at the wrong files | MITIGATED — the end-to-end tier compares the plugin's `dist/server/wrangler.json` with `wrangler.jsonc` and the two configs' dry-run uploads on every run, so a lockfile bump that changes either fails before a tag | | TS-C | The plugin warns on every build that `no_bundle` and `rules` are ignored under Vite | ACCEPTED — they are for the deploy; the warning is the cost of one config (design §3, §5) | | TS-D | Server functions are an internal protocol: `/_serverFn/<id>`, a seroval body, an `Origin` (or `Sec-Fetch-Site`) check that answers 403 otherwise. The end-to-end tier speaks it | ACCEPTED — the tier builds each body with the app's own seroval and reads each id from the build's own resolver, so an upgrade that changes the wire fails the tier, not the site | @@ -11,3 +11,7 @@ | TS-G | `nodejs_compat` is required: Start's server imports `node:async_hooks` and friends | ACCEPTED | | TS-H | stack-tectonic 0.19.0, not 0.20.0: 0.20.0's lane-scoped install links each job's `node_modules` out of its staged tree, and this site's build has not been tried in that layout | ACCEPTED — the pin keeps the layout the end-to-end tier proves | | TS-I | A custom domain is the owner's step: the site goes live on workers.dev, and attaching a domain needs zone permissions the brokered `workers-deploy` token does not carry | ACCEPTED | +| TS-J | Going live later needs the site's checkout as the build's `--out`: `02-live` requires `01-scaffold` derived from the tree and lands from its git, and a fresh, empty `--out` re-places the scaffold, whose landing is refused once `main` holds files the baseline does not (a code-only app's own work) | OPEN — the platform's go-live runs in a checkout of the app's `main` | +| TS-K | Going live in the container that built the scaffold needs orun v2.90.0, which exempts late-bound inputs from the resume rule; older ones refuse the real subdomain against the recorded placeholder (a fresh container records nothing) | OPEN — closes when v2.90.0 is the runner's | +| TS-L | Stage's `frame-ancestors` list narrows framing from any origin (no header at all) to the listed ones: orun.work served from another origin — a custom domain — cannot frame a stage site until it is listed and that site's stage redeploys | OPEN — orun.work's final origins listed in `apps/web/src/lib/framing.ts` before sites depend on them | +| TS-M | A code-only site's manual deploy of stage or prod (Orunbase's Deploy button) is refused by `orun plan` — `environment stage is not activated by trigger github-push-main` — with a red run, not a notice | ACCEPTED — there is no credential to deploy with until the live stage; the run says why | diff --git a/tasks/TS-4.TaskContract.yaml b/tasks/TS-4.TaskContract.yaml new file mode 100644 index 0000000..5ddddf3 --- /dev/null +++ b/tasks/TS-4.TaskContract.yaml @@ -0,0 +1,27 @@ +apiVersion: orun.io/v1 +kind: TaskContract +metadata: + name: TS-4 + title: "Scaffold, then live: the build splits at a declared stage" +spec: + goal: A site's code lands with GitHub alone and deploys nothing until a later live stage, declared to the platform as spec.stages, with the stage Worker framable by orun.work (saas-orun-work WA5) + affects: + - blueprint.yaml + - repo-blueprint.yaml + - BOOTSTRAP.md + - README.md + - intent.yaml + - .baseline + - .github/workflows/baseline.yml + - ai/context + - docs/phases + - testing + - tooling/bootstrap + - apps/web + - specs/epics + - tasks + doneWhen: + - every Baseline CI tier is green, the code-only build and its later go-live included + - Orunbase's blueprint-manifest parser reads the card's stages and late-bound subdomain + - the stage Worker answers with frame-ancestors naming orun.work's origins, and prod with none + gates: [] diff --git a/testing/bootstrap-defer.test.sh b/testing/bootstrap-defer.test.sh index 526e2b4..12c860d 100755 --- a/testing/bootstrap-defer.test.sh +++ b/testing/bootstrap-defer.test.sh @@ -1,10 +1,12 @@ #!/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. +# The three things a bootstrap turns off in intent.yaml and puts back — +# `prod.promotion` (tooling/bootstrap/promotion.mjs), dev's push-to-main +# activation (tooling/bootstrap/dev-lanes.mjs), and stage's and prod's +# push-to-main activation, the deploy lanes a code-only site runs without +# (tooling/bootstrap/deploys.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)" @@ -15,7 +17,7 @@ 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 +for tool in promotion dev-lanes deploys; 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" @@ -40,6 +42,29 @@ 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/deploys.mjs" --defer --file "$f" >/dev/null +python3 - "$f" <<'PY' && ok "stage and prod are not activated by github-push-main while deferred; dev still is" || bad "stage and prod are not activated by github-push-main while deferred; dev still is" +import sys, yaml +d = yaml.safe_load(open(sys.argv[1]))["environments"] +for env in ("stage", "prod"): + refs = d[env]["activation"]["triggerRefs"] + assert "github-push-main" not in refs and "github-pull-request" in refs, (env, refs) +# orun refuses a push plan no environment answers; dev answers it (and +# verifies), so a code-only site's merge still plans — and deploys nothing. +assert "github-push-main" in d["dev"]["activation"]["triggerRefs"], d["dev"] +assert "promotion" in d["prod"], "deploys.mjs touched prod's promotion gate" +PY +# 01-scaffold defers the deploy lanes; 02-live restores them and defers the +# other two; 03-docs restores those. The sequence must put back exactly the +# file it started from. +f="$tmp/intent.yaml"; cp "$root/intent.yaml" "$f" +for step in "deploys --defer" "deploys --restore" "promotion --defer" "dev-lanes --defer" \ + "promotion --restore" "dev-lanes --restore"; do + node "$root/tooling/bootstrap/${step%% *}.mjs" "${step#* }" --file "$f" >/dev/null +done +cmp -s "$f" "$root/intent.yaml" && ok "the bootstrap's whole sequence of deferrals restores byte-for-byte" \ + || bad "the bootstrap's whole sequence of deferrals restores byte-for-byte" +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 diff --git a/testing/e2e.test.sh b/testing/e2e.test.sh index 652f54b..d5eb748 100755 --- a/testing/e2e.test.sh +++ b/testing/e2e.test.sh @@ -46,7 +46,10 @@ # (testing/lib/serverfn-payload.mjs) — the visitor's starter list, a # todo added by the POST one and read back by the page and by the GET # one with the cookie it set, an empty todo refused, a cross-origin post -# refused — and an unknown path's 404. +# refused — and an unknown path's 404. And, because the lane built it +# for STAGE (`DEPLOY_ENV`), every page it renders names who may frame +# it — orun.work's preview pane among them (src/lib/framing.ts); the +# static files, which never reach the Worker, carry nothing. # # What it cannot do is the platform's half: create the repository, mint the # brokered Cloudflare token, deploy for real and probe workers.dev. That is a @@ -109,7 +112,7 @@ 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" +echo " 3 phases placed and landed" # ── 1. the finished site ─────────────────────────────────────────────────── echo "── the finished site: install, the fixture render, typecheck, lint, test, build" @@ -117,9 +120,9 @@ checks "$tree" "$scratch/checks-site.log" # ── 2. the deploy lane's steps, for stage ────────────────────────────────── echo "── the stage lane: build-app, verify-build-output, deploy-dry-run" -# The 01-product landing over the repository's empty first commit: every file +# The 01-scaffold landing over the repository's empty first commit: every file # of the site changed, as on its pull request. -s00="$(git -C "$tree" rev-parse HEAD~2)"; s01="$(git -C "$tree" rev-parse HEAD~1)" +s00="$(git -C "$tree" rev-parse HEAD~3)"; s01="$(git -C "$tree" rev-parse HEAD~2)" (cd "$tree" && orun plan --intent intent.yaml --trigger github-pull-request --changed \ --base "$s00" --head "$s01" --env stage --output "$scratch/plan.json") > "$scratch/plan.log" 2>&1 \ || { echo "FAIL: orun plan" >&2; tail -15 "$scratch/plan.log" >&2; exit 1; } @@ -160,6 +163,10 @@ else [ -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 +# The lane tells the build which environment it is for: the stage Worker's +# framing policy depends on it (component.yaml's environmentBuildVar). +grep -q '^export DEPLOY_ENV="stage"$' "$scratch/steps/build-app.sh" \ + || { echo "FAIL: the stage lane's build-app does not export DEPLOY_ENV=stage" >&2; cat "$scratch/steps/build-app.sh" >&2; exit 1; } for step in build-app verify-build-output deploy-dry-run; do [ -f "$scratch/steps/$step.sh" ] || { echo "FAIL: the stage verify lane has no $step step" >&2; exit 1; } echo " ▸ $step" @@ -419,12 +426,32 @@ nf = body.decode() if s != 404 or "<p>Not Found</p>" not in nf or 'href="/demo/start/server-funcs"' not in nf: bad(f"/no-such-page answered {s} without the not-found page in the layout") +# The stage Worker says who may frame it: orun.work's preview pane shows a +# site's stage deploy in an iframe. Every response the Worker renders carries +# the policy — a page, a 404, the API route, a server function; the static +# files never reach the Worker and carry none. +ORUN_WORK = ("https://orun-agent-web-stage.oruncloud.workers.dev", + "https://orun-agent-web-prod.oruncloud.workers.dev") +for path in ("/", "/demo/start/server-funcs", "/demo/start/ssr/spa-mode", "/no-such-page", "/demo/api/names"): + _, h, _ = get(path) + csp = h.get_all("content-security-policy") or [] + framing = [c for c in csp if c.startswith("frame-ancestors ")] + if len(framing) != 1 or not all(o in framing[0].split() for o in ORUN_WORK + ("'self'",)): + bad(f"{path} on stage does not let orun.work frame it: Content-Security-Policy {csp}") +_, h, _ = serverfn("getTodos") +if not any(c.startswith("frame-ancestors ") for c in h.get_all("content-security-policy") or []): + bad("a server function's answer from the stage Worker carries no framing policy") +_, h, _ = get("/robots.txt") +if h.get_all("content-security-policy"): + bad(f"/robots.txt, a static file, carries {h.get_all('content-security-policy')} — the Worker never saw it") +print(" framing: every page the stage Worker renders lets orun.work's preview pane frame it") + if problems: for p in problems: print(f" ✕ {p}", file=sys.stderr) sys.exit(1) print(" /, the client build, the static files, the API route and its page, the three SSR modes, " - "the todos, a 404 — the site's own") + "the todos, a 404, the stage framing policy — the site's own") PY echo "e2e.test.sh: ok" diff --git a/testing/lib/bootstrap.sh b/testing/lib/bootstrap.sh index 4289b20..8c536bb 100755 --- a/testing/lib/bootstrap.sh +++ b/testing/lib/bootstrap.sh @@ -5,6 +5,14 @@ # landing — minus the platform. Sourced by placement.test.sh and e2e.test.sh. # # bootstrap_offline <root> <tree> <values.json> <log-dir> [until-phase] +# bootstrap_init <tree> +# bootstrap_phase <root> <tree> <values.json> <log-dir> <phase> +# +# `bootstrap_offline` is `bootstrap_init`, then `bootstrap_phase` for every +# phase in order, stopping after `until-phase` when one is named (a code-only +# build stops after the scaffold stage: `--until 01-scaffold`). A build that +# goes on LATER — the live stage of a code-only app, with the late-bound +# subdomain it did not have before — is `bootstrap_phase` on the same tree. # # What stands in for the platform: # - the typed actions (`uses:` — task, repo, reconcile, land, watch, probe) @@ -18,23 +26,25 @@ # 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. +# deferrals and their restore, the subdomain bound, 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' +# The values file as `--set k=v` arguments, one per line pair. +_bootstrap_sets() { + python3 - "$1" <<'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}") + print("--set") + print(f"{k}={'true' if v is True else 'false' if v is False else v}") PY - ) - mkdir -p "$tree"/{apps,infra,packages,tests} "$logs" +} + +bootstrap_init() { + local tree="$1" d + mkdir -p "$tree"/{apps,infra,packages,tests} for d in apps infra packages tests; do touch "$tree/$d/.gitkeep"; done ( cd "$tree" @@ -43,28 +53,47 @@ PY git config user.name "offline bootstrap" git commit -q --allow-empty -m "Initial commit" ) || { echo "FAIL: the repository's first commit" >&2; return 1; } +} + +bootstrap_phase() { + local root="$1" tree="$2" values="$3" logs="$4" phase="$5" + local sets=() select=(--phase "$phase") first + mapfile -t sets < <(_bootstrap_sets "$values") + # The FIRST phase is placed the way a code-only build places it, `--until`: + # an orun that reads `lateBound` lets only a run that stops before the last + # phase keep a late-bound input's placeholder, and refuses `--phase` without + # the value. For the first phase the two select the same thing; for a later + # one `--until` would place its predecessors again, so they take `--phase`. + first="$(python3 -c "import yaml,sys;print(yaml.safe_load(open(sys.argv[1]))['phases'][0]['name'])" "$root/repo-blueprint.yaml")" + [ "$phase" = "$first" ] && select=(--until "$phase") + mkdir -p "$logs" + echo "── $phase: place" + if ! orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" "${select[@]}" \ + "${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; } +} +bootstrap_offline() { + local root="$1" tree="$2" values="$3" logs="$4" until="${5:-}" phase + bootstrap_init "$tree" || return 1 for phase in $(python3 -c "import yaml,sys;print(' '.join(p['name'] for p in yaml.safe_load(open(sys.argv[1]))['phases']))" "$root/repo-blueprint.yaml"); do - echo "── $phase: place" - if ! orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" --phase "$phase" \ - "${sets[@]}" > "$logs/place-$phase.log" 2>&1; then - echo "FAIL: $phase did not place" >&2; tail -20 "$logs/place-$phase.log" >&2; return 1 - fi - echo "── $phase: post hooks" - if ! python3 "$root/testing/lib/run-hooks.py" "$root/repo-blueprint.yaml" "$phase" post \ - "$tree" "$root" "$values" --skip link > "$logs/hooks-$phase.log" 2>&1; then - echo "FAIL: $phase's post hooks" >&2; tail -30 "$logs/hooks-$phase.log" >&2; return 1 - fi - sed 's/^/ /' "$logs/hooks-$phase.log" - # The landing: what the PR merges is what the next phase is placed onto. - ( - cd "$tree" - git config user.email bootstrap@example.invalid - git config user.name "offline bootstrap" - git checkout -q -B main 2>/dev/null || true - git add -A - git commit -q -m "land $phase" --allow-empty - ) || { echo "FAIL: $phase did not commit" >&2; return 1; } + bootstrap_phase "$root" "$tree" "$values" "$logs" "$phase" || return 1 [ "$phase" = "$until" ] && break done return 0 diff --git a/testing/manifest.test.sh b/testing/manifest.test.sh index a834d4d..0e99093 100755 --- a/testing/manifest.test.sh +++ b/testing/manifest.test.sh @@ -431,7 +431,91 @@ for path in manifests: 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 []))) + # ── stages: where a build may stop (saas-orun-work WA5) ─────────────── + # + # The platform's parser (`readStages` in orun-cloud's + # blueprint-manifest.ts) holds the block to its grammar: both stages, no + # third, each a phase name, the two different, neither named after the + # OTHER stage's key. Mirrored here, because the parser only ever sees + # this file at a tag, and a tag is never moved. + # + # What the parser cannot check is that the names are PHASES — it never + # reads the build document; the runner refuses an unknown one, mid-build. + # This file reads both, so it checks that here: each stage is a phase + # repo-blueprint.yaml declares, and scaffold runs before live. What each + # stage DOES (GitHub only, then the deploy) is phases.test.sh's. + stages = spec.get("stages") + phase_names = [p_.get("name") for p_ in bp_phases] + PHASE_NAME = re.compile(r"^[a-z0-9][a-z0-9._-]{0,79}$") + if stages is not None: + if not isinstance(stages, dict): + B("spec.stages must be a mapping {scaffold: <phase>, live: <phase>}") + stages = None + if stages is not None: + if set(stages) != {"scaffold", "live"}: + B(f"spec.stages declares {sorted(stages)}; it is exactly scaffold and live") + sc, lv = stages.get("scaffold"), stages.get("live") + for key, value in (("scaffold", sc), ("live", lv)): + if not isinstance(value, str) or not PHASE_NAME.match(value): + B(f"spec.stages.{key} is {value!r}, not a phase name") + elif value not in phase_names: + B(f"spec.stages.{key} names {value}, which repo-blueprint.yaml does not declare " + f"(its phases: {', '.join(phase_names)}) — the runner would refuse the build") + elif value in ("scaffold", "live") and value != key: + B(f"spec.stages.{key} names the phase {value!r}, the other stage's key — the " + f"platform accepts either, so the two must not cross") + if sc == lv: + B(f"spec.stages names {sc} for both stages — a build that stops after the scaffold " + f"must leave a phase to go live with") + elif sc in phase_names and lv in phase_names and phase_names.index(sc) > phase_names.index(lv): + B(f"spec.stages: scaffold {sc} runs after live {lv}") + # The preview is the stage environment: the app's stage URL is what + # orun.work frames, and its prod URL the live link (design WA-D9). + envs = (spec.get("verify") or {}).get("envs") or [] + if "stage" not in envs or "prod" not in envs: + B(f"spec.stages is declared and spec.verify.envs is {envs} — an eligible baseline " + f"names stage (the preview) and prod (the live link)") + + # ── lateBound: an input the scaffold stage runs without ─────────────── + # + # The parser's two rules: `lateBound` needs `spec.stages` (there is no + # "before its phase" without a stage boundary), and an input derived from + # a late-bound one is late too. And the one only this repository can + # check: the BUILD DOCUMENT must treat it the same way. A card input that + # is late-bound and a build input that is not would be refused by orun's + # resume rule when the live stage brings the real value; one the build + # requires with no default would refuse the scaffold build outright. + late = set() + for field in spec.get("inputs") or []: + key = field.get("key") + if "lateBound" in field and not isinstance(field.get("lateBound"), bool): + B(f"inputs[{key}].lateBound is {field.get('lateBound')!r}, not a boolean") + if field.get("lateBound") is True: + late.add(key) + if late and not spec.get("stages"): + B(f"inputs {sorted(late)} are lateBound and spec.stages is not declared — without a " + f"stage boundary there is no later phase to bind them in") + for field in spec.get("inputs") or []: + derive = field.get("derive") + if derive and field.get("key") not in late: + for ref in re.findall(r"\{([a-z][a-z0-9_]*)\}", derive): + if ref in late: + B(f"inputs[{field.get('key')}] derives from {{{ref}}}, which is lateBound — " + f"declare it lateBound too") + if bp is not None: + bp_in = bp.get("inputs") or {} + for key in sorted(input_keys - {"env"}): + build = bp_in.get(key) if isinstance(bp_in.get(key), dict) else {} + if (key in late) != (build.get("lateBound") is True): + B(f"inputs[{key}] is {'' if key in late else 'not '}lateBound on the card and " + f"{'' if build.get('lateBound') is True else 'not '}in repo-blueprint.yaml — " + f"the two must agree, or one side refuses the value the other defers") + if key in late and (build.get("required") or "default" not in build): + B(f"inputs[{key}] is lateBound, and repo-blueprint.yaml requires it or gives it no " + f"default — a build that stops after the scaffold has no value to give it") + + checked.append((name, len(declared), len((prog or {}).get("milestones") or []), + stages, sorted(late))) if problems: print("FAIL: a manifest and the blueprint disagree:", file=sys.stderr) @@ -439,8 +523,11 @@ if problems: print(f" - {p}", file=sys.stderr) sys.exit(1) -for name, ns, nm in checked: +for name, ns, nm, stages, late in checked: print(f" {name}: {ns} secret(s), {nm} milestone(s) agree with repo-blueprint.yaml") + if stages: + print(f" {name}: stages scaffold {stages['scaffold']} → live {stages['live']}; " + f"late-bound {', '.join(late) or 'none'}") PY echo "manifest.test.sh: ok" diff --git a/testing/phases.test.sh b/testing/phases.test.sh index 5db92e0..494597e 100755 --- a/testing/phases.test.sh +++ b/testing/phases.test.sh @@ -9,8 +9,13 @@ # at landing time, live, with nothing in this repository having looked wrong. # Moving one is a deliberate change, argued in the diff that edits both places. # -# ONE LANDING BUILDS THE SITE (SK-5, cirrus-baseline baseline-v22's shape): -# 01-product places every module, and 03-docs only records. +# ONE LANDING PLACES THE SITE (SK-5, cirrus-baseline baseline-v22's shape), +# AND THE BUILD SPLITS AT A DECLARED STAGE (saas-orun-work WA5): 01-scaffold +# places every module and lands them with GitHub alone, its deploy lanes +# parked; 02-live binds the late-bound subdomain, puts the lanes back, mints +# the Cloudflare credentials and watches the one convergence that deploys; +# 03-docs only records. blueprint.yaml's `spec.stages` names the two stages, +# and the stage rules below hold each to what it may need. # # And the shape that keeps a bootstrap fast (orun >= v2.88.0, turso-starter # baseline-v8's): the run-level task set-up runs in the background, each @@ -47,29 +52,32 @@ if not phases: PARTITION = { # One deployable component, `web`: the site's tests run inside it # (apps/web's vitest), so there is no test package to place beside it. - "01-product": ["ai-deployment", "ai-operations", "discovery-roots", "github-workflows", - "rebrand-values", "root-gitignore", "root-intent", - "root-package-json", "root-pnpm-lock", - "root-pnpm-workspace", "root-readme", "root-turbo", "tooling-eslint", - "tooling-tsconfig", "tooling-wire", "vscode", "web"], + "01-scaffold": ["ai-deployment", "ai-operations", "discovery-roots", "github-workflows", + "rebrand-values", "root-gitignore", "root-intent", + "root-package-json", "root-pnpm-lock", + "root-pnpm-workspace", "root-readme", "root-turbo", "tooling-eslint", + "tooling-tsconfig", "tooling-wire", "vscode", "web"], + "02-live": [], "03-docs": [], } -HOOK_ONLY = {"03-docs"} +HOOK_ONLY = {"02-live", "03-docs"} # The phases that DEPLOY, and so must give a re-run something to land. -DEPLOYS = {"01-product"} -# Each phase's pre, post and await hooks, in order — the one-landing recipe. -# The brokered keys are one `secrets` reconcile. No phase has a `pre` hook: -# the task is found in `post`, just before the landing, so that everything -# before it runs beside the background task set-up. 03-docs awaits nothing: -# its render probes as it writes, and its landing redeploys nothing. -PRE = {"01-product": [], "03-docs": []} +DEPLOYS = {"02-live"} +# Each phase's pre, post and await hooks, in order. The brokered keys are one +# `secrets` reconcile, in the live stage. 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. 01-scaffold awaits nothing (its +# merge deploys nothing), nor does 03-docs (its render probes as it writes, +# and its landing redeploys nothing). +PRE = {"01-scaffold": [], "02-live": [], "03-docs": []} POST = { - "01-product": ["retouch", "git-init", "git-stage", "rebrand", "orun-workspace", "work-tree", - "promotion", "dev-lanes", "git-restage", "rebrand-verify", - "repo", "link", "secrets", "task", "land"], + "01-scaffold": ["git-init", "git-stage", "rebrand", "orun-workspace", "work-tree", + "deploys", "git-restage", "rebrand-verify", "repo", "link", "task", "land"], + "02-live": ["subdomain", "deploys", "promotion", "dev-lanes", "retouch", + "secrets", "task", "land"], "03-docs": ["promotion", "dev-lanes", "render", "task", "land"], } -AWAIT = {"01-product": ["converge", "verify"], "03-docs": []} +AWAIT = {"01-scaffold": [], "02-live": ["converge", "verify"], "03-docs": []} by_name = {p["name"]: p for p in phases} names = [p["name"] for p in phases] @@ -168,6 +176,122 @@ for p in phases: 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')})") +# ── EVERY DEFERRAL IS PUT BACK ──────────────────────────────────────────── +# promotion.mjs, dev-lanes.mjs and deploys.mjs each park something in the +# site's intent.yaml for the bootstrap's sake. In phase order, each `--restore` +# must follow a `--defer`, and the last phase must leave nothing parked: a +# finished site deploys on every merge, prod after stage, dev verifying. +def tool_runs(p): + for h in ((p.get("hooks") or {}).get("post") or []): + argv = h.get("run") or [] + for tool in ("promotion", "dev-lanes", "deploys"): + if any(a.endswith(f"tooling/bootstrap/{tool}.mjs") for a in argv): + for mode in ("--defer", "--restore"): + if mode in argv: + yield tool, mode +for tool in ("promotion", "dev-lanes", "deploys"): + state, seen = "active", [] + for p in phases: + for t, mode in tool_runs(p): + if t != tool: + continue + seen.append(f"{p['name']} {mode}") + if mode == "--restore" and state != "deferred": + bad(f"{p['name']} restores {tool}.mjs, which nothing before it deferred") + state = "deferred" if mode == "--defer" else "active" + if state != "active": + bad(f"{tool}.mjs is deferred and never restored ({', '.join(seen)}) — the finished site " + f"would keep the bootstrap's shortcut") + +# ── THE STAGES (saas-orun-work WA5, blueprint.yaml `spec.stages`) ───────── +# SCAFFOLD needs GitHub only: no phase up to and including it may mint a +# credential, watch a convergence, probe a URL, ask for a provider other than +# github, or read a late-bound input (a code-only build does not have one); +# and it must park the deploy lanes before it lands, so main's CI deploys +# nothing. LIVE needs the card's `requires.integrations`: it asks for them, +# binds every late-bound input before it lands, puts the deploy lanes back, +# and deploys. +card = yaml.safe_load((root / "blueprint.yaml").read_text()) +cspec = (card or {}).get("spec") or {} +stages = cspec.get("stages") or {} +late = {f.get("key") for f in cspec.get("inputs") or [] if f.get("lateBound") is True} +needs = [i for i in ((cspec.get("requires") or {}).get("integrations") or []) if i != "github"] +def expressions(p): + """Every templated string a phase renders: argv, `with:`, narration, probes.""" + out = [] + def walk(v): + if isinstance(v, str): + out.append(v) + elif isinstance(v, dict): + for x in v.values(): + walk(x) + elif isinstance(v, list): + for x in v: + walk(x) + walk(p.get("hooks") or {}) + walk(p.get("narrate") or {}) + walk(((p.get("requires") or {}).get("probe")) or []) + return out +def post_ids(p): + return [h.get("id") for h in ((p.get("hooks") or {}).get("post") or [])] +def runs(p, tool, mode): + """The id of the post hook that runs tooling/bootstrap/<tool> <mode>, or None.""" + for h in ((p.get("hooks") or {}).get("post") or []): + argv = h.get("run") or [] + if any(a.endswith(f"tooling/bootstrap/{tool}") for a in argv) and mode in argv: + return h.get("id") + return None +if not stages: + bad("blueprint.yaml declares no spec.stages — the stage rules have nothing to hold") +else: + sc, lv = stages.get("scaffold"), stages.get("live") + if sc not in names or lv not in names: + bad(f"spec.stages names {sc} and {lv}; the phases are {names}") + else: + for p in phases[: names.index(sc) + 1]: + for h in hooks_of(p) + list(((p.get("requires") or {}).get("probe")) or []): + u = h.get("uses") or "" + if u.startswith(("orun.integrations/reconcile@", "orun.run/watch@", "orun.http/probe@")): + bad(f"{p['name']} is in the scaffold stage and runs {u} ({h.get('id')}) — " + f"scaffold needs GitHub only") + if u.startswith("orun.doctor/check@"): + others = [x for x in ((h.get("with") or {}).get("providers") or []) if x != "github"] + if others: + bad(f"{p['name']} is in the scaffold stage and asks for {others} — " + f"scaffold needs GitHub only") + for text in expressions(p): + for key in sorted(late): + if re.search(rf"\.inputs\.{key}\b", text): + bad(f"{p['name']} is in the scaffold stage and reads the late-bound input " + f"{key} — a code-only build runs it without one") + scp, lvp = by_name[sc], by_name[lv] + if names.index(sc) >= names.index(lv): + bad(f"scaffold {sc} does not run before live {lv}") + defer = runs(scp, "deploys.mjs", "--defer") + if not defer or post_ids(scp).index(defer) > post_ids(scp).index("land"): + bad(f"{sc} does not park the deploy lanes (deploys.mjs --defer) before it lands — " + f"main's CI would deploy without credentials") + if lv not in DEPLOYS: + bad(f"the live stage {lv} is not a deploying phase") + restore = runs(lvp, "deploys.mjs", "--restore") + if not restore or post_ids(lvp).index(restore) > post_ids(lvp).index("land"): + bad(f"{lv} does not put the deploy lanes back (deploys.mjs --restore) before it lands") + asked = set() + for h in ((lvp.get("requires") or {}).get("probe")) or []: + if (h.get("uses") or "").startswith("orun.doctor/check@"): + asked |= set((h.get("with") or {}).get("providers") or []) + for need in needs: + if need not in asked: + bad(f"the live stage {lv} does not ask for {need} (requires.probe), which the card " + f"requires — it would mint and deploy without checking the connection") + for key in sorted(late): + binds = [h.get("id") for h in ((lvp.get("hooks") or {}).get("post") or []) + if (h.get("run") and "--bind" in h["run"] + and any(f"{{{{ .inputs.{key} }}}}" == a for a in h["run"]))] + if not binds or post_ids(lvp).index(binds[0]) > post_ids(lvp).index("land"): + bad(f"the live stage {lv} does not bind the late-bound input {key} " + f"(a `--bind \"{{{{ .inputs.{key} }}}}\"` hook) before it lands") + # ── 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 @@ -332,6 +456,8 @@ placed_n = sum(len(p.get("modules") or []) for p in phases) narrated = sum(len(p.get("narrate") or {}) for p in phases) narrated += sum(1 for p in phases for h in hooks_of(p) if h.get("narrate")) print(f" {len(phases)} phases, {placed_n} modules, {len(HOOK_ONLY)} hook-only — in execution order") +print(f" stages: scaffold {stages.get('scaffold')} (GitHub only, deploy lanes parked), " + f"live {stages.get('live')} ({', '.join(needs)}; binds {', '.join(sorted(late)) or 'nothing'})") print(f" {narrated} authored narration lines, every reference resolving") PY diff --git a/testing/placement.test.sh b/testing/placement.test.sh index 214f0e3..3176a7b 100755 --- a/testing/placement.test.sh +++ b/testing/placement.test.sh @@ -14,13 +14,21 @@ # `run:` hooks (rebrand, re-tenant, work-tree strip, the deferrals, the # retouch marker, the deployment record), each landing a commit; # 3. the product it ends with: branded with no residue, carrying nothing of -# the factory, re-tenanted, its gates restored, its record rendered; -# 4. what the product's own CI would do with the 01-product merge: `orun -# plan` for a push to main over exactly that commit, onto the -# repository's empty first commit — the site deployed to stage and prod +# the factory, re-tenanted, its gates and deploy lanes restored, its +# record rendered; +# 4. what the product's own CI would do with each merge: `orun plan` for a +# push to main over exactly that commit — the scaffold's onto the +# repository's empty first commit (dev's verify lane, nothing deployed, +# no credential), the live stage's (the site deployed to stage and prod # side by side, nothing on dev, the Worker, the smoke and the secret refs -# the product's own; -# 5. a `--resume` over the finished site places nothing and un-brands nothing. +# the product's own), the record's (nothing); +# 5. a `--resume` over the finished site places nothing and un-brands +# nothing; +# 6. THE CODE-ONLY SITE (saas-orun-work WA5): a build with no subdomain +# stopped after 01-scaffold — the placeholder in place, the deploy lanes +# parked, main's plan deploying nothing — then taken live later with +# the account's subdomain, ending on exactly the tree the full build +# ended on. # # testing/e2e.test.sh goes on from here: it installs, builds and serves the # product and runs its smoke against it. @@ -77,7 +85,7 @@ bootstrap_offline "$root" "$tree" "$values" "$scratch/logs" > "$scratch/bootstra echo "FAIL: the offline bootstrap stopped" >&2; tail -40 "$scratch/bootstrap.log" >&2; exit 1; } grep -E '^── ' "$scratch/bootstrap.log" | sed 's/^/ /' commits="$(git -C "$tree" rev-list --count HEAD)" -[ "$commits" = 3 ] || fail "the repository has $commits commits, not its first one and one per phase (1 + 2)" +[ "$commits" = 4 ] || fail "the repository has $commits commits, not its first one and one per phase (1 + 3)" # ── 3. the product it ends with ──────────────────────────────────────────── echo "── the site it produced" @@ -157,6 +165,13 @@ if "promotion" not in intent["environments"]["prod"] or "@promotion-deferred" in bad("prod's promotion gate was not restored by 03-docs") if "github-push-main" not in intent["environments"]["dev"]["activation"]["triggerRefs"] or "@dev-lanes-deferred" in intent_text: bad("dev's push activation was not restored by 03-docs") +for env in ("stage", "prod"): + if "github-push-main" not in intent["environments"][env]["activation"]["triggerRefs"]: + bad(f"{env}'s push activation (its deploy lane) was not restored by 02-live") +if "@deploys-deferred" in intent_text: + bad("intent.yaml still carries a @deploys-deferred marker") +if json.loads((tree / ".rebrand/values.json").read_text()).get("subdomain") != sub: + bad("the identity file does not record the site's subdomain") for env in ("stage", "prod"): want = f"https://{repo}-web-{env}.{sub}.workers.dev" if intent["environments"][env].get("url") != want: @@ -166,8 +181,8 @@ for page in (intent.get("repo") or {}).get("docs", {}).get("pages", []): bad(f"intent repo.docs names {page['path']}, which the site does not have") # The landings, as the phases made them. -if not re.search(r"^# orun: redeploy 01-product \S+$", (tree / "apps/web/component.yaml").read_text(), re.M): - bad("apps/web/component.yaml carries no 01-product redeploy marker") +if not re.search(r"^# orun: redeploy 02-live \S+$", (tree / "apps/web/component.yaml").read_text(), re.M): + bad("apps/web/component.yaml carries no 02-live redeploy marker") dep = (tree / "ai/context/deployment.md").read_text() if "GENERATED by the `03-docs` phase" not in dep or f"https://{repo}-web-prod.{sub}.workers.dev" not in dep: bad("ai/context/deployment.md was not rendered for the site") @@ -189,28 +204,55 @@ if problems: print(f" {len(tracked)} tracked files; branded, re-tenanted, gates restored, record rendered") PY -# ── 4. the product's own CI, over the 01-product merge ───────────────────── -# The one landing's push: from the repository's empty first commit to the -# whole site, as main sees it the moment the pull request merges. -echo "── orun plan in the site, for the push that merged 01-product" -s00="$(git -C "$tree" rev-parse HEAD~2)"; s01="$(git -C "$tree" rev-parse HEAD~1)" -git -C "$tree" checkout -q "$s01" -(cd "$tree" && orun validate --intent intent.yaml) > "$scratch/validate.log" 2>&1 \ - || { fail "orun validate refused the site's intent at 01-product"; tail -10 "$scratch/validate.log" >&2; } -(cd "$tree" && orun plan --intent intent.yaml --trigger github-push-main --changed \ - --base "$s00" --head "$s01" --output "$scratch/plan.json") > "$scratch/plan.log" 2>&1 \ - || { fail "orun plan failed in the site at 01-product"; tail -15 "$scratch/plan.log" >&2; } -git -C "$tree" checkout -q main -python3 - "$scratch/plan.json" "$values" <<'PY' || fails=$((fails + 1)) +# ── 4. the product's own CI, over each merge ────────────────────────────── +# Each landing's push, as main sees it the moment its pull request merges. +echo "── orun plan in the site, for the push each landing merged" +s00="$(git -C "$tree" rev-parse HEAD~3)"; s01="$(git -C "$tree" rev-parse HEAD~2)" +s02="$(git -C "$tree" rev-parse HEAD~1)"; s03="$(git -C "$tree" rev-parse HEAD)" +push_plan() { # TREE BASE HEAD OUT — `orun plan` for a push to main, at HEAD + local t="$1" base="$2" head="$3" out="$4" + git -C "$t" checkout -q "$head" + (cd "$t" && orun validate --intent intent.yaml) > "$out.validate.log" 2>&1 \ + || { fail "orun validate refused the site's intent at $head"; tail -10 "$out.validate.log" >&2; } + (cd "$t" && orun plan --intent intent.yaml --trigger github-push-main --changed \ + --base "$base" --head "$head" --output "$out") > "$out.log" 2>&1 \ + || { fail "orun plan failed in the site at $head"; tail -15 "$out.log" >&2; } + git -C "$t" checkout -q main +} +push_plan "$tree" "$s00" "$s01" "$scratch/plan-01.json" +push_plan "$tree" "$s01" "$s02" "$scratch/plan-02.json" +push_plan "$tree" "$s02" "$s03" "$scratch/plan-03.json" +python3 - "$scratch" "$values" <<'PY' || fails=$((fails + 1)) import json, sys -plan, values = json.load(open(sys.argv[1])), json.load(open(sys.argv[2])) +scratch, values = sys.argv[1], json.load(open(sys.argv[2])) repo, sub, ws = values["reponame"], values["subdomain"], values["orunWorkspace"] problems = [] def bad(m): problems.append(m) -jobs = {(j["component"], j["environment"]): j for j in plan["jobs"]} -if set(jobs) != {("web", "stage"), ("web", "prod")}: - bad(f"the 01-product merge plans {sorted(jobs)}; it must deploy web to stage and prod and nothing else") -for (comp, env), j in jobs.items(): +def jobs(n): + try: + plan = json.load(open(f"{scratch}/plan-{n}.json")) + except FileNotFoundError: + bad(f"no plan for the {n} merge") + return {} + return {(j["component"], j["environment"]): j for j in plan["jobs"]} + +# The scaffold: the deploy lanes are parked, so the push plans dev's verify +# lane — built and dry-deployed — binds no credential, and deploys nothing. +scaffold = jobs("01") +if set(scaffold) != {("web", "dev")}: + bad(f"the 01-scaffold merge plans {sorted(scaffold)}; it must verify web on dev and deploy nothing") +for (comp, env), j in scaffold.items(): + if not j["profile"].endswith(".verify"): + bad(f"the 01-scaffold merge plans {comp}@{env} with {j['profile']}, not a verify") + if j.get("secretRefs"): + bad(f"the 01-scaffold merge's {comp}@{env} resolves {[r['asEnv'] for r in j['secretRefs']]} — " + f"a code-only site has no credential to give it") + +# The live stage: the site deployed to stage and prod side by side. +live = jobs("02") +if set(live) != {("web", "stage"), ("web", "prod")}: + bad(f"the 02-live merge plans {sorted(live)}; it must deploy web to stage and prod and nothing else") +for (comp, env), j in live.items(): if not j["profile"].endswith(".deploy"): bad(f"{comp}@{env} plans profile {j['profile']}, not a deploy") if j.get("dependsOn"): @@ -219,6 +261,8 @@ for (comp, env), j in jobs.items(): for need in ("build-app", "deploy", "smoke"): if need not in steps: bad(f"{comp}@{env} has no {need} step") + if f'export DEPLOY_ENV="{env}"' not in steps.get("build-app", ""): + bad(f"{comp}@{env}'s build is not told its environment (DEPLOY_ENV) — the stage Worker's framing policy needs it") if f'EFFECTIVE_WORKER_NAME="{repo}-web-{env}"' not in steps.get("deploy", ""): bad(f"{comp}@{env} deploys a Worker not named {repo}-web-{env}") if f'DEPLOYED_URL="https://${{EFFECTIVE_WORKER_NAME}}.${{WORKERS_DEV_SUBDOMAIN}}.workers.dev"' not in steps.get("smoke", "") \ @@ -232,11 +276,18 @@ for (comp, env), j in jobs.items(): ref = refs.get(key, "") if not ref.startswith(f"secret://{ws}/") or f"project:{repo}" not in ref: bad(f"{comp}@{env} resolves {key} from {ref or 'nowhere'} — not the site's workspace and project") + +# The record: intent.yaml's environments and the docs — no component. +docs = jobs("03") +if docs: + bad(f"the 03-docs merge plans {sorted(docs)}; it changes no component and must deploy nothing") if problems: for p in problems: print(f" ✕ {p}", file=sys.stderr) sys.exit(1) -print(f" web → stage + prod, deploy, side by side; Worker, smoke and secrets the site's own") +print(" 01-scaffold → web verified on dev, nothing deployed, no credential") +print(" 02-live → web deployed to stage + prod side by side; Worker, smoke, secrets and DEPLOY_ENV the site's own") +print(" 03-docs → nothing") PY # ── 5. a resume over the finished site ──────────────────────────────────── @@ -250,5 +301,74 @@ grep -q "SITE_NAME = \"Sam's Notes & Links\"" "$tree/apps/web/src/lib/site.ts" \ || fail "--resume reverted the site's identity" [ "$fails" -eq 0 ] && echo " nothing placed again, nothing un-branded" +# ── 6. a code-only site, then live ──────────────────────────────────────── +# The build an account with no Cloudflare connection gets (`--until +# 01-scaffold`, the platform's `until: scaffold`): no subdomain to read, so +# the late-bound input falls to its placeholder. +echo "── a code-only site: --until 01-scaffold, with no subdomain" +code="$scratch/code-only/$repo" +python3 - "$values" "$scratch/code-only.json" <<'PY' +import json, sys +v = json.load(open(sys.argv[1])) +v.pop("subdomain") +json.dump(v, open(sys.argv[2], "w")) +PY +bootstrap_offline "$root" "$code" "$scratch/code-only.json" "$scratch/code-logs" 01-scaffold \ + > "$scratch/code-only.log" 2>&1 || { echo "FAIL: the code-only bootstrap stopped" >&2; tail -40 "$scratch/code-only.log" >&2; exit 1; } +[ "$(git -C "$code" rev-list --count HEAD)" = 2 ] || fail "the code-only site is not its first commit and one landing" +(cd "$code" && node "$root/tooling/rebrand/rebrand.mjs" --verify --values .rebrand/values.json) > "$scratch/code-verify.log" 2>&1 \ + || { fail "rebrand --verify refused the code-only site"; cat "$scratch/code-verify.log" >&2; } +[ "$(cd "$code" && node "$root/tooling/bootstrap/subdomain.mjs" --check)" = placeholder ] \ + || fail "the code-only site does not record the placeholder subdomain" +for t in deploys:deferred promotion:enforced dev-lanes:active; do + [ "$(node "$root/tooling/bootstrap/${t%%:*}.mjs" --check --file "$code/intent.yaml")" = "${t#*:}" ] \ + || fail "the code-only site's ${t%%:*} is not ${t#*:}" +done +push_plan "$code" "$(git -C "$code" rev-parse HEAD~1)" "$(git -C "$code" rev-parse HEAD)" "$scratch/plan-code.json" +python3 - "$scratch/plan-code.json" <<'PY' || fails=$((fails + 1)) +import json, sys +jobs = [(j["component"], j["environment"], j["profile"].split(".")[-1], bool(j.get("secretRefs"))) + for j in json.load(open(sys.argv[1]))["jobs"]] +if jobs != [("web", "dev", "verify", False)]: + print(f" ✕ the code-only site's merge plans {jobs}; CI on main must verify on dev and deploy nothing", file=sys.stderr) + sys.exit(1) +print(" placeholder subdomain, deploy lanes parked; main's plan: web verified on dev, nothing deployed") +PY + +# …and later, live: the account connected, its subdomain known. A fresh +# container carries no `.orun/` (no checkout does), so nothing recorded the +# placeholder there; an orun that reads `lateBound` lets the live run differ +# from the record even in the container that ran the scaffold. +echo "── the same site taken live later: 02-live and 03-docs, with the subdomain" +rm -rf -- "$code/.orun" +for phase in 02-live 03-docs; do + bootstrap_phase "$root" "$code" "$values" "$scratch/code-logs" "$phase" > "$scratch/code-$phase.log" 2>&1 \ + || { echo "FAIL: the code-only site's $phase" >&2; tail -40 "$scratch/code-$phase.log" >&2; exit 1; } +done +grep -q 'subdomain --bind: .* bound in ' "$scratch/code-logs/hooks-02-live.log" \ + || fail "02-live did not bind the subdomain into the code-only site" +# The resume does not place 01-scaffold's files again, so 02-live's own hook +# is all that replaces the placeholder: nowhere in the site may it be left. +left="$(cd "$code" && git grep -l -E '(^|[^A-Za-z0-9-])your-workers-subdomain([^A-Za-z0-9-]|$)' || true)" +[ -z "$left" ] || fail "the placeholder subdomain is still in the code-only site after 02-live: $left" +push_plan "$code" "$(git -C "$code" rev-parse HEAD~2)" "$(git -C "$code" rev-parse HEAD~1)" "$scratch/plan-code-live.json" +python3 - "$scratch/plan-code-live.json" <<'PY' || fails=$((fails + 1)) +import json, sys +jobs = sorted((j["component"], j["environment"], j["profile"].split(".")[-1]) + for j in json.load(open(sys.argv[1]))["jobs"]) +if jobs != [("web", "prod", "deploy"), ("web", "stage", "deploy")]: + print(f" ✕ the code-only site's 02-live merge plans {jobs}; it must deploy web to stage and prod", file=sys.stderr) + sys.exit(1) +PY +# It ends where the full build ended: the same tree, but for the stamps of +# when each one ran (the redeploy marker, the record's probe time). +if diff -r -x .git -x .orun \ + -I '^# orun: redeploy ' -I 'GENERATED by the `03-docs` phase on' -I '^## Public URLs (probed ' \ + "$tree" "$code" > "$scratch/code-vs-full.diff"; then + echo " 02-live bound the subdomain and deployed; the site is the full build's, byte for byte" +else + fail "the code-only site taken live is not the tree the full build made:"; head -40 "$scratch/code-vs-full.diff" >&2 +fi + [ "$fails" -eq 0 ] || { echo "placement.test.sh: $fails failure(s)" >&2; exit 1; } echo "placement.test.sh: ok" diff --git a/testing/retouch.test.sh b/testing/retouch.test.sh index e524cd9..137d524 100755 --- a/testing/retouch.test.sh +++ b/testing/retouch.test.sh @@ -193,7 +193,7 @@ while IFS= read -r line; do bad "a retouch hook does not resolve: $argv"; sed 's/^/ /' "$tmp/hook.log" >&2 fi done < <(grep -E '^\s*run: \[.*retouch\.mjs' "$root/repo-blueprint.yaml") -[ "$hooks" -ge 1 ] || bad "only $hooks retouch hook(s) in repo-blueprint.yaml — 01-product lands the deployable site and needs one" +[ "$hooks" -ge 1 ] || bad "only $hooks retouch hook(s) in repo-blueprint.yaml — 02-live deploys the site and needs one" [ "$fail" -eq 0 ] || exit 1 echo "retouch.test.sh: ok" diff --git a/testing/subdomain.test.sh b/testing/subdomain.test.sh new file mode 100644 index 0000000..28b1d0f --- /dev/null +++ b/testing/subdomain.test.sh @@ -0,0 +1,120 @@ +#!/usr/bin/env bash +# THE LATE-BOUND SUBDOMAIN IS BOUND WHERE THE PLACEHOLDER STANDS, ONCE. +# +# A code-only site — a build that stopped after 01-scaffold, with no +# Cloudflare connection to read a workers.dev subdomain from — carries the +# placeholder `your-workers-subdomain` in its component, its intent, its +# operating contract and its identity file. 02-live's `subdomain` hook +# (tooling/bootstrap/subdomain.mjs --bind) writes the account's real +# subdomain there before anything deploys, and must: +# +# - replace the placeholder as a whole DNS label, in every tracked file, +# and record the value in .rebrand/values.json LAST; +# - change nothing on a site that already has it (a build that ran both +# stages at once), and nothing on a second run; +# - refuse the placeholder and an empty value (the live stage may never +# keep it), a value that is not a subdomain, and a MOVE from one real +# subdomain to another; +# - finish a bind that was interrupted. +# +# Needs: node, git, python3 (+PyYAML). No network. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" +tool="$root/tooling/bootstrap/subdomain.mjs" +identity="$here/fixtures/baseline-identity.tanstack-start.json" +fail=0 +ok() { echo " ok $1"; } +bad() { echo " ✕ $1" >&2; fail=1; } +scratch="$(mktemp -d)"; trap 'rm -rf "$scratch"' EXIT + +# A site as 01-scaffold leaves it without a subdomain: the four places the +# placeholder stands, and one file whose value merely CONTAINS it. +site() { # DIR SUBDOMAIN-RECORDED + local d="$1" rec="$2" + mkdir -p "$d/.rebrand" "$d/apps/web" "$d/ai/context" "$d/notes" + cat > "$d/.rebrand/values.json" <<JSON +{ + "reponame": "acme-notes", + "productname": "Acme Notes", + "productdomain": "", + "subdomain": "$rec", + "orunWorkspace": "ws_X", + "githuborg": "acme-inc", + "epicSlug": "tanstack-start-baselining" +} +JSON + printf 'spec:\n parameters:\n workersDevSubdomain: your-workers-subdomain\n' > "$d/apps/web/component.yaml" + printf 'environments:\n stage:\n url: https://acme-notes-web-stage.your-workers-subdomain.workers.dev\n prod:\n url: https://acme-notes-web-prod.your-workers-subdomain.workers.dev\n' > "$d/intent.yaml" + printf "curl https://acme-notes-web-stage.your-workers-subdomain.workers.dev/\n" > "$d/ai/context/operations.md" + printf 'another site: https://x-web-stage.your-workers-subdomain-2.workers.dev\n' > "$d/notes/other.md" + git -C "$d" init -q && git -C "$d" add -A +} +bind() { (cd "$1" && node "$tool" --baseline-identity "$identity" --bind "$2"); } +snapshot() { (cd "$1" && find . -path ./.git -prune -o -type f -print0 | LC_ALL=C sort -z | xargs -0 cksum); } + +echo "── a code-only site goes live" +s="$scratch/code-only"; site "$s" your-workers-subdomain +cp "$s/.rebrand/values.json" "$scratch/values.before" +bind "$s" acme > "$scratch/bind.log" 2>&1 || { bad "--bind acme failed"; cat "$scratch/bind.log" >&2; } +grep -q 'workersDevSubdomain: acme$' "$s/apps/web/component.yaml" && ok "the component's smoke URL takes the subdomain" || bad "component.yaml not bound" +[ "$(grep -c '\.acme\.workers\.dev' "$s/intent.yaml")" = 2 ] && ok "both environment URLs in intent.yaml" || bad "intent.yaml not bound" +grep -q 'acme-notes-web-stage\.acme\.workers\.dev' "$s/ai/context/operations.md" && ok "the operating contract's example" || bad "operations.md not bound" +grep -q 'your-workers-subdomain-2' "$s/notes/other.md" && ok "a subdomain that merely contains the placeholder is left alone" || bad "your-workers-subdomain-2 was rewritten" +changed_lines="$(diff "$scratch/values.before" "$s/.rebrand/values.json" | grep -c '^[<>]' || true)" +[ "$changed_lines" = 2 ] && grep -q '"subdomain": "acme",' "$s/.rebrand/values.json" \ + && ok ".rebrand/values.json records it, and only that line changed" || bad ".rebrand/values.json was not rewritten as one line" +[ "$(cd "$s" && node "$tool" --baseline-identity "$identity" --check)" = "bound acme" ] && ok "--check says bound acme" || bad "--check" +grep -q 'bound in 4 file' "$scratch/bind.log" && ok "it says which files it changed" || bad "the summary: $(cat "$scratch/bind.log")" + +before="$(snapshot "$s")" +bind "$s" acme > "$scratch/again.log" 2>&1 || bad "a second --bind acme failed" +[ "$before" = "$(snapshot "$s")" ] && grep -q 'already bound' "$scratch/again.log" \ + && ok "a second bind changes nothing and says so" || bad "a second bind changed the tree" + +echo "── what it refuses" +for value in your-workers-subdomain "" "Not_A_Subdomain" "-acme"; do + t="$scratch/refuse-$RANDOM"; site "$t" your-workers-subdomain; b="$(snapshot "$t")" + if bind "$t" "$value" > "$t.log" 2>&1; then + bad "--bind '$value' passed" + else + [ "$b" = "$(snapshot "$t")" ] && ok "--bind '${value}' is refused, and nothing is written" || bad "--bind '$value' wrote before refusing" + fi +done +grep -q 'needs the workers.dev subdomain' "$scratch"/refuse-*.log && ok "the refusal names what the live stage needs" \ + || bad "the placeholder's refusal does not say what is needed" +t="$scratch/moved"; site "$t" acme +sed -i 's/your-workers-subdomain\b/acme/; s/\.your-workers-subdomain\./.acme./g' "$t/apps/web/component.yaml" "$t/intent.yaml" "$t/ai/context/operations.md" +git -C "$t" add -A; b="$(snapshot "$t")" +if bind "$t" other > "$t.log" 2>&1; then bad "moving acme → other passed"; else + [ "$b" = "$(snapshot "$t")" ] && grep -q 'bound to acme.workers.dev' "$t.log" \ + && ok "a site bound to acme is not moved to another account's subdomain" || bad "the move refusal wrote, or did not say why" +fi + +echo "── a site built with its subdomain from the start" +t="$scratch/full"; site "$t" acme +sed -i 's/workersDevSubdomain: your-workers-subdomain$/workersDevSubdomain: acme/; s/\.your-workers-subdomain\./.acme./g' \ + "$t/apps/web/component.yaml" "$t/intent.yaml" "$t/ai/context/operations.md" +git -C "$t" add -A; b="$(snapshot "$t")" +bind "$t" acme > "$t.log" 2>&1 && [ "$b" = "$(snapshot "$t")" ] \ + && ok "binding the subdomain it already has changes nothing" || bad "a full build's bind changed the tree: $(cat "$t.log")" + +echo "── an interrupted bind is finished by the next" +t="$scratch/half"; site "$t" your-workers-subdomain +sed -i 's/workersDevSubdomain: your-workers-subdomain$/workersDevSubdomain: acme/' "$t/apps/web/component.yaml" +git -C "$t" add -A +bind "$t" acme > "$t.log" 2>&1 && ! grep -rq 'your-workers-subdomain\.' "$t/intent.yaml" "$t/ai" \ + && grep -q '"subdomain": "acme"' "$t/.rebrand/values.json" \ + && ok "the record still named the placeholder, so the bind ran again over what was left" || bad "the half-done bind: $(cat "$t.log")" + +echo "── the placeholder is the one the build document defaults to" +python3 - "$root" <<'PY' && ok "repo-blueprint.yaml's subdomain default = .baseline/identity.json's subdomain" || bad "the subdomain placeholder is spelled two ways" +import json, pathlib, sys, yaml +root = pathlib.Path(sys.argv[1]) +default = yaml.safe_load((root / "repo-blueprint.yaml").read_text())["inputs"]["subdomain"]["default"] +declared = json.loads((root / ".baseline/identity.json").read_text())["subdomain"] +assert default == declared, (default, declared) +PY + +[ "$fail" -eq 0 ] || { echo "subdomain.test.sh: failure(s)" >&2; exit 1; } +echo "subdomain.test.sh: ok" diff --git a/tooling/bootstrap/deploys.mjs b/tooling/bootstrap/deploys.mjs new file mode 100644 index 0000000..a0839cb --- /dev/null +++ b/tooling/bootstrap/deploys.mjs @@ -0,0 +1,137 @@ +#!/usr/bin/env node +// The deploy lanes stay off main until the site has somewhere to deploy to +// (zero-dependency). +// +// intent.yaml activates `stage` and `prod` on `github-push-main` as well as on +// pull requests, and the component deploys on that trigger (apps/web's +// `profileRules`: `deploy` when `triggerRef: github-push-main`). That is the +// right rule for a site that is live. It is the wrong one for a site whose +// code exists before its Cloudflare account does: the build splits into a +// SCAFFOLD stage that needs GitHub only (the code placed, branded, landed) +// and a LIVE stage that needs Cloudflare (the deploy credentials minted, the +// deploy watched, the URLs probed). An app with no Cloudflare connection yet +// stops after the scaffold, and every merge to its `main` would otherwise +// plan a deploy whose credentials do not exist — a red CI on every merge, for +// as long as the app is code only. +// +// So the scaffold phase parks the two deploy rungs' push-to-main activation +// and the live phase puts it back, exactly as promotion.mjs and dev-lanes.mjs +// do for prod's gate and dev's verify lanes: +// +// node tooling/bootstrap/deploys.mjs --defer # 01-scaffold, before its landing +// node tooling/bootstrap/deploys.mjs --restore # 02-live, before its landing +// node tooling/bootstrap/deploys.mjs --check # prints deferred | active +// +// While deferred, a merge to main plans nothing on stage or prod (dev's push +// activation is deferred by dev-lanes.mjs for the same bootstrap), so the +// run is `plan` alone: green, and nothing deployed. Pull requests keep their +// stage and prod verify lanes (built and dry-deployed, no credential), so a +// code-only app's changes are still checked before they merge. +// +// --defer replaces each rung'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. Restoring is a +// change to intent.yaml's `environments` section only, which `orun plan +// --changed` maps to no component, so the landing that restores the lanes +// must also change the component it deploys (the live phase's retouch marker +// on its component.yaml does). +// +// The activation is deferred, never dropped: an app that stops after the +// scaffold carries the markers in intent.yaml, and `--restore` (or the live +// phase) 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 = "@deploys-deferred"; +const TRIGGER = "github-push-main"; +// The rungs that DEPLOY. dev only verifies, and dev-lanes.mjs owns its lanes. +const RUNGS = new Set(["stage", "prod"]); + +function usage() { + console.error("usage: deploys.mjs --defer | --restore | --check [--file intent.yaml]"); + process.exit(2); +} + +// The `- github-push-main` lines under environments.{stage,prod}.activation. +function findDeployTriggers(text) { + const lines = text.split("\n"); + const found = []; + let inEnvs = false; + let envIndent = -1; + let current = null; + 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 && (envIndent < 0 || env[1].length <= envIndent)) { + envIndent = env[1].length; + current = env[2]; + continue; + } + if (!RUNGS.has(current)) continue; + if (new RegExp(`^\\s+-\\s+${TRIGGER}\\s*$`).test(line)) found.push({ env: current, index: i }); + } + return { lines, found }; +} + +function markerFor(original) { + const indent = /^(\s*)/.exec(original)[1]; + const b64 = Buffer.from(original, "utf8").toString("base64"); + return `${indent}# ${MARKER}:${b64} (tooling/bootstrap/deploys.mjs --restore puts it back)`; +} + +const MARKER_RE = new RegExp( + `^[ \\t]*# ${MARKER}:([A-Za-z0-9+/=]+) \\(tooling/bootstrap/deploys\\.mjs --restore puts it back\\)$`, + "gm", +); + +function defer() { + const text = fs.readFileSync(FILE, "utf8"); + const { lines, found } = findDeployTriggers(text); + if (found.length === 0) { + console.log( + text.includes(`# ${MARKER}:`) + ? `deploys --defer: already deferred in ${FILE}` + : `deploys --defer: neither stage nor prod is activated on ${TRIGGER} in ${FILE} — nothing to defer`, + ); + return; + } + const out = [...lines]; + for (const { index } of found) out[index] = markerFor(lines[index]); + fs.writeFileSync(FILE, out.join("\n")); + const envs = found.map((f) => f.env).join(" and "); + console.log(`deploys --defer: ${envs} deploy nothing on a merge to main until --restore (${FILE})`); +} + +function restore() { + const text = fs.readFileSync(FILE, "utf8"); + let n = 0; + const out = text.replace(MARKER_RE, (_m, b64) => { + n++; + return Buffer.from(b64, "base64").toString("utf8"); + }); + if (n === 0) { + console.log(`deploys --restore: nothing deferred in ${FILE}`); + return; + } + fs.writeFileSync(FILE, out); + console.log(`deploys --restore: stage and prod deploy on 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/dev-lanes.mjs b/tooling/bootstrap/dev-lanes.mjs index 72f00c8..b1db58c 100755 --- a/tooling/bootstrap/dev-lanes.mjs +++ b/tooling/bootstrap/dev-lanes.mjs @@ -15,10 +15,12 @@ // where this tool comes from: dev took eight of eighteen lanes and stage and // prod got five each.) // -// So 01-product defers the trigger and 03-docs, the last landing, puts it -// back, exactly as tooling/bootstrap/promotion.mjs does for prod's gate: +// So 02-live, the landing that deploys, defers the trigger and 03-docs, the +// last landing, puts it back, exactly as tooling/bootstrap/promotion.mjs does +// for prod's gate. (01-scaffold leaves it alone: while stage and prod are +// parked by deploys.mjs, dev is what a merge to main plans.) // -// node tooling/bootstrap/dev-lanes.mjs --defer # 01-product, before its landing +// node tooling/bootstrap/dev-lanes.mjs --defer # 02-live, before its landing // node tooling/bootstrap/dev-lanes.mjs --restore # 03-docs, the last landing // node tooling/bootstrap/dev-lanes.mjs --check # prints deferred | active // diff --git a/tooling/bootstrap/promotion.mjs b/tooling/bootstrap/promotion.mjs index ed6edf8..bcfb062 100644 --- a/tooling/bootstrap/promotion.mjs +++ b/tooling/bootstrap/promotion.mjs @@ -10,9 +10,10 @@ // is watched to green before the next one starts) and it doubles the length // of every convergence: each worker's prod deploy waits out its stage deploy. // -// So 01-product defers the gate and 03-docs, the last landing, puts it back: +// So 02-live, the landing that deploys, defers the gate and 03-docs, the last +// landing, puts it back: // -// node tooling/bootstrap/promotion.mjs --defer # 01-product, before its landing +// node tooling/bootstrap/promotion.mjs --defer # 02-live, before its landing // node tooling/bootstrap/promotion.mjs --restore # 03-docs, the last landing // node tooling/bootstrap/promotion.mjs --check # prints deferred | enforced // diff --git a/tooling/bootstrap/retouch.mjs b/tooling/bootstrap/retouch.mjs index a118e5b..21beb4a 100644 --- a/tooling/bootstrap/retouch.mjs +++ b/tooling/bootstrap/retouch.mjs @@ -29,8 +29,8 @@ // phase state is DERIVED from the tree, never stored in it — holds. Delete the // line and nothing is lost but the next redeploy's reason to happen. // -// node retouch.mjs --phase 01-product --affects .baseline/tasks/01-product.TaskContract.yaml -// node retouch.mjs --phase 01-product --components web +// node retouch.mjs --phase 02-live --affects .baseline/tasks/02-live.TaskContract.yaml +// node retouch.mjs --phase 02-live --components web // // Options: // --phase <name> the phase the marker names (required) diff --git a/tooling/bootstrap/subdomain.mjs b/tooling/bootstrap/subdomain.mjs new file mode 100644 index 0000000..78e91dd --- /dev/null +++ b/tooling/bootstrap/subdomain.mjs @@ -0,0 +1,189 @@ +#!/usr/bin/env node +// Bind the site's workers.dev subdomain when it goes live (zero-dependency). +// +// The subdomain is a LATE-BOUND input. It belongs to the Cloudflare account +// the site deploys into, and a build that stops after the scaffold stage — +// an app with no Cloudflare connection yet — does not have one. So the +// scaffold places and brands the tree with the placeholder, +// `your-workers-subdomain` (the baseline's own, `.baseline/identity.json`), +// and the live stage must replace it before anything deploys: in the +// component's `workersDevSubdomain` (the deploy's smoke URL), in +// intent.yaml's environment URLs, in the operating contract's examples, and +// in `.rebrand/values.json`, the identity every later phase reads back. +// +// A build that runs both stages at once was given the real value from the +// start, so the rebrand already wrote it everywhere and binding finds +// nothing to change. +// +// node subdomain.mjs --bind <subdomain> # 02-live, before its landing +// node subdomain.mjs --check # prints `bound <subdomain>` | `placeholder` +// +// --bind refuses the placeholder itself (or nothing): the live stage may +// never keep it, because every URL the deploy smokes and the phase probes is +// built from it. It also refuses to MOVE a site already bound to another +// subdomain: that is another Cloudflare account, whose deploy token this +// workspace's secrets do not hold, not a step of a bootstrap. +// +// Only the placeholder is replaced, and only where it stands as a whole DNS +// label, so a subdomain that merely contains it is left alone; the +// `.rebrand/values.json` record is written LAST, so an interrupted bind is +// finished by the next one. Idempotent. Runs in the product checkout, over +// the files git tracks there. +import { execFileSync } from "node:child_process"; +import * as fs from "node:fs"; +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; + +const VALUES = ".rebrand/values.json"; +const SUBDOMAIN_RE = /^[a-z0-9][a-z0-9-]{0,62}$/; // = blueprint.yaml's pattern + +function usage(msg) { + if (msg) console.error(`subdomain: ${msg}`); + console.error("usage: subdomain.mjs --bind <subdomain> | --check [--baseline-identity <file>]"); + process.exit(2); +} + +function arg(name) { + const i = process.argv.indexOf(`--${name}`); + return i >= 0 ? process.argv[i + 1] : undefined; +} + +// The placeholder, from the baseline's declared identity — the same file the +// rebrand reads its FROM side from, beside this script. +function placeholder() { + const file = + arg("baseline-identity") ?? + path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".baseline", "identity.json"); + try { + const declared = JSON.parse(fs.readFileSync(file, "utf8")).subdomain; + if (typeof declared === "string" && declared.length > 0) return declared; + } catch { + // absent is fine: the default IS this baseline's placeholder + } + return "your-workers-subdomain"; +} + +function readValues() { + try { + return { text: fs.readFileSync(VALUES, "utf8") }; + } catch { + console.error(`subdomain: ${VALUES} is missing — is this a scaffolded site?`); + process.exit(1); + } +} + +function recorded(text, fallback) { + let v; + try { + v = JSON.parse(text).subdomain; + } catch (e) { + console.error(`subdomain: ${VALUES} does not parse: ${e.message}`); + process.exit(1); + } + return typeof v === "string" && v.trim() ? v.trim() : fallback; +} + +// The placeholder as a whole DNS label: not preceded or followed by a label +// character, so `your-workers-subdomain-2` is somebody's real subdomain. +const labelRe = (label) => + new RegExp(`(?<![A-Za-z0-9-])${label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![A-Za-z0-9-])`, "g"); + +function trackedTextFiles() { + let out; + try { + out = execFileSync("git", ["ls-files", "-z"], { encoding: "utf8" }); + } catch (e) { + console.error(`subdomain: git ls-files failed — run it in the site's checkout (${e.message.trim()})`); + process.exit(1); + } + return out + .split("\0") + .filter((f) => f && !f.startsWith(".rebrand/") && !/^pnpm-lock\.yaml$/.test(f)) + .filter((f) => !/\.(png|jpe?g|ico|gif|webp|woff2?|ttf|eot)$/i.test(f)) + .filter((f) => { + try { + return fs.statSync(f).isFile(); + } catch { + return false; + } + }); +} + +function bind(value) { + const hold = placeholder(); + const want = String(value ?? "").trim(); + if (!want || want === hold) { + console.error( + `subdomain --bind: the site goes live on <worker>.<subdomain>.workers.dev and was given ${want ? `the placeholder "${hold}"` : "no subdomain"}. ` + + "The live stage needs the workers.dev subdomain of the Cloudflare account it deploys into: a console or orun.work " + + "build reads it from the Cloudflare connection; a hand-run build passes --set subdomain=<subdomain>.", + ); + process.exit(1); + } + if (!SUBDOMAIN_RE.test(want)) { + console.error(`subdomain --bind: "${want}" is not a workers.dev subdomain (${SUBDOMAIN_RE})`); + process.exit(1); + } + const { text } = readValues(); + const was = recorded(text, hold); + if (was !== hold && was !== want) { + console.error( + `subdomain --bind: this site is bound to ${was}.workers.dev and was given ${want}. Moving a site to another ` + + "Cloudflare account's subdomain is not a step of a bootstrap — its Workers, deploy token and URLs belong to the " + + `old one. To move it on purpose, replace "${was}" with "${want}" in .rebrand/values.json, intent.yaml and ` + + "apps/web/component.yaml in one change.", + ); + process.exit(1); + } + + const re = labelRe(hold); + const changed = []; + for (const file of trackedTextFiles()) { + const before = fs.readFileSync(file, "utf8"); + if (before.includes("\0")) continue; // binary safety net + const after = before.replace(re, want); + if (after !== before) { + fs.writeFileSync(file, after); + changed.push(file); + } + } + // The record last: until it names the subdomain, the next bind redoes the rest. + if (was !== want) { + const line = /("subdomain"\s*:\s*)"[^"]*"/; + let next = line.test(text) ? text.replace(line, `$1${JSON.stringify(want)}`) : null; + if (next === null || recorded(next, hold) !== want) { + const obj = JSON.parse(text); + obj.subdomain = want; + next = `${JSON.stringify(obj, null, 2)}\n`; + } + fs.writeFileSync(VALUES, next); + changed.push(VALUES); + } + + const left = trackedTextFiles().filter((f) => labelRe(hold).test(fs.readFileSync(f, "utf8"))); + if (left.length > 0) { + console.error(`subdomain --bind: the placeholder "${hold}" is still in ${left.join(", ")}`); + process.exit(1); + } + console.log( + changed.length > 0 + ? `subdomain --bind: ${want}.workers.dev bound in ${changed.length} file(s): ${changed.join(", ")}` + : `subdomain --bind: already bound to ${want}.workers.dev — nothing to change`, + ); +} + +function check() { + const hold = placeholder(); + const was = recorded(readValues().text, hold); + console.log(was === hold ? "placeholder" : `bound ${was}`); +} + +const argv = process.argv.slice(2); +const at = argv.indexOf("--bind"); +if (at >= 0) { + // The value may be empty (an input nobody set renders as ""), which bind() + // refuses with the reason; only a MISSING one is a usage error. + if (at + 1 >= argv.length || argv[at + 1].startsWith("--")) usage("--bind needs a value"); + bind(argv[at + 1]); +} else if (argv.includes("--check")) check(); +else usage(); diff --git a/tooling/bootstrap/work-tree.mjs b/tooling/bootstrap/work-tree.mjs index ac16e62..30f7f3f 100644 --- a/tooling/bootstrap/work-tree.mjs +++ b/tooling/bootstrap/work-tree.mjs @@ -15,9 +15,9 @@ // block would point the product's every plan at two directories that do not // exist. // -// So 01-product removes it from the product's copy, before its landing: +// So 01-scaffold removes it from the product's copy, before its landing: // -// node tooling/bootstrap/work-tree.mjs --strip # 01-product +// node tooling/bootstrap/work-tree.mjs --strip # 01-scaffold // node tooling/bootstrap/work-tree.mjs --check # prints declared | absent // // The block removed is the top-level `work:` key with everything indented