diff --git a/.baseline/identity.json b/.baseline/identity.json new file mode 100644 index 0000000..2d8be39 --- /dev/null +++ b/.baseline/identity.json @@ -0,0 +1,9 @@ +{ + "_comment": "THIS TREE'S OWN IDENTITY — the FROM side of every rebrand. tooling/rebrand/rebrand.mjs reads it to know what to rename AWAY from; a product's identity is the --values file, which is the TO side. Change a value here only together with the tree: these strings must be what the tree actually contains, or the rename silently misses and the product ships carrying this baseline's name. `productName` is the SITE_NAME seam in apps/web/lib/site.ts; `slug` also names the KV namespace titles (terraform `repo`) and the secret project; `domain` and `subdomain` are placeholders, because this baseline has never deployed under a name of its own; `githubOwner` is the owner in SOURCE_URL.", + "slug": "cron-starter", + "pascal": "CronStarter", + "productName": "Cron Triggers on Cloudflare", + "domain": "cron-starter.example.com", + "subdomain": "your-workers-subdomain", + "githubOwner": "sourceplane" +} diff --git a/.baseline/product/README.md b/.baseline/product/README.md new file mode 100644 index 0000000..1d708b2 --- /dev/null +++ b/.baseline/product/README.md @@ -0,0 +1,120 @@ +# cron-starter + +Seven schedules — every minute, every ten minutes, hourly, every twelve +hours, daily, weekly, monthly — each recording the newest Hacker News story +and the time it ran, and a page that shows every schedule's last run. +Next.js on **Cloudflare Workers + Static Assets** through +[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), the schedules +as **Cron Triggers** on the same Worker, the runs in a **Workers KV** +namespace that Terraform provisions per environment. + +## Live deployment + + +Not recorded yet. The bootstrap's last phase writes the live URLs, the +workspace and the secrets inventory into +[ai/context/deployment.md](ai/context/deployment.md); how the site deploys +and how to operate it is in +[ai/context/operations.md](ai/context/operations.md). + + +## What is here + +| Surface | Where | +|---|---| +| The page (the seven schedules and their last runs) | `apps/web/pages/index.tsx`, `components/post.tsx` | +| The site's name and source link | `apps/web/lib/site.ts` | +| What a schedule runs, and how its record is read | `apps/web/pages/api/cron/[cron].ts`, `pages/api/data/[interval].ts` | +| The Cron Trigger and the scheduled handler | the one `triggers.crons` entry in `apps/web/wrangler.template.jsonc`, the seven schedules in `lib/crons.ts`, `lib/scheduled.ts`, `worker.ts` | +| The store (Workers KV, `kv.set` / `kv.get`) | `apps/web/lib/kv.ts` | +| Workers build, bindings and deploy contract | `apps/web/next.config.mjs`, `open-next.config.ts`, `wrangler.template.jsonc` + `wiring.fixture.json` (→ `wrangler.jsonc`), `component.yaml` | +| The KV namespace (stage, prod) | `infra/terraform/cloudflare-kv` | +| Tests | `tests/web` (vitest) | + +## Getting started + +```bash +pnpm install +pnpm run wire:fixture # render apps/web/wrangler.jsonc from the offline fixture +pnpm typecheck +pnpm lint +pnpm test +pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next +``` + +```bash +pnpm --filter @app/web dev # http://localhost:3000 — a local KV through wrangler's platform proxy, no scheduler +cd apps/web && pnpm exec wrangler dev --test-scheduled # the built Worker on :8787, triggers fired by hand +curl "http://localhost:8787/__scheduled?cron=*+*+*+*+*" # fires the trigger now: 1m, and whatever else is due +curl "http://localhost:8787/cdn-cgi/local/scheduled?cron=*+*+*+*+*&time=1793491200000" # as at Sunday 2026-11-01 00:00 UTC: all seven +curl http://localhost:8787/api/data/1m # …and reads what a run recorded +``` + +Make the page yours in `apps/web/pages/index.tsx`, and its name and the +repository it links to in `apps/web/lib/site.ts`. + +## How the schedules run + +`wrangler.template.jsonc` registers ONE Cron Trigger on the Worker, every +minute. `worker.ts` is the Worker's entry: the fetch handler OpenNext +generates, plus a `scheduled` handler. Each time the trigger fires, the +handler checks the seven schedules in `lib/crons.ts` against the minute the +trigger was scheduled for (UTC) and, for every one that is due, requests +`/api/cron/` through that same fetch handler — the route a +scheduler would call over HTTPS — which writes `{ fetchedAt, id }` under the +interval's key. `1m` runs every minute, `10m` when the minute is a multiple +of ten, `1h` on the hour, `12h` at 00:00 and 12:00, `1d` at midnight, `1w` at +midnight on Sunday and `1mo` at midnight on the 1st. The page polls +`/api/data/` for each schedule and shows "fetched N ago". + +To change a schedule, change its expression in `lib/crons.ts` (and the one +the page shows beside it in `pages/index.tsx`); the trigger stays as it is. +One trigger per Worker, two for stage and prod, stays inside the five Cron +Triggers per account that Cloudflare's Workers Free plan allows. The trigger +can take a few minutes to start firing after the first deploy. +`/api/cron/` is public, as in the template it comes from: anyone +can run a schedule early. Guarding it is a Worker secret the scheduled +handler sends as a header and the route checks. + +## How the namespace is wired + +The Worker binds the namespace as `KV`. Its id is never hand-written: +`apps/web/wrangler.template.jsonc` names it as a wiring token, and +`wrangler.jsonc` is that template rendered — from `wiring.fixture.json` +(placeholder ids) for local work and verification, and on every deploy from +the document the `cloudflare-kv` Terraform root publishes after its apply +(`WIRING_CLOUDFLARE_KV`, per environment). Edit the template, then +`pnpm run wire:fixture`; Checks fails if the committed `wrangler.jsonc` is +not the fixture render. + +KV is eventually consistent: a run recorded in one location can read as the +previous one elsewhere for up to a minute — invisible for "fetched N ago". + +## How it deploys + +Merges to `main` converge through [Orun](https://github.com/sourceplane/orun): +`.github/workflows/ci.yml` plans the changed components and runs each lane +against the workspace in `intent.yaml`. The KV namespace applies first, then +the Worker builds with that environment's namespace id and deploys — to +`stage`, then to `prod` once stage has converged on the same commit; `dev` +only verifies. The Worker is `cron-starter-web-` on your account's +workers.dev subdomain, and every deploy is smoke-tested over HTTP: +`/api/data/1m` must carry a run the every-minute trigger recorded in the last +ten minutes. `checks.yml` runs install, the fixture render, typecheck, lint, +test and build on every pull request. (A push to `main` runs `ci.yml` alone, +which applies, builds and deploys.) + +The pipeline holds one credential, GitHub's own `GITHUB_TOKEN`. The +Cloudflare token and account id are brokered per run from the workspace's +Cloudflare connection, and the namespace ids travel as Orun secrets; nothing +provider-shaped is stored in the repository or in GitHub. + +## Custom domain + +The site answers on workers.dev from its first deploy. To serve it on your +own domain, add the domain to the Cloudflare account the site deploys into +and attach it to the Worker (dashboard → Workers & Pages → +`cron-starter-web-prod` → Settings → Domains & Routes → Add → Custom +domain). Nothing in the repository changes: the page builds its absolute +links from the request it is answering, and the Cron Triggers do not depend +on a hostname. diff --git a/.baseline/tasks/01-product.TaskContract.yaml b/.baseline/tasks/01-product.TaskContract.yaml new file mode 100644 index 0000000..6507f58 --- /dev/null +++ b/.baseline/tasks/01-product.TaskContract.yaml @@ -0,0 +1,27 @@ +# Task contract template for the 01-product landing. +# Unbound to a key on purpose: `orun.task/ensure@v1` seals and attaches it to +# the key the allocator issues. It lives under `.baseline/`, not `tasks/`, +# because `tasks/` is this repository's own work tree (`intent.yaml` `work:`), +# where an unkeyed contract is an error. gates: [] is a DECLARATION — merge +# alone finishes this task; the main convergence is the gate the bootstrap +# watches, not one the plane observes as a PR check. +# +# The whole product in one landing. `affects` names COMPONENTS, by +# metadata.name: the phase's retouch hook reads this list to decide which +# component.yaml files get the redeploy marker, so a re-run of the phase has a +# diff and exactly these components are re-planned — the deploy set and the +# task plane's statement of the work are one list. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The product's repository is born and linked, the whole product lands in one pull request, and one convergence applies the KV namespace and deploys the Worker — its page, API routes and Cron Triggers — on stage and prod + affects: + - cloudflare-kv + - web + - web-tests + doneWhen: + - repo pushed, main pinned as default, workspace linked + - WIRING_CLOUDFLARE_KV published on stage and prod + - main convergence green (KV applied, then the Worker built, deployed and smoke-tested on stage and prod — the smoke reads a run its every-minute trigger recorded) + - the page answers on both workers.dev URLs + gates: [] diff --git a/.baseline/tasks/02-docs.TaskContract.yaml b/.baseline/tasks/02-docs.TaskContract.yaml new file mode 100644 index 0000000..d62a6e7 --- /dev/null +++ b/.baseline/tasks/02-docs.TaskContract.yaml @@ -0,0 +1,13 @@ +# Task contract template for the 02-docs landing. See 01-product's header. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The live deployment is recorded from verified facts as agent-readable state in the product's repo + affects: + - ai/context/deployment.md + - ai/context/operations.md + - README.md + doneWhen: + - committed deployment manifest matches probed reality + - prod waits on stage again, and dev verifies every merge to main again + gates: [] diff --git a/.github/workflows/baseline.yml b/.github/workflows/baseline.yml new file mode 100644 index 0000000..336b176 --- /dev/null +++ b/.github/workflows/baseline.yml @@ -0,0 +1,136 @@ +name: Baseline CI + +# THE FACTORY'S OWN LANES — this repository tested as a BASELINE: that its +# build document parses with the orun a bootstrap actually runs, that its card +# agrees with it, that every component is placed by the one product phase, +# that the KV namespace's wiring reaches the Worker's config, that a placed +# tree comes up branded and carrying nothing of the factory — and plans the +# namespace before the Worker on a merge — and that the product it produces +# installs, builds, deploys (dry) and serves. +# +# ─── WHY THIS IS NOT IN ci.yml OR checks.yml ────────────────────────────── +# +# `repo-blueprint.yaml`'s `github-workflows` module copies the WHOLE `.github` +# directory into every site built from this repository. These jobs run +# `testing/*.sh`, and `testing/` is deliberately not placed — so in a site they +# would be steps that cannot pass, red on its very first pull request. This +# file is in the blueprint's `ignore` list, and `testing/coverage.test.sh` +# fails on any workflow that reads `testing/` and is not. + +on: + push: + branches: [main] + pull_request: + +concurrency: + group: baseline-ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read + +jobs: + # Tier 0. bash, python3 and git; node for the tools. No workspace install, + # no network, no credential — the job that most certainly fails a PR. + baseline-contract: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-node@v5 + with: + node-version: 22 + # setup-node v5 turns on the pnpm cache by itself when package.json + # names a packageManager, and then fails on a runner with no pnpm. + # This job installs nothing. + package-manager-cache: false + - name: Contract tests (manifest, phases, coverage, rebrand, retouch, bootstrap-defer, wire) + run: | + set -euo pipefail + python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml + for t in manifest phases coverage rebrand retouch bootstrap-defer wire; do + echo "── $t" + bash "testing/$t.test.sh" + done + + # Tier 1. THE BLUEPRINT, READ AND PLACED BY THE BINARY A BOOTSTRAP RUNS. + # + # Pinned at the bootstrap floor (BOOTSTRAP.md), not the site's lane pin: + # every test here reads YAML with PyYAML, which parses anything well-formed; + # only the pinned orun can say whether the document is one a bootstrap can + # run. `--status` parses it, validates every hook against the action + # registry, compiles every `when` and narration template, and writes + # nothing. Then the leak gate (what a product would carry, derived by the + # floor too), and the placement tier (the offline bootstrap: both phases + # placed and finished by the blueprint's own hooks, then the product's own + # `orun plan` for the 01-product merge — the KV apply before the Worker's + # deploy — under the product's lane pin, below). + blueprint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: sourceplane/orun-action@v1.2.0 + with: + version: v2.58.11 + - uses: pnpm/action-setup@v4 + with: + version: 10.12.1 + - uses: actions/setup-node@v5 + with: + node-version: 22 + - name: repo-blueprint.yaml, read by the pinned CLI + run: | + set -euo pipefail + orun --version + python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml + # Required inputs must be supplied for the document to resolve; the + # values are arbitrary and nothing is written. + orun new --blueprint repo-blueprint.yaml --status \ + --out "$(mktemp -d)" \ + --set reponame=acme-crons \ + --set "productname=Acme Crons" \ + --set productdomain=acme.dev \ + --set githuborg=acme-inc + - name: the leak gate — what a product carries + run: bash testing/leak.test.sh + # The placement tier ENDS with the product's own `orun plan` — what the + # product's ci.yml runs — so it runs under the product's lane pin, not + # the bootstrap floor. v2.58.11 plans a pull request with apps/web + # waiting on the KV plan: it does not apply a dependsOn edge's + # `modeRules`. The lane pin does (advisory on a PR, enforced on main), + # and the test refuses an orun older than the pin rather than assert + # the wrong CLI's plan. Its placements are valid under either. + - uses: sourceplane/orun-action@v1.2.0 + with: + version: v2.78.4 + - name: placement — the offline bootstrap, and the product's own plan + run: | + git config --global user.email ci@example.invalid + git config --global user.name "baseline ci" + bash testing/placement.test.sh + + # Tier 2. THE PRODUCT IT PRODUCES WORKS: its one landing under the checks + # its pull request waits on, the stage lane's own structure check, build + # (the live wiring render included), output check and dry deploy in the tree + # orun stages, and the built Worker served and smoke-tested with the + # component's own smoke command. Pinned at the product's lane version, + # because that is the orun the product's CI runs. + site: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: sourceplane/orun-action@v1.2.0 + with: + version: v2.78.4 + - uses: pnpm/action-setup@v4 + with: + version: 10.12.1 + - uses: actions/setup-node@v5 + with: + node-version: 22 + cache: pnpm + - name: e2e — the bootstrapped product builds, deploys (dry) and serves + run: | + python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml + git config --global user.email ci@example.invalid + git config --global user.name "baseline ci" + bash testing/e2e.test.sh diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index bd8d5df..1426539 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -1,14 +1,21 @@ name: Checks # Credential-free verification: install, render the offline wrangler fixtures, -# typecheck, lint, test and build. Runs on every push and pull request and is -# the merge gate until the product is linked to an Orun workspace, at which -# point `ci.yml` (Orun plan/run with brokered Cloudflare credentials) takes -# over — it stays gated behind the `ORUN_CI` repository variable until then. +# typecheck, lint, test and build, on every pull request, linked or not. +# `ci.yml` is the Orun pipeline beside it (plan/run with brokered Cloudflare +# credentials, deploys on merge); it plans nothing until intent.yaml names a +# workspace. +# +# PULL REQUESTS ONLY — not pushes to main. A push to main must start exactly +# one workflow, `ci.yml`, because the bootstrap's convergence watch +# (`orun.run/watch@v1` with `sha:`) takes the newest run for the merge commit +# from ANY workflow. With this one on push too, the first live bootstrap +# watched this run go green while ci.yml's deploy lanes had failed, and called +# the site converged. On main the convergence builds and tests the site +# anyway. The baseline's coverage gate holds the rule. on: - push: - branches: [main] pull_request: + workflow_dispatch: concurrency: group: checks-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} @@ -33,6 +40,11 @@ jobs: # Templated deployables render their wrangler config from the committed # fixture; an unresolved wiring token fails here, not at deploy time. - run: pnpm run wire:fixture + # …and the render is what is committed. The deploy lane checks that the + # config exists before it builds, so wrangler.jsonc is in the tree as the + # fixture render; a template edited without re-rendering fails here. + - name: the committed wrangler config is the fixture render + run: git diff --exit-code - run: pnpm typecheck - run: pnpm lint - run: pnpm test diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 027b0c4..e262a92 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,6 @@ permissions: jobs: plan: - if: ${{ vars.ORUN_CI == 'true' }} runs-on: ubuntu-latest outputs: lane-matrix: ${{ steps.matrix.outputs.lane-matrix }} @@ -33,10 +32,31 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - - uses: sourceplane/orun-action@v1.2.0 + # A TREE THAT NAMES NO WORKSPACE PLANS NOTHING. `ws_CHANGE_ME` is the + # placeholder this repository ships with until someone links it; every + # remote op of a plan here would be refused, so the job says so and + # stops green, and `run` below has no lanes to start. A site built from + # this baseline never carries the placeholder — its bootstrap writes the + # product's own workspace into intent.yaml — and a bootstrap that had no + # workspace to write leaves `ws_SET_ME`, which is NOT skipped: it fails + # here loudly rather than deploying nothing in silence. + # + # This replaced an `ORUN_CI` repository variable, which a bootstrap has + # no way to set: every site it built would have converged on nothing. + - id: linked + run: | + if grep -Eq '^[[:space:]]*workspace:[[:space:]]*ws_CHANGE_ME[[:space:]]*$' intent.yaml; then + echo "::notice title=Orun CI::intent.yaml names no Orun workspace (ws_CHANGE_ME) — nothing to plan. Link this repository (orun cloud link) and set execution.state.workspace to turn the pipeline on." + echo "linked=false" >> "$GITHUB_OUTPUT" + else + echo "linked=true" >> "$GITHUB_OUTPUT" + fi + - if: steps.linked.outputs.linked == 'true' + uses: sourceplane/orun-action@v1.2.0 with: - version: v2.78.0 - - env: + version: v2.78.4 + - if: steps.linked.outputs.linked == 'true' + env: # Surface the best-effort catalog auto-sync (execution.state.autopushCatalog). # A successful push prints "✓ pushed catalog …"; ORUN_VERBOSE also makes # any skip/failure visible instead of silent. @@ -57,11 +77,13 @@ jobs: # without lanes gets one per job, exactly the old matrix, and # `orun run --lane ` on it is `--job `. - id: matrix + if: steps.linked.outputs.linked == 'true' run: | echo "lane-matrix=$(jq -c 'if ((.lanes // []) | length) > 0 then [.lanes[] | {"lane": .id, "name": .name}] else [.jobs[] | {"lane": .id, "name": .checkName}] end' plan.json)" >> "$GITHUB_OUTPUT" - - uses: actions/upload-artifact@v7 + - if: steps.linked.outputs.linked == 'true' + uses: actions/upload-artifact@v7 with: name: orun-plan path: plan.json @@ -124,7 +146,7 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - uses: sourceplane/orun-action@v1.2.0 with: - version: v2.78.0 + version: v2.78.4 # exec-id is the RUN id alone (no attempt suffix): a `gh run rerun # --failed` then RESUMES the same orun execution — jobs that succeeded in # a prior attempt stay completed, so re-run lanes' cross-job dependencies @@ -174,8 +196,8 @@ jobs: env: # GITHUB_TOKEN is the only credential CI holds — GitHub-issued and # ephemeral. Every provider credential (the Cloudflare token and - # account id — this baseline has no second provider) is an - # orun-managed secret: + # account id — there is no second provider) is an orun-managed + # secret: # brokered fresh per run from the workspace's integrations, resolved # lease-bound by the jobs that declare it (profile secretBindings or # component secretEnv), and log-redacted. Nothing provider-shaped is diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml new file mode 100644 index 0000000..c0383e3 --- /dev/null +++ b/.github/workflows/tag.yml @@ -0,0 +1,97 @@ +name: Baseline tag + +# CUTS A `baseline-vN` TAG FOR THIS REPOSITORY. +# +# A baseline tag is what the platform's registry resolves and what every +# product bootstrapped from this repository is built out of, so it is cut by a +# workflow rather than by hand: the version must look like a baseline tag, an +# existing tag is never moved, and the commit is resolved here, once. +# +# Whether a commit is fit to release is decided outside this repository, by +# whoever cuts the tag; nothing here asks for proof beyond a green `main`. + +on: + workflow_dispatch: + inputs: + version: + description: "The tag to cut, e.g. baseline-v2." + required: true + type: string + ref: + description: "Branch, tag or sha to cut it from. Defaults to main." + required: false + default: main + type: string + +concurrency: + group: baseline-tag + cancel-in-progress: false + +permissions: + contents: read + +jobs: + cut: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v6 + with: + # Full history: the ref being cut from may be any commit, and a + # shallow clone cannot resolve one it did not fetch. + fetch-depth: 0 + ref: ${{ inputs.ref }} + + - name: the version must look like a baseline tag + run: | + set -euo pipefail + # Refused here rather than by the API, because the API's error for a + # malformed ref says nothing about the convention it broke. + case "${{ inputs.version }}" in + baseline-v[0-9]*) ;; + *) echo "✕ '${{ inputs.version }}' is not a baseline-vN tag" >&2; exit 1 ;; + esac + + - name: resolve the commit + id: commit + run: | + set -euo pipefail + sha="$(git rev-parse HEAD)" + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "Cutting ${{ inputs.version }} from ${{ inputs.ref }} = $sha" + + - name: the tag must not already exist + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + code="$(curl -sS -o /dev/null -w '%{http_code}' \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/git/ref/tags/${{ inputs.version }}")" + if [ "$code" = "200" ]; then + echo "✕ ${{ inputs.version }} already exists. A baseline tag is never moved:" >&2 + echo " products resolve it, and repointing one changes what a build that" >&2 + echo " already shipped was made of. Cut the next number." >&2 + exit 1 + fi + # Anything other than 200 or 404 means the question was not answered, + # and "it probably does not exist" is not a thing to guess about a + # tag that is about to be created. + [ "$code" = "404" ] || { echo "✕ could not check for the tag (HTTP $code)" >&2; exit 1; } + + - name: cut the tag + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + curl -sS -X POST --fail-with-body \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/git/refs" \ + -d "$(printf '{"ref":"refs/tags/%s","sha":"%s"}' \ + "${{ inputs.version }}" "${{ steps.commit.outputs.sha }}")" + echo "" + echo "✓ ${{ inputs.version }} → ${{ steps.commit.outputs.sha }}" + echo " Next: move the registry row in orun-cloud's infra/baselines-registry/baselines.yaml." diff --git a/.gitignore b/.gitignore index 17062c1..6657531 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,6 @@ crash.log **/.orun/runs/ **/.orun/ -# Rendered wrangler configs for wiring-templated deployables (committed as -# wrangler.template.jsonc; rendered by tooling/wire at verify/deploy time). -apps/web/wrangler.jsonc +# apps/web/wrangler.jsonc is NOT ignored: it is committed as the fixture render +# of wrangler.template.jsonc, because the deploy lane checks the config exists +# before it builds (and re-renders it for its environment in the build). diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md new file mode 100644 index 0000000..12fab2c --- /dev/null +++ b/BOOTSTRAP.md @@ -0,0 +1,236 @@ +# BOOTSTRAP — a new product from this baseline, in one landing + +How to go from **nothing** to **seven scheduled jobs and their page live on +stage and prod, their KV namespaces applied, documented**, with ONE provider +consent. + +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 fifteen minutes** — an estimate summed from the +phases until a bootstrap measures it: ONE landing whose pull request waits on +Checks (a full Next.js build), then one convergence — the KV namespace +applied on stage and prod, then the Worker built with its id and deployed, +stage and prod side by side, each smoke waiting for the every-minute Cron +Trigger's first recorded run — then a short docs landing that restores the +promotion gate. + +## 0. What you need + +- GitHub org access (repository creation) and a machine with `git`, `node` + (≥ 22), `pnpm` (10.12.1), `python3` with PyYAML, `curl`, and the `orun` + CLI **≥ v2.58.11** — the floor for RUNNING the bootstrap (the phase overlay, + landings that commit per phase and wait on the PR's whole CI run, + `githubOwner` on the doctor probe, `environments` on the secrets probe, a + probe deferred for a project not yet created, and `from: workspace`). The + product's own `ci.yml` pins its lanes separately (v2.78.4), and its plans + need that pin: the floor does not apply a `dependsOn` edge's `modeRules`. +- A Cloudflare account (the Free plan is enough: the product registers ONE + Cron Trigger per Worker, two in all, and dispatches its seven schedules + from it; Free allows five per account) and its **Account API token** with + Workers Scripts Write and Workers KV Storage Write (the console's Connect + recipe lists the exact permission groups). It is the ONLY provider + credential this baseline needs: the brokered `workers-deploy` scope covers + the namespace's apply and the Worker's deploy, its trigger included. +- An Orun Cloud workspace for the product — `orunWorkspace`, or the + workspace the build runs in (ORUN_WORKSPACE) when that is unset — with an + **admin-role API key** for headless runs (secret writes below admin are + masked as `not_found`). +- **The repository allow-listed in the workspace** (console → Settings → Git + repos), unless the credential can write links. `01-product`'s `link` step + stops and names the fix if it is not. + +## 1. One command: `--resume` + +The whole bootstrap, unattended. `--resume` places every phase not already +derived as done, in order, honouring each phase's barrier: + +```bash +git clone --depth 1 --branch https://github.com/sourceplane/cron-starter +cd cron-starter + +orun new --blueprint repo-blueprint.yaml \ + --out ~/sites/acme-crons --run-hooks --resume \ + --set reponame=acme-crons --set productname="Acme Crons" \ + --set productdomain=acme.dev --set githuborg=acme-inc \ + --set orunWorkspace=ws_XXXXXXXX \ + --set subdomain= +``` + +**`--run-hooks` is the difference between placing files and bootstrapping a +product.** Without it `orun new` writes the tree and stops: no repository, no +landing, no convergence watch, no probe. That is deliberate — it is what +makes the offline bootstrap in `testing/` possible with no workspace and no +provider. + +`--resume` is safe to re-run from anywhere, a fresh container with a fresh +`--out` included: **phase state is derived from the tree, never stored.** A +phase whose files are present but branded derives as `drifted`, and +`--resume` leaves it placed rather than reverting the product's identity. + +## 1b. Or phase by phase + +| phase | what it lands | verified by | +|---|---|---| +| `01-product` | the repository, created and linked; the WHOLE product in one PR — intent, CI, tooling, identity, the KV root, the Worker (page, API routes, Cron Trigger) and its tests; the brokered Cloudflare secrets | its PR's checks green and merged; the convergence green (KV applied, then the Worker built, deployed, smoke-tested on a run its every-minute trigger recorded); `WIRING_CLOUDFLARE_KV` on stage and prod; both workers.dev URLs answering | +| `02-docs` | `ai/context/deployment.md` from probed facts; prod's promotion gate and dev's push lanes restored | the final probe | + +```bash +orun new --blueprint repo-blueprint.yaml --out ~/sites/acme-crons --run-hooks \ + --phase 01-product --values ~/acme-crons.values.yaml +# … then 02-docs +``` + +`02-docs` reads the identity back from `.rebrand/values.json` in the placed +tree, but the blueprint's **required** inputs — `reponame`, `productname`, +`productdomain`, `githuborg` — are validated before anything runs, so pass +them every time (a `--values` file is easier). The full guide, one page per +phase: [docs/phases/README.md](docs/phases/README.md). + +| flag | what it does | +|---|---| +| `--status` | derives and prints every phase's state and writes nothing. It parses the document, validates each hook against the action registry and compiles every template; it needs no credential and no network | +| `--phase ` | places exactly that phase; its `requires.phases` still gates | +| `--until ` | places every phase through that one and stops | + +What lands in the product is PRODUCT-ONLY: the app, its KV root, its tests, +its CI, its tooling, its README and its two context pages. None of this +repository's machinery (`.baseline/`, the blueprints, `tooling/rebrand`, +`tooling/bootstrap`, `hooks/`, `testing/`, `docs/phases/`, `specs/`, +`tasks/`, this file) ships, and no file that ships names one of them. That +promise is a test: `testing/leak.test.sh` derives what every phase would +place and gates the set and its sources, and `testing/placement.test.sh` +gates the same rules over a placed, branded tree. + +## 2. Why one landing is safe: the plan carries the order + +The namespace must exist before the Worker that binds it: the Worker's +`wrangler.jsonc` carries the namespace id, rendered in its build from the +wiring document the KV root publishes after its apply — and the Worker's +Cron Triggers start writing to it the minute it is deployed. That order used to +need landings of its own. It does not, because the product's plan holds it: + +- `apps/web/component.yaml` declares `dependsOn: cloudflare-kv` with + `mode: enforced`, and `modeRules` making it advisory on + `github-pull-request`. On the merge the Worker's deploy waits for its + environment's apply; on a pull request nothing deploys, so nothing waits. +- A job resolves its secrets when it STARTS, so `WIRING_CLOUDFLARE_KV_` + is there when the deploy begins. +- The landing's `await` then asks the platform that the wiring exists on + stage and prod (`orun.secrets/exists@v1`) — every later deploy reads it. + +`testing/phases.test.sh` fails if a component that reads a wiring document +does not wait for its publisher this way; `testing/placement.test.sh` plans +the product's own merge and asserts the KV lanes run first. + +## 3. Headless / container mode + +The blueprint's source is this repository (`sources: [{kind: dir, path: .}]`), +so the container contract is a shallow clone at a pinned tag plus two +tokens: + +```bash +export ORUN_TOKEN=… # orun auth, headless +export GITHUB_TOKEN=… # fine-grained PAT (below) + +git clone --depth 1 --branch https://github.com/sourceplane/cron-starter +cd cron-starter +orun new --blueprint repo-blueprint.yaml \ + --out /work/acme-crons --run-hooks --resume --progress json \ + --values /work/acme-crons.values.yaml +``` + +| requirement | detail | +|---|---| +| `GITHUB_TOKEN` | fine-grained PAT: **read** on this repository; on the PRODUCT's repository **contents write**, **pull-requests write**, **actions read+write** (`orun.run/watch@v1` resumes runs with `gh run rerun`), **checks read**; **repository create** on the owner if `01-product` creates it (or pre-create it — supported) | +| classic token caveat | a classic PAT or gh OAuth token also needs the `workflow` scope to push `.github/workflows/` | +| pinning | the clone's `--branch ` pins everything: the blueprint, its modules and its hooks' scripts all come from that one commit | + +## 4. After the product is live + +- **Change the page**: `apps/web/pages/index.tsx`; its name and source link + are `apps/web/lib/site.ts`. Every merge to `main` redeploys. +- **Change a schedule**: its expression in `apps/web/lib/crons.ts` (and + the one the page shows in `pages/index.tsx`). The trigger stays + `* * * * *`; the scheduled handler dispatches every schedule from it. +- **Add a binding** (R2, D1, another namespace): a Terraform root that + lease-publishes `WIRING_`, a token in `wrangler.template.jsonc`, its + fixture entry, and in `apps/web/component.yaml` the root in the build's + `--components`, the `WIRING__` secretEnv and an enforced + `dependsOn` on it. `ai/context/operations.md` in the product says the same. +- **Custom domain**: attach it to the Worker in Cloudflare (the product's + README, "Custom domain"). There is no domain phase: attaching a domain + needs zone permissions the brokered `workers-deploy` token does not carry. + Nothing in the repository changes — the page builds its absolute links + from the request, and the trigger needs no hostname. +- **Refresh the record**: re-run `--phase 02-docs`; it is idempotent. + +## 5. Testing this baseline + +`.github/workflows/baseline.yml` runs three tiers on every pull request, and +each runs locally the same way: + +```bash +for t in manifest phases coverage rebrand retouch bootstrap-defer wire; do bash testing/$t.test.sh; done +bash testing/leak.test.sh # needs orun +bash testing/placement.test.sh # needs orun >= ci.yml's pin, node, pnpm: the offline bootstrap and the product's own plan +bash testing/e2e.test.sh # + network for pnpm and Hacker News: the product built in the job tree, dry-deployed, served, its scheduled handler fired +``` + +The offline bootstrap (`testing/lib/bootstrap.sh`) places both phases in +order and finishes each with the blueprint's OWN `run:` hooks — read out of +`repo-blueprint.yaml`, not transcribed — so the retouch marker, the rebrand, +the re-tenant, the deferrals and their restore, the lockfile and the +deployment record all run exactly as a real bootstrap runs them. Only the +platform's typed actions (task, repo, link, reconcile, land, watch, secrets, +probe) are stood in for, a landing becoming a commit. The end-to-end tier +then serves the built Worker with `wrangler dev --test-scheduled`, fires the +trigger through the scheduled handler on the clock and at crafted times that +make each schedule due, and reads each record back. What no +offline test can do is the platform's half: the namespace applied for real +(the KV root is held to `terraform validate`), the token minted, the deploy, +the trigger firing on Cloudflare's clock, the probes. + +## 6. Cutting a baseline tag (maintainers) + +Every product built from this repository resolves a `baseline-vN` tag, so +the tag is cut by a workflow rather than by hand: + +```bash +gh workflow run tag.yml -f version=baseline-v1 # from main +gh workflow run tag.yml -f version=baseline-v1 -f ref= +``` + +It refuses a version that is not `baseline-v` and a tag that already +exists: a baseline tag is never moved. Then move the registry row in +orun-cloud's `infra/baselines-registry/baselines.yaml` by pull request — +after the tag exists, because the registry's sync fetches `blueprint.yaml` +at the tag and refuses the whole catalogue if it 404s. + +## Troubleshooting + +| Symptom | Cause → fix | +|---|---| +| `01-product` parks: `waiting for github for ` | the workspace's GitHub connection is to another account. Connect the App installation on `` (console → Integrations → GitHub), then `--resume` | +| `01-product` waits on the `providers` probe, then stops | Cloudflare is not connected. Connect it (console → Integrations), then re-run the phase — the probe is a wait, not a failure | +| `01-product` stops at `link` | the repository is not linked to the workspace and the credential cannot link it. Allow-list it (console → Settings → Git repos) and re-run the phase | +| Secret WRITE fails `not_found` while listings work | the API key's role is below admin; re-mint it with the admin role | +| KV lane or deploy lane: Authentication error (10000) | the connection's token lacks Workers Scripts or KV Storage write; re-issue it, re-connect, re-run `01-product` | +| deploy lane: the Cron Trigger is refused for a limit | the account already has five Cron Triggers (the Workers Free limit) from other Workers; this product adds one per environment. Remove a trigger another Worker no longer needs and re-run `01-product` | +| web smoke fails after its retries: no recent `fetchedAt` on `/api/data/1m` | the trigger had not fired yet (a new trigger can take up to fifteen minutes to reach every location), or its run threw — `wrangler tail -web-` shows it. The watch resumes the failed lane up to three times | +| KV lane: title already exists (10014) | `adopt.tf` imports a namespace of the same title; restore it if removed. Two products with one `reponame` in one account share titles — pick another `reponame` | +| web lane fails resolving `WIRING_CLOUDFLARE_KV_` | that environment's KV apply failed — read its lane; the web lane waits on it | +| `wiring` await stops: `WIRING_CLOUDFLARE_KV` missing on stage or prod | the convergence was green but the apply published nothing: the KV component lost its `secretOutputs`, or its lane was not in the plan. Re-run the phase; its retouch marker re-plans the KV root | +| 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 KV root and the Worker re-plan | +| The product's `intent.yaml` says `workspace: ws_SET_ME` | `orunWorkspace` was empty and the build ran outside a workspace; set it and re-run `01-product` | +| A bootstrap stopped before `02-docs`; prod no longer waits on stage | the gate is deferred, not dropped: run `02-docs`, or `node tooling/bootstrap/promotion.mjs --restore --file /intent.yaml` | +| `✕ input "productdomain" is required` | all four required inputs must be set on every invocation, single-phase ones included | +| `unknown flag: --phase` or a parse error in the blueprint | the CLI is below the v2.58.11 floor | +| web lane `verify-app-structure` fails on `wrangler.jsonc` | the config is not committed. It is the fixture render of `wrangler.template.jsonc`: `pnpm run wire:fixture` and commit it | +| web lane `build-app`: `Symlink apps/web/node_modules/next is invalid, it points out of the filesystem root` | the product's intent pins stack-tectonic ≥ 0.20.0, whose lane-scoped install links each job's node_modules out of its tree, which Next 16's Turbopack refuses. Pin 0.19.0 (`intent.yaml` says why) | +| the convergence reported green, then `verify` got 404 | a second workflow ran on the push to main and the watch took its run. Only `ci.yml` may run on a push to main (`checks.yml` is pull-request only) | diff --git a/README.md b/README.md index 605a0f3..48fb85f 100644 --- a/README.md +++ b/README.md @@ -8,34 +8,82 @@ on **Cloudflare Workers + Static Assets** through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with the schedules as **Cron Triggers** on the same Worker and the records in a **Workers KV** namespace provisioned by Terraform through -[Orun](https://github.com/sourceplane/orun), inside the repository -conventions of the [Cirrus baseline](https://github.com/sourceplane/cirrus-baseline). +[Orun](https://github.com/sourceplane/orun), and packaged as an **Orun +baseline**: one command takes a new product from nothing to live on stage +and prod, in its own repository, under its own name — in ONE landing. The page and the API routes are the template's; what calls the routes on -schedule, and where they write, is Cloudflare's. See +schedule, and where they write, is Cloudflare's. What the baseline adds is +everything needed to make a copy of it somebody else's, built the way +[cirrus-baseline](https://github.com/sourceplane/cirrus-baseline) is since +its one-landing bootstrap. See [`specs/epics/cron-starter`](specs/epics/cron-starter/README.md) for the design, the milestones and the as-built status. -## What is here +## Instantiating a product + +```bash +git clone --depth 1 --branch https://github.com/sourceplane/cron-starter +cd cron-starter +orun new --blueprint repo-blueprint.yaml --out ~/sites/acme-crons --run-hooks --resume \ + --set reponame=acme-crons --set productname="Acme Crons" --set productdomain=acme.dev \ + --set githuborg=acme-inc --set subdomain= +``` + +Or, once the platform's registry lists it, from the Orun console (Baselines → +`cron-starter` → Build). Two phases: **`01-product`** creates the +repository and lands the whole product as ONE pull request — intent, CI, +tooling, the KV root, the Worker with its page, routes and Cron Trigger, +and its tests — and one convergence applies the KV namespace on stage and +prod and then deploys the Worker with its id, smoke-tested on a run its +every-minute trigger recorded; **`02-docs`** records the live deployment +from probed facts. **[BOOTSTRAP.md](BOOTSTRAP.md)** is the operator guide; +[docs/phases/](docs/phases/README.md) has a page per phase. The Workers +Free plan is enough: the product registers one Cron Trigger per Worker. + +The new repository receives the **product only** — the app, its KV root, its +tests, its CI, its tooling, a README of its own and its operating contract — +renamed throughout to the product's name, repository, Cloudflare Worker and +namespace titles. None of this repository's machinery ships. + +| What makes it a baseline | Where | +|---|---| +| The console card (inputs, secrets, programme) | `blueprint.yaml` | +| The build document (modules, phases, hooks) | `repo-blueprint.yaml` | +| This tree's identity, and the bootstrap's task contracts | `.baseline/` | +| The rename engine | `tooling/rebrand/rebrand.mjs` | +| The bootstrap's helpers (deferrals, redeploy marker, work-tree strip) | `tooling/bootstrap/` | +| The deployment-record renderer | `hooks/render-deployment-docs.sh` | +| The product's README and context pack | `.baseline/product/README.md`, `ai/context/` | +| The baseline's tests: contract, wiring, leak, offline bootstrap, end to end | `testing/`, `.github/workflows/baseline.yml` | +| Cutting a `baseline-vN` tag | `.github/workflows/tag.yml` | + +## What is here (the product) | Surface | Where | |---|---| | The page (seven intervals, each polling its record with SWR) | `apps/web/pages/index.tsx`, `apps/web/components/post.tsx` | +| The site's name and source link | `apps/web/lib/site.ts` | | The cron route (records `{ fetchedAt, id }` under the interval) | `apps/web/pages/api/cron/[cron].ts` | | The data route (reads the record, fetches the story) | `apps/web/pages/api/data/[interval].ts` | | `@vercel/kv`'s `set`/`get` over the `KV` binding | `apps/web/lib/kv.ts` | -| The Worker entry: OpenNext's `fetch` + the `scheduled` handler | `apps/web/worker.ts`, `apps/web/lib/scheduled.ts`, `apps/web/lib/crons.ts` | -| Workers build, triggers, bindings and deploy contract | `apps/web/next.config.mjs`, `open-next.config.ts`, `wrangler.template.jsonc` + `wiring.fixture.json`, `component.yaml` | +| The Worker entry: OpenNext's `fetch` + the `scheduled` handler that dispatches the schedules | `apps/web/worker.ts`, `apps/web/lib/scheduled.ts`, `apps/web/lib/crons.ts` | +| Workers build, trigger, bindings and deploy contract | `apps/web/next.config.mjs`, `open-next.config.ts`, `wrangler.template.jsonc` + `wiring.fixture.json` (→ the committed `wrangler.jsonc`), `component.yaml` | | The KV namespace (stage, prod) | `infra/terraform/cloudflare-kv` | +| The wrangler renderer | `tooling/wire` | | Tests | `tests/web` (vitest) | ## The schedules -The seven schedules are `vercel.json`'s, verbatim, now `triggers.crons` in -`apps/web/wrangler.template.jsonc`. Cron Triggers take the same five-field -expressions, in UTC. +The seven schedules are `vercel.json`'s, verbatim, now in +`apps/web/lib/crons.ts`. The Worker registers ONE Cron Trigger, every minute +(`triggers.crons` in `apps/web/wrangler.template.jsonc`), and the scheduled +handler runs every schedule whose five-field expression, in UTC, matches the +minute the trigger was scheduled for. One trigger per Worker — two for stage +and prod — fits the Workers Free plan's five per account; seven per Worker +would not. -| Interval | Expression | Fires | Route the trigger runs | +| Interval | Expression | Due | Route the handler runs | |---|---|---|---| | `1m` | `* * * * *` | every minute | `GET /api/cron/1m` | | `10m` | `*/10 * * * *` | every ten minutes | `GET /api/cron/10m` | @@ -45,10 +93,11 @@ expressions, in UTC. | `1w` | `0 0 * * 0` | Sundays at 00:00 | `GET /api/cron/1w` | | `1mo` | `0 0 1 * *` | the 1st at 00:00 | `GET /api/cron/1mo` | -A trigger hands the Worker only the expression that fired; `lib/crons.ts` -turns it back into the interval, and `lib/scheduled.ts` requests -`/api/cron/` through the OpenNext fetch handler in-process — so -the template's own route is what runs on schedule, as it did on Vercel. +The trigger hands the Worker its expression and the minute it was +scheduled for; `lib/crons.ts` says which schedules are due then, and +`lib/scheduled.ts` requests `/api/cron/` for each through the +OpenNext fetch handler in-process — so the template's own route is what runs +on schedule, as it did on Vercel. ## Getting started @@ -83,7 +132,7 @@ curl http://127.0.0.1:8808/api/data/1m # {"fetchedAt":…," The Worker's log shows `/api/cron/1m 200 "OK"` for each run; a route that answers non-2xx makes the invocation throw, which is how a failed run shows in the Workers dashboard once deployed. There, Workers → the Worker → -Triggers lists the seven Cron Triggers and their next runs; the page's +Triggers lists the one Cron Trigger and its next run; the page's "fetched N ago" is the same thing from the outside. ## How it maps to Vercel @@ -91,26 +140,44 @@ Triggers lists the seven Cron Triggers and their next runs; the page's | Vercel | Here | |---|---| | Next.js hosting | One Cloudflare Worker (`worker.ts` wrapping `.open-next/worker.js`) + Static Assets | -| Vercel Cron: `vercel.json` `crons[]` requesting `/api/cron/` | Cron Triggers: `triggers.crons` on the same Worker; the `scheduled` handler requests the same path through the OpenNext fetch handler | +| Vercel Cron: `vercel.json` `crons[]` requesting `/api/cron/` | One every-minute Cron Trigger on the same Worker; the `scheduled` handler requests the same path, for each schedule due that minute, through the OpenNext fetch handler | | Vercel KV `kv.set` / `kv.get` | Workers KV `KV` binding behind `lib/kv.ts` with the same surface (JSON values) | | `KV_URL`, `KV_REST_API_*` | No env var: the namespace id is rendered into `wrangler.jsonc` per environment from the Terraform root's wiring document | | `@vercel/analytics` | Cloudflare Web Analytics beacon (`components/analytics.tsx`), rendered when `NEXT_PUBLIC_CF_BEACON_TOKEN` is set at build | -| Deploy on push | Orun deploys `cron-starter-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`); each carries its own seven triggers and writes its own namespace | +| A KV store created in the dashboard | `infra/terraform/cloudflare-kv`, applied by Orun before the Worker deploys | +| Deploy on push | Orun applies the namespace and deploys `-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`); each carries its own trigger and writes its own namespace | +| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, deployed | The cron route is public over HTTP, as upstream (no `CRON_SECRET`); the risks file names the guard. KV is eventually consistent: a record written in one location can read as the previous value elsewhere for up to a minute, which "fetched N ago" on a polling page does not notice. -## Deploying - -`.github/workflows/checks.yml` runs install, wire, typecheck, lint, test and -build on every push and pull request. `ci.yml` is the Orun pipeline: set -`execution.state.workspace` in `intent.yaml` to this product's workspace -(`orun cloud link`), connect a Cloudflare account to it, and set the -`ORUN_CI` repository variable to `true`. A merge to `main` then applies the -KV root, renders the Worker's config with the real namespace id, and deploys -to `stage`, then `prod` — the triggers register with the Worker and start -firing on the next minute. Cloudflare caps Cron Triggers per account by -plan (5 on Workers Free, 250 on Workers Paid); seven per environment is the -template's count, so stage + prod need the Paid plan. +## How the namespace id reaches the Worker + +``` +infra/terraform/cloudflare-kv ──apply──► orun secret WIRING_CLOUDFLARE_KV (stage, prod) + │ (the landing's await checks it exists) + ▼ +apps/web dependsOn cloudflare-kv (enforced on main) · secretEnv WIRING_CLOUDFLARE_KV_ + build: tooling/wire/live.mjs → wrangler.jsonc with the environment's namespace id + (dev, verify-only, renders the fixture) → next build → opennextjs-cloudflare + deploy: worker.ts (fetch + scheduled) and its one trigger, * * * * * + smoke: /api/data/1m carries a fetchedAt the every-minute trigger recorded +``` + +`wrangler.jsonc` is committed as the fixture render of +`wrangler.template.jsonc`, because the deploy lane's `verify-app-structure` +step checks the config exists before it builds; Checks fails if the two +disagree. The render keeps the template's `main` (`worker.ts`) and its +`triggers.crons`, so the scheduled handler and its trigger survive every +lane's build; the schedules live in `lib/crons.ts`, inside the bundle. + +## CI + +| Workflow | What it runs | Ships to a product | +|---|---|---| +| `checks.yml` | install, wire fixtures (and the committed config is their render), typecheck, lint, test, build — every PR (not pushes: on main, `ci.yml` must be the only run a commit has, because the bootstrap's convergence watch takes the newest one) | yes | +| `ci.yml` | the Orun pipeline: `orun plan --changed`, then one job per lane; applies the KV namespace, then deploys stage → prod on merge — the trigger registers with the Worker and starts firing within minutes. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does | yes | +| `baseline.yml` | the baseline's own tiers: contract tests, the wiring path, the blueprint read by the pinned orun, the leak gate, the offline bootstrap with the product's own plan, the product built in the job tree, dry-deployed, served, and its scheduled handler fired | no | +| `tag.yml` | cuts a `baseline-vN` tag (manual) | no | diff --git a/ai/context/deployment.md b/ai/context/deployment.md new file mode 100644 index 0000000..592d928 --- /dev/null +++ b/ai/context/deployment.md @@ -0,0 +1,7 @@ +# cron-starter — live deployment manifest + +> Not rendered yet. The bootstrap's `02-docs` phase probes every live URL and +> regenerates this file from what answered — the workspace, the URLs and +> their status, and the secrets inventory by name. Until then, nothing here +> claims the site is live. The operating contract is +> [operations.md](operations.md). diff --git a/ai/context/operations.md b/ai/context/operations.md new file mode 100644 index 0000000..3471c71 --- /dev/null +++ b/ai/context/operations.md @@ -0,0 +1,154 @@ +# cron-starter — operating contract (for humans and agents) + +This is the standing guide to how this site is deployed and operated. +Instance facts (live URLs, workspace, secrets inventory) live in +[deployment.md](deployment.md), rendered from probed reality by the +bootstrap's `02-docs` phase; this file is the contract that stays true +between deployments. It is written to give an agent with repository read +access enough context to reason about and operate the site without any +other source. + +## What this system is + +Seven scheduled jobs and the page that shows their last runs, on Cloudflare +alone, expressed as an Orun component-native desired-state repo. + +- **`infra/terraform/cloudflare-kv`** — one Workers KV namespace per deployed + environment (`stage`, `prod`), applied by Terraform. After each apply it + publishes a wiring document — `{app_kv_id, app_kv_title}` — as the Orun + secret `WIRING_CLOUDFLARE_KV` on that environment. +- **`apps/web`** — one Worker: Next.js built by `@opennextjs/cloudflare` + plus Static Assets, with ONE **Cron Trigger**, every minute (`triggers.crons` + in `wrangler.template.jsonc`). Its entry, `worker.ts`, is OpenNext's fetch + handler plus a `scheduled` handler that checks the seven schedules in + `lib/crons.ts` against the minute the trigger was scheduled for (UTC) and + turns each one that is due into `GET /api/cron/` through that + fetch handler. The route fetches the newest Hacker News story + id and writes `{ fetchedAt, id }` under the interval's key in the `KV` + binding; `/api/data/` reads it back with the story, and the page + polls it for each schedule. +- **`tests/web`** — the schedule table, the scheduled handler, the KV shim + and the two routes against mocks (vitest), verified on the `dev` rung. +- **`tooling/*`** — shared TypeScript and ESLint configuration, and the + wrangler renderer that turns `wrangler.template.jsonc` plus a wiring + document into `wrangler.jsonc`. + +Environments: **`stage`** and **`prod`** are deployed; **`dev` is +verify-only by design** — lanes build and test, nothing deploys, no KV +namespace exists for it (its build renders the committed fixture), and no +trigger fires there. + +## Identity and tenancy + +Every remote operation runs against ONE Orun workspace, declared in +`intent.yaml` under `execution.state.workspace` — committed, enforced, and +what CI uses. Do not remove it; headless credentials depend on it. If it +reads `ws_SET_ME`, the bootstrap had no workspace to write: set the real one +before anything else. + +## How deployment works + +1. Merge (or push) to `main`. +2. CI (`.github/workflows/ci.yml`) runs `orun plan --changed` — only + components whose files changed are planned — then runs each planned lane + with `orun run --remote-state`, authenticated by GitHub OIDC (the + exchange resolves this repository's linked workspace server-side). +3. **The namespace before the Worker.** `cloudflare-kv` applies for the + environment and publishes `WIRING_CLOUDFLARE_KV`. `apps/web` declares an + enforced `dependsOn` on it for pushes to `main`, so its deploy starts only + after that apply — and a job resolves its secrets when it starts, so the + document is there. +4. `apps/web` renders `wrangler.jsonc` from that document (the real + namespace id), builds once per environment, and `wrangler deploy` ships + `cron-starter-web-` with its Cron Trigger. The smoke test fetches + `/api/data/1m` and requires a `fetchedAt` from the last ten minutes — + proof the trigger ran the every-minute schedule's route, the Worker wrote + its namespace, and reads it back. It retries for about four and a half + minutes, because a new trigger can take minutes to start firing. +5. `prod` deploys after `stage` has converged on the same commit + (`environments.prod.promotion` in intent.yaml). +6. **The convergence run is the deployment.** A green run means every + planned lane applied. Failed lanes are retried with + `gh run rerun --failed`, which resumes the same execution. + +On a pull request nothing applies or deploys: the KV root plans, the page +builds and dry-deploys, and the edges in step 3 are advisory. + +Caveats that matter: + +- A push that touches no component files plans zero lanes — that run is + green and deployed nothing. Never treat "latest run green" as "site + converged"; probe the URLs instead. +- A change to `intent.yaml`'s `environments` maps to no component and + redeploys nothing on its own. Land it with a change under `apps/web`. +- `wrangler.jsonc` is generated. Edit `wrangler.template.jsonc` and run + `pnpm run wire:fixture`; Checks fails when the two disagree. +- Cron Triggers count per account (Workers Free allows five). This site + registers one per deployed Worker — two in all — and dispatches its seven + schedules from it. Add schedules to `lib/crons.ts`, not triggers. +- A trigger change can take up to fifteen minutes to reach every Cloudflare + location. A smoke that ran out of retries right after a FIRST deploy is + that; re-run the failed lane. +- Hacker News is called live: if it does not answer, the run throws (the + previous record stays) and `/api/data/` answers an error. + +## Secrets model + +- **Brokered provider secrets**: `CLOUDFLARE_API_TOKEN` (the + `workers-deploy` scope: Workers Scripts and KV Storage write) and + `CLOUDFLARE_ACCOUNT_ID` — pointers minted per run from the workspace's + Cloudflare connection. No long-lived values at rest; nothing to rotate by + hand. The KV root and the Worker deploy (its trigger included) use the + same two. +- **Wiring**: `WIRING_CLOUDFLARE_KV` on `stage` and `prod`, written by the + KV root's apply (lease-published), read by the Worker's build as + `WIRING_CLOUDFLARE_KV_`. It holds ids, not credentials. +- Inspect by NAME only: `orun secrets list --org --project` and + `--env stage|prod`. No tooling in this repository prints a secret value, + and no document in `ai/context/` may contain one. +- The Worker needs no runtime secret. Hacker News needs no key. + +## Verifying the system + +```bash +# each environment's last every-minute run (also recorded, probed, in +# deployment.md): fetchedAt moves forward once a minute +curl -s https://cron-starter-web-stage.your-workers-subdomain.workers.dev/api/data/1m | grep -Eo '"fetchedAt":[0-9]+' +curl -s -o /dev/null -w '%{http_code}\n' https://cron-starter-web-prod.your-workers-subdomain.workers.dev/ + +# each trigger's invocations, live +pnpm --filter @app/web exec wrangler tail cron-starter-web-prod --format pretty + +# the wiring the deploys read, and workspace readiness +orun secrets list --org --env stage && orun secrets list --org --env prod +orun integrations list --org --json && orun cloud check --org +``` + +## Common operations + +| task | how | +|---|---| +| change the page | edit `apps/web/pages/index.tsx` (its name and links: `apps/web/lib/site.ts`), merge | +| change a schedule | edit its expression in `apps/web/lib/crons.ts` (and the one `pages/index.tsx` shows), merge. The trigger stays `* * * * *`: the scheduled handler dispatches every schedule from it | +| run a schedule now | `curl https:///api/cron/` (the route is public) | +| deploy a change | merge to `main`; watch the run; failed lanes → `gh run rerun --failed` | +| redeploy without a change | edit the last line of `apps/web/component.yaml` (`# orun: redeploy `) and merge — it is a deploy trigger, nothing reads it | +| add a binding (R2, D1, another KV) | a Terraform root under `infra/terraform/` that publishes `WIRING_`, a token in `wrangler.template.jsonc`, its fixture entry, the root in the build's `--components`, the `WIRING__` secretEnv and an enforced `dependsOn` on it in `apps/web/component.yaml` | +| forget a schedule's last run | `wrangler kv key delete --namespace-id --remote` (the id is in the environment's `WIRING_CLOUDFLARE_KV`) | +| serve a custom domain | attach it to the Worker in Cloudflare (README, "Custom domain"); nothing in the repository changes | +| add a runtime secret | `orun secrets set --org --env ` | +| headless credentials | `ORUN_TOKEN` (workspace-scoped) + `GITHUB_TOKEN` | + +The deployment record is the bootstrap's `02-docs` phase. Re-running it (the +Orun console's Retry on that phase, or `orun new … --phase 02-docs`) +re-probes the URLs and re-renders [deployment.md](deployment.md); it is +idempotent. + +## Evolution + +A job that must not run twice, or must run longer than a scheduled +invocation allows, is a Workflow or a Queue consumer the handler hands off +to. Structural changes follow the same +contract that deployed the site: add a component under `apps/`, `infra/` or +`packages/` with a `component.yaml`, land it as a pull request, and the +convergence run applies it. diff --git a/apps/web/README.md b/apps/web/README.md index 90f53bd..898b6a2 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -1,52 +1,41 @@ ---- -name: Vercel Cron Job Example -slug: vercel-cron -description: A Next.js app that uses Vercel Cron Jobs to update data at different intervals. -framework: Next.js -useCase: - - Cron - - Functions -css: Tailwind -database: Vercel KV -deployUrl: https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fexamples%2Ftree%2Fmain%2Fsolutions%2Fcron&project-name=cron&repository-name=cron&demo-title=Vercel%20Cron%20Job%20Example&demo-description=A%20Next.js%20app%20that%20uses%20Vercel%20Cron%20Jobs%20to%20update%20data%20at%20different%20intervals.&demo-url=https%3A%2F%2Fcron-template.vercel.app%2F&demo-image=https%3A%2F%2Fcron-template.vercel.app%2Fthumbnail.png&stores=%5B%7B"type"%3A"kv"%7D%5D -demoUrl: https://cron-template.vercel.app/ -relatedTemplates: - - hacker-news-slack-bot - - cron-og ---- - -# Vercel Cron Job Example - -A Next.js app that uses [Vercel Cron Jobs](https://vercel.com/docs/cron-jobs) to update data at different intervals. - -## Demo - -https://cron-template.vercel.app/ - -## How to Use - -You can choose from one of the following two methods to use this repository: - -### One-Click Deploy - -Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=examples-repo): - -[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fexamples%2Ftree%2Fmain%2Fsolutions%2Fcron&project-name=cron&repository-name=cron&demo-title=Vercel%20Cron%20Job%20Example&demo-description=A%20Next.js%20app%20that%20uses%20Vercel%20Cron%20Jobs%20to%20update%20data%20at%20different%20intervals.&demo-url=https%3A%2F%2Fcron-template.vercel.app%2F&demo-image=https%3A%2F%2Fcron-template.vercel.app%2Fthumbnail.png&stores=%5B%7B"type"%3A"kv"%7D%5D) - -Don't forget to set the required environment variables that you got from the previous step. - -### Clone and Deploy - -Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [pnpm](https://pnpm.io/installation) to bootstrap the example: +# apps/web — the page, its API routes and its Cron Trigger + +Seven schedules record the newest Hacker News story and the time they ran, +and a page shows each one's last run — Vercel's Cron Jobs example +([vercel/examples `solutions/cron`](https://github.com/vercel/examples/tree/main/solutions/cron), +MIT), running on Cloudflare Workers + Static Assets with the schedules +dispatched from one every-minute **Cron Trigger** on the same Worker and the +records in a **Workers KV** namespace instead of Vercel KV: + +- `pages/index.tsx` — the page: the seven intervals, each polling its record +- `pages/api/cron/[cron].ts` — what a schedule runs: fetches the newest story + id and writes `{ fetchedAt, id }` under the interval's key +- `pages/api/data/[interval].ts` — reads the record back with its story +- `worker.ts` — the Worker's entry: OpenNext's `fetch`, plus the `scheduled` + handler the trigger calls (`lib/scheduled.ts`), which turns every schedule + due at the trigger's scheduled minute into `GET /api/cron/` + through that same `fetch` +- `lib/crons.ts` — the seven expressions and their intervals, the trigger + (`* * * * *`, the only entry in `triggers.crons`) and the UTC matcher that + says which schedules are due +- `lib/kv.ts` — `kv.set` / `kv.get` over the `KV` binding +- `lib/site.ts` — the site's name and the repository its links point at ```bash -pnpm create next-app --example https://github.com/vercel/examples/tree/main/solutions/cron cron +pnpm dev # next dev on http://localhost:3000, a local KV through wrangler's platform proxy (no scheduler) +pnpm build # next build + opennextjs-cloudflare build → .open-next/ +pnpm exec wrangler dev --test-scheduled # the built Worker, same local KV, the trigger fired by hand: +curl "http://localhost:8787/__scheduled?cron=*+*+*+*+*" # now: /api/cron/1m and whatever else is due +curl "http://localhost:8787/cdn-cgi/local/scheduled?cron=*+*+*+*+*&time=1793491200000" # as at 2026-11-01 00:00 UTC: all seven +curl http://localhost:8787/api/data/1m # a record ``` -Next, run Next.js in development mode: - -```bash -pnpm dev -``` +The binding's namespace id is not hand-written. `wrangler.template.jsonc` +names it as a wiring token; `wrangler.jsonc` is that template rendered from +`wiring.fixture.json` (placeholder ids, for local work and verification), and +every deploy renders it again from the id the `cloudflare-kv` Terraform root +published for the environment (`component.yaml`'s `buildCommand`). -Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=examples-repo) ([Documentation](https://nextjs.org/docs/deployment)). +One Cron Trigger per deployed environment, two in all, fits the Workers +Free plan's five per account. KV is eventually consistent, so a record written in one location can read as the +previous run elsewhere for up to a minute — invisible for "fetched N ago". diff --git a/apps/web/component.yaml b/apps/web/component.yaml index 3df91a5..683dc43 100644 --- a/apps/web/component.yaml +++ b/apps/web/component.yaml @@ -12,10 +12,19 @@ spec: # Its own lane per environment: the Next.js build is the longest job in the # plan, and a shared lane would wait on it. lane: isolated - # The KV namespace must exist before this deploys: its id is rendered into - # the wrangler config from the cloudflare-kv root's wiring document. + # INFRA BEFORE APP. The Worker binds the KV namespace by id, and the id is + # rendered into its config during the build from the wiring document the + # cloudflare-kv root lease-publishes after its apply. A job resolves its + # secrets when it STARTS, so on a merge to main this deploy waits for that + # environment's apply (enforced) and the document is there; a pull request + # deploys nothing, so nothing on one waits (advisory). dependsOn: - component: cloudflare-kv + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request secretEnv: WIRING_CLOUDFLARE_KV_STAGE: "secret://cron-starter/cron-starter/stage/WIRING_CLOUDFLARE_KV" WIRING_CLOUDFLARE_KV_PROD: "secret://cron-starter/cron-starter/prod/WIRING_CLOUDFLARE_KV" @@ -52,9 +61,10 @@ spec: workerEntrypoint: worker.ts assetsDir: .open-next/assets - # Per-env worker name: cron-starter-web-{dev,stage,prod}. The seven Cron - # Triggers in wrangler.jsonc are registered on each deployed Worker, so - # stage and prod each write their own namespace on schedule. + # Per-env worker name: cron-starter-web-{dev,stage,prod}. The one Cron + # Trigger in wrangler.jsonc (every minute; the seven schedules are + # dispatched from it) is registered on each deployed Worker, so stage and + # prod each write their own namespace on schedule. workerName: cron-starter-web environmentAwareWorkerName: true @@ -63,13 +73,26 @@ spec: workersDevSubdomain: your-workers-subdomain installCommand: pnpm install --frozen-lockfile - # Render this environment's wrangler config from the wiring document, then - # build (the verify lane already rendered from the fixture through - # `wire:fixture`; a deploy lane re-renders with the real namespace id). - buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-kv --env "${ORUN_ENVIRONMENT}" && pnpm exec turbo run build --filter=@app/web + # Render this environment's wrangler config, then build. stage and prod + # render from the wiring document their cloudflare-kv apply published + # (secretEnv above, resolved before the job's first step); dev, which no + # root applies to and which only verifies, renders from the committed + # fixture. The committed wrangler.jsonc (the fixture render) is what the + # composition's verify-app-structure step finds before this runs; the + # render keeps its `main` (worker.ts) and its one `triggers.crons` entry. + buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-kv --env "${ORUN_ENVIRONMENT}" --fixture wiring.fixture.json --fixture-envs dev && pnpm exec turbo run build --filter=@app/web - # Smoke: the home page renders and carries the app's marker text. - smokeCommand: "html=$(curl -sfL \"${DEPLOYED_URL}/\") && echo \"${html}\" | grep -q 'Cron Triggers on Cloudflare'" + # Smoke: the CRON's effect is readable. Every minute the trigger runs + # /api/cron/1m through the scheduled handler, which records `fetchedAt` + # under `1m` in the KV namespace; /api/data/1m — answered only by the + # Worker, reading that namespace — must carry a run time no older than ten + # minutes. A page that merely renders proves neither the trigger nor the + # binding, and the site's name is the owner's to change. The composition + # retries this with backoff (~4.5 min), usually long enough for a first + # deploy's new trigger to fire (Cloudflare allows up to 15 minutes; a + # rerun of the failed lane covers the rest). The response is buffered + # before it is parsed. + smokeCommand: "body=$(curl -sf \"${DEPLOYED_URL}/api/data/1m\") && at=$(printf '%s' \"${body}\" | grep -Eo '\"fetchedAt\":[0-9]{13}' | grep -Eo '[0-9]{13}') && [ $(( $(date +%s) - at / 1000 )) -lt 600 ]" labels: team: platform layer: delivery diff --git a/apps/web/eslint.config.mjs b/apps/web/eslint.config.mjs index 822de1b..08f3baa 100644 --- a/apps/web/eslint.config.mjs +++ b/apps/web/eslint.config.mjs @@ -12,8 +12,6 @@ export default defineConfig([ // - `getLayout(Component)` in pages/_app.tsx builds the layout during // render (the @vercel/examples-ui pattern). "react-hooks/static-components": "off", - // - pages/index.tsx types its unused `data` prop as `any`. - "@typescript-eslint/no-explicit-any": "off", // worker.ts imports the generated `.open-next/worker.js` the way the // OpenNext custom-worker howto does: `@ts-ignore` with a reason, because // the file does not exist before the build and an `@ts-expect-error` @@ -30,5 +28,6 @@ export default defineConfig([ files: ["tailwind.config.js", "postcss.config.js"], rules: { "@typescript-eslint/no-require-imports": "off" }, }, - globalIgnores([".next/**", ".open-next/**", "next-env.d.ts", "cloudflare-env.d.ts"]), + // .wrangler holds the bundles `wrangler dev` writes; never source. + globalIgnores([".next/**", ".open-next/**", ".wrangler/**", "next-env.d.ts", "cloudflare-env.d.ts"]), ]); diff --git a/apps/web/lib/crons.ts b/apps/web/lib/crons.ts index 50d2a96..8415290 100644 --- a/apps/web/lib/crons.ts +++ b/apps/web/lib/crons.ts @@ -1,8 +1,10 @@ // The seven schedules vercel.json declared, each with the interval whose -// route it called (`/api/cron/`). wrangler.template.jsonc's -// `triggers.crons` lists the same seven expressions; a Cron Trigger hands the -// scheduled handler the expression that fired, and this table turns it back -// into the route. +// route it called (`/api/cron/`). They are not seven Cron Triggers: +// the Worker registers ONE, every minute (TRIGGER, the only entry in +// wrangler.template.jsonc's `triggers.crons`), and the scheduled handler runs +// every schedule below whose expression matches the minute that trigger was +// scheduled for. One trigger per Worker — two for stage and prod — fits the +// Workers Free plan's five per account; seven per Worker would not. export const crons = [ { interval: '1m', cron: '* * * * *' }, { interval: '10m', cron: '*/10 * * * *' }, @@ -15,6 +17,67 @@ export const crons = [ export type Interval = (typeof crons)[number]['interval'] -export function intervalFor(cron: string): Interval | undefined { - return crons.find((entry) => entry.cron === cron)?.interval +// The one Cron Trigger the Worker registers. +export const TRIGGER = '* * * * *' + +// minute, hour, day of month, month, day of week (0 or 7 is Sunday) +const FIELDS = [ + { min: 0, max: 59 }, + { min: 0, max: 23 }, + { min: 1, max: 31 }, + { min: 1, max: 12 }, + { min: 0, max: 7 }, +] as const + +function fieldMatches(spec: string, value: number, { min, max }: { min: number; max: number }): boolean { + return spec.split(',').some((part) => { + const [range = '', stepText] = part.split('/') + const step = stepText === undefined ? 1 : Number(stepText) + let lo: number + let hi: number + if (range === '*') { + lo = min + hi = max + } else if (range.includes('-')) { + const [from = '', to = ''] = range.split('-') + lo = Number(from) + hi = Number(to) + } else { + lo = Number(range) + hi = stepText === undefined ? lo : max + } + if (![lo, hi, step].every(Number.isInteger) || step < 1 || lo < min || hi > max) { + throw new Error(`unsupported cron field "${spec}"`) + } + return value >= lo && value <= hi && (value - lo) % step === 0 + }) +} + +// Whether a five-field cron expression fires at `at`, in UTC as Cron Triggers +// (and Vercel Cron) evaluate it. When both day fields are restricted a day +// matching either one fires, as in cron(8). +export function matches(cron: string, at: Date): boolean { + const fields = cron.trim().split(/\s+/) + const [minute, hour, dom, month, dow] = fields + if (fields.length !== 5 || !minute || !hour || !dom || !month || !dow) { + throw new Error(`"${cron}" is not a five-field cron expression`) + } + const weekday = at.getUTCDay() + const domOk = fieldMatches(dom, at.getUTCDate(), FIELDS[2]) + const dowOk = + fieldMatches(dow, weekday, FIELDS[4]) || (weekday === 0 && fieldMatches(dow, 7, FIELDS[4])) + const dayOk = dom.startsWith('*') || dow.startsWith('*') ? domOk && dowOk : domOk || dowOk + return ( + fieldMatches(minute, at.getUTCMinutes(), FIELDS[0]) && + fieldMatches(hour, at.getUTCHours(), FIELDS[1]) && + fieldMatches(month, at.getUTCMonth() + 1, FIELDS[3]) && + dayOk + ) +} + +// The schedules due at a trigger's scheduled time (ms since the epoch, the +// controller's `scheduledTime`), in table order. Every minute runs `1m`. +export function dueIntervals(scheduledTime: number): Interval[] { + const at = new Date(scheduledTime) + return crons.filter((entry) => matches(entry.cron, at)).map((entry) => entry.interval) } diff --git a/apps/web/lib/scheduled.ts b/apps/web/lib/scheduled.ts index 0a5bd48..08d0fe5 100644 --- a/apps/web/lib/scheduled.ts +++ b/apps/web/lib/scheduled.ts @@ -1,4 +1,4 @@ -import { intervalFor } from './crons' +import { TRIGGER, dueIntervals } from './crons' type FetchHandler = ( request: Request, @@ -6,11 +6,13 @@ type FetchHandler = ( ctx: ExecutionContext ) => Response | Promise -// Vercel ran each cron job by requesting its path over HTTPS. A Cron Trigger -// hands the Worker only the expression that fired, so this turns it back into -// that request: a synthetic GET to /api/cron/ through the OpenNext -// fetch handler, which means the template's own route — unchanged — is what -// runs on schedule. The origin is a placeholder; the route never reads it. +// Vercel ran each cron job by requesting its path over HTTPS. Here one Cron +// Trigger fires every minute, and this handler decides which of the seven +// schedules are due at the minute it was scheduled for (`scheduledTime`, via +// lib/crons.ts) and turns each into that request: a synthetic GET to +// /api/cron/ through the OpenNext fetch handler, which means the +// template's own route — unchanged — is what runs on schedule. The origin is a +// placeholder; the route never reads it. export const CRON_ORIGIN = 'https://cron.internal' export function makeScheduled(fetch: FetchHandler) { @@ -19,18 +21,30 @@ export function makeScheduled(fetch: FetchHandler) { env: CloudflareEnv, ctx: ExecutionContext ): Promise { - const interval = intervalFor(controller.cron) - if (!interval) { - console.warn(`scheduled: no route for cron "${controller.cron}"`) + if (controller.cron !== TRIGGER) { + console.warn(`scheduled: no route for cron "${controller.cron}" (this Worker's trigger is "${TRIGGER}")`) return } - const path = `/api/cron/${interval}` - const response = await fetch(new Request(`${CRON_ORIGIN}${path}`), env, ctx) - const body = await response.text() - if (!response.ok) { + // One at a time, and every due schedule runs even when an earlier one + // failed: at midnight on the 1st up to seven are due at once. + const failures: string[] = [] + for (const interval of dueIntervals(controller.scheduledTime)) { + const path = `/api/cron/${interval}` + try { + const response = await fetch(new Request(`${CRON_ORIGIN}${path}`), env, ctx) + const body = await response.text() + if (!response.ok) { + failures.push(`${path} answered ${response.status}: ${body}`) + continue + } + console.log(`${path} ${response.status} ${body}`) + } catch (error) { + failures.push(`${path} threw: ${error instanceof Error ? error.message : String(error)}`) + } + } + if (failures.length > 0) { // A thrown error marks the invocation failed in the Worker's logs. - throw new Error(`${path} answered ${response.status}: ${body}`) + throw new Error(failures.join('; ')) } - console.log(`${path} ${response.status} ${body}`) } } diff --git a/apps/web/lib/site.ts b/apps/web/lib/site.ts new file mode 100644 index 0000000..8b678ff --- /dev/null +++ b/apps/web/lib/site.ts @@ -0,0 +1,24 @@ +// The site's identity, written once. The page heading and its read +// SITE_NAME; the layout's repository link and "Clone & Deploy" button go to +// SOURCE_URL. Instantiating the site under a new name rewrites both to that +// name and its repository, so keep them literal and on one line each. +export const SITE_NAME = "Cron Triggers on Cloudflare" +export const SOURCE_URL = "https://github.com/sourceplane/cron-starter" + +// The origin a request was made to, for the page's absolute URLs (the Open +// Graph image). The page renders per request, so the site needs no configured +// origin: on workers.dev, on a custom domain or under `wrangler dev` it is +// whatever host the visitor asked for. +export function requestOrigin(headers: { + get(name: string): string | null | undefined +}): URL | undefined { + const host = headers.get('x-forwarded-host') ?? headers.get('host') + if (!host) return undefined + const local = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(host) + const proto = headers.get('x-forwarded-proto') ?? (local ? 'http' : 'https') + try { + return new URL(`${proto}://${host}`) + } catch { + return undefined + } +} diff --git a/apps/web/open-next.config.ts b/apps/web/open-next.config.ts index 18162d2..c2ac4dc 100644 --- a/apps/web/open-next.config.ts +++ b/apps/web/open-next.config.ts @@ -1,11 +1,11 @@ // OpenNext Cloudflare adapter config. // -// The page is static (no data fetching at render; SWR polls the API routes -// from the browser) and nothing revalidates. The static-assets incremental -// cache serves the pre-rendered page straight from the Worker's static assets -// (read only, no R2/KV/D1 to provision for the cache). The API routes are -// dynamic and run in the Worker. A template that revalidates (ISR, -// `revalidateTag`) swaps this for the R2 incremental cache plus a tag cache. +// Nothing is cached between requests and nothing revalidates: the page renders +// per request (only to put its Open Graph image on the request's origin; SWR +// polls the API routes from the browser), and the API routes are dynamic. The +// static-assets incremental cache is the read-only one, with no R2/KV/D1 to +// provision for it. A template that revalidates (ISR, `revalidateTag`) swaps +// this for the R2 incremental cache plus a tag cache. import { defineCloudflareConfig } from "@opennextjs/cloudflare/config"; import staticAssetsIncrementalCache from "@opennextjs/cloudflare/overrides/incremental-cache/static-assets-incremental-cache"; diff --git a/apps/web/pages/_app.tsx b/apps/web/pages/_app.tsx index cd091fd..e80aa99 100644 --- a/apps/web/pages/_app.tsx +++ b/apps/web/pages/_app.tsx @@ -1,6 +1,8 @@ import type { AppProps } from 'next/app' import type { LayoutProps } from '@vercel/examples-ui/layout' +import Head from 'next/head' import { CloudflareWebAnalytics } from '@/components/analytics' +import { SITE_NAME, SOURCE_URL } from '@/lib/site' import { getLayout } from '@vercel/examples-ui' import '@vercel/examples-ui/globals.css' @@ -8,16 +10,25 @@ import '@vercel/examples-ui/globals.css' function App({ Component, pageProps }: AppProps) { const Layout = getLayout<LayoutProps>(Component) + // The <title> is the site's name (lib/site.ts), and it and the description + // are rendered here rather than through the layout's `title`/`description` + // props: the layout's own <Head> does not reach the server-rendered page, + // and it would suffix the title with " - Vercel Examples". return ( <Layout - title="Cron Triggers Example" deployButton={{ - repositoryUrl: 'https://github.com/sourceplane/cron-starter', - customDeployUrl: 'https://github.com/sourceplane/cron-starter', + repositoryUrl: SOURCE_URL, + customDeployUrl: SOURCE_URL, }} path="solutions/cron" - description="How to use Cloudflare Cron Triggers to update data at different intervals" > + <Head> + <title>{SITE_NAME} + + diff --git a/apps/web/pages/index.tsx b/apps/web/pages/index.tsx index 656257b..530ac59 100644 --- a/apps/web/pages/index.tsx +++ b/apps/web/pages/index.tsx @@ -1,6 +1,8 @@ +import type { GetServerSideProps } from 'next' import { Layout, Text, Code, Page, Link } from '@vercel/examples-ui' import Post from '@/components/post' import Head from 'next/head' +import { SITE_NAME, requestOrigin } from '@/lib/site' const intervals = [ { @@ -42,15 +44,29 @@ const intervals = [ const image = '/thumbnail.png' -export default function Home({ data }: { data: any }) { +type Props = { origin: string | null } + +// An Open Graph image must be an absolute URL, so the page is rendered per +// request and builds it on the origin it was asked on (lib/site.ts) — right on +// workers.dev, on a custom domain and under `wrangler dev`, with no configured +// site URL. The cron data itself still loads in the browser, as upstream. +export const getServerSideProps: GetServerSideProps = async ({ req }) => { + const origin = requestOrigin({ + get: (name) => [req.headers[name]].flat()[0] ?? null, + }) + return { props: { origin: origin?.origin ?? null } } +} + +export default function Home({ origin }: Props) { + const imageUrl = origin ? `${origin}${image}` : image return ( - - + +
- Cron Triggers on Cloudflare + {SITE_NAME} This example shows you how you can use{' '} ) of every schedule whose expression + // matches the minute the trigger was scheduled for. One trigger per Worker — + // two for stage and prod — fits Workers Free's five per account. + "triggers": { + "crons": ["* * * * *"] + }, + // The last-run store — Workers KV in place of Vercel KV. + "kv_namespaces": [ + { + "binding": "KV", + "id": "00000000000000000000000000000001" + } + ] +} diff --git a/apps/web/wrangler.template.jsonc b/apps/web/wrangler.template.jsonc index 6fb8878..9cce59b 100644 --- a/apps/web/wrangler.template.jsonc +++ b/apps/web/wrangler.template.jsonc @@ -1,8 +1,11 @@ -// Rendered to wrangler.jsonc (git-ignored) by tooling/wire: the verify lane -// renders from wiring.fixture.json, the deploy lane from the wiring document -// the `cloudflare-kv` Terraform root lease-publishes (WIRING_CLOUDFLARE_KV_). -// The workers-assets composition deploys one environment per job with no -// wrangler `--env`, so `__ENV__` names the environment this is rendered for. +// The source of wrangler.jsonc, which tooling/wire renders from it: from +// wiring.fixture.json for local work (`pnpm run wire:fixture`, committed as +// that render), and on every Orun lane from the wiring document the +// `cloudflare-kv` Terraform root lease-publishes (WIRING_CLOUDFLARE_KV_) +// — dev, which no root applies to, from the fixture (component.yaml's +// buildCommand). Edit this file, never wrangler.jsonc. The workers-assets +// composition deploys one environment per job with no wrangler `--env`, so +// `__ENV__` names the environment this is rendered for. { "$schema": "node_modules/wrangler/config-schema.json", "name": "cron-starter-web", @@ -16,19 +19,13 @@ "binding": "ASSETS" }, "observability": { "enabled": true }, - // The seven schedules vercel.json declared, verbatim. Each fires the - // scheduled handler with its expression; lib/crons.ts maps the expression - // back to the interval whose route Vercel called (/api/cron/). + // ONE Cron Trigger, every minute. The seven schedules vercel.json declared + // are dispatched from it: lib/crons.ts holds them, and the scheduled handler + // runs the route (/api/cron/) of every schedule whose expression + // matches the minute the trigger was scheduled for. One trigger per Worker — + // two for stage and prod — fits Workers Free's five per account. "triggers": { - "crons": [ - "* * * * *", - "*/10 * * * *", - "0 * * * *", - "0 */12 * * *", - "0 0 * * *", - "0 0 * * 0", - "0 0 1 * *" - ] + "crons": ["* * * * *"] }, // The last-run store — Workers KV in place of Vercel KV. "kv_namespaces": [ diff --git a/blueprint.yaml b/blueprint.yaml new file mode 100644 index 0000000..668dc7e --- /dev/null +++ b/blueprint.yaml @@ -0,0 +1,144 @@ +# The cron-starter card: what the console's Blueprints page renders and +# the platform's bootstrap door consumes. +# +# THIS FILE IS NOT THE BUILD. `spec.bootstrap.blueprint` names the build +# document — `repo-blueprint.yaml`, whose phases a runner places. This card is +# what an operator reads and fills in before pressing Build, and +# `testing/manifest.test.sh` compares every list below to the document that +# actually does the thing, not to a copy of itself. +# +# The division of labour with the registry is strict: the registry (orun-cloud +# `infra/baselines-registry/baselines.yaml`) owns identity and commerce — id, +# visibility, tier, the pinned tag. This file owns the build contract. Neither +# restates the other, which is why there is no `tag` here: this file is +# fetched AT the tag the registry pins. +apiVersion: orun.io/v1 +kind: Blueprint +metadata: + name: cron-starter + displayName: Cron Jobs — scheduled work on Cloudflare Cron Triggers + description: > + Vercel's Cron Jobs example as a product of its own: seven schedules, from + every minute to monthly, each recording the newest Hacker News story and + its run time, and a page that shows every schedule's last run. Built by + OpenNext into one Cloudflare Worker with Static Assets whose one + every-minute Cron Trigger dispatches the seven schedules to its own API + routes, the runs in a Workers KV namespace Terraform provisions per + environment, and CI that applies the namespace and deploys the Worker to + stage and prod on merge. One provider, one consent, one token; the + Workers Free plan is enough. Live in about fifteen minutes, in one + landing. + tags: [cron, scheduled, cloudflare, nextjs, kv, terraform] +spec: + source: + repo: sourceplane/cron-starter + # No `tag`. The registry pins it; this file is fetched at it. + + # ── What the operator reads first ──────────────────────────────────────── + overview: + lede: > + Scheduled work without a server: one Cron Trigger on a Next.js + Worker dispatches seven schedules to its own API routes, each run + recorded in Workers KV, and the page reads them back. Merge, and the namespace is applied before + the Worker that binds it is deployed. + architecture: + - layer: Edge + items: [web (page, API routes, Cron Trigger)] + - layer: Data + items: [Workers KV (cloudflare-kv)] + - layer: Delivery + items: [GitHub Actions, OpenNext, Terraform] + outcome: + - Live on stage and prod, in one landing + - The KV namespace applied before the Worker that binds it + - Seven schedules recording runs from the first minute + - Every merge redeploys, smoke-tested on a recorded run + - Its own CI from the first commit + + requires: + # Cloudflare is the only provider connection a bootstrap needs. GitHub + # arrives as the App installation plus the repo link, not as a + # connection row. + integrations: [github, cloudflare] + apiKeyRole: admin # secret writes need the admin floor + + # Every input is collected by the console: keys are lowercase (the + # platform's reader refuses anything else), every one carries the `pattern` + # its value is checked against before Continue, and a value the console + # already holds says so with `from`. repo-blueprint.yaml declares the same + # names; `repoPrivate`, `orunWorkspace` and `epicSlug` are build inputs with + # defaults (or filled from the build's workspace) and are not asked. + inputs: + - key: reponame + label: Repo name + pattern: "^[a-z][a-z0-9-]{1,38}$" + # The operator picked the repository; its name IS this value. + from: repo.name + - key: productname + label: Site name + pattern: "^[A-Za-z0-9][A-Za-z0-9 .,'&-]{1,48}$" + help: The name visitors see — the page's heading and its title. + example: Acme Crons + - key: productdomain + label: Site domain + pattern: "^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$" + help: The domain the site will answer on. It does not need to exist — the site goes live on workers.dev first. + example: acme.dev + - key: githuborg + label: GitHub organisation + pattern: "^[A-Za-z0-9][A-Za-z0-9-]*$" + help: The GitHub org or user the site's repository is created under. + # DERIVED FROM THE CHOSEN REPOSITORY: its owner IS this value. Declared + # because repo-blueprint.yaml requires it — a build may declare more + # inputs than this card, but not require one nobody supplies. + from: repo.owner + - key: subdomain + label: workers.dev subdomain + pattern: "^[a-z0-9][a-z0-9-]{0,62}$" + help: The workers.dev subdomain of the Cloudflare account the site deploys into. + example: acme + + # ── PREVIEW ONLY. repo-blueprint.yaml's `orun.integrations/reconcile@v1` + # hooks mint these, brokered, during 01-product. ───────────────────────── + # Transcribed from those hooks' own `keys:` and `template:` values, so + # testing/manifest.test.sh compares this list to the document that mints + # them. The console renders them read-only: no credential is ever typed, + # shown or stored. Keys that already exist are kept. The KV namespace ids + # are not here: they are not credentials, and the namespace's own apply + # publishes them. + secrets: + - key: CLOUDFLARE_API_TOKEN + provider: cloudflare + template: workers-deploy + why: Applies the KV namespace and deploys the Worker, its static assets and its Cron Trigger + - key: CLOUDFLARE_ACCOUNT_ID + provider: cloudflare + template: account-id + why: Connection fact, not a secret + fact: true + + # ── PREVIEW ONLY. repo-blueprint.yaml's run-level `hooks.preInstantiate` + # opens these — the epic, every milestone in this order, every task — before + # the first phase places. Idempotent by identity, so a re-run finds what it + # made before. + programme: + epicSlug: cron-baselining # = repo-blueprint.yaml's `epicSlug` default + epicName: "Cron baselining — {productname}" + milestones: + # The whole product is one landing (01-product): the repository, the KV + # root, the Worker and its tests are one pull request and one convergence. + - name: 01-product + - name: 02-docs + + bootstrap: + # THE BUILD DOCUMENT. There is no umbrella workflow and no agent brief: + # every phase is declared in it and orun runs it. + blueprint: repo-blueprint.yaml + # Summed from the phases' expectedMinutes. An estimate until a bootstrap + # measures it. + expectedMinutes: 15 + tokenChannel: ORUN_TOKEN_FILE # how a runner hands over its refreshed token + verify: + urls: + - "https://{reponame}-web-{env}.{subdomain}.workers.dev" + envs: [stage, prod] diff --git a/docs/phases/01-product.md b/docs/phases/01-product.md new file mode 100644 index 0000000..4a5a8ee --- /dev/null +++ b/docs/phases/01-product.md @@ -0,0 +1,74 @@ +# 01-product — the product, built in one landing + +**Places** every module: the root manifests, CI, tooling and the identity +file; `infra/terraform/cloudflare-kv` (the KV namespace per environment); +`apps/web` (the page and its two API routes, the custom Worker entry and its +scheduled handler, which dispatches the seven schedules, its OpenNext build, +its wrangler template — the one Cron Trigger among it — and fixture, its +deploy contract); `tests/web` (vitest). Then brands them, lands them as +ONE pull request, and watches the ONE convergence that merge triggers. + +**Requires** both connections live — GitHub (the App installation on the +OWNER of the repository, the only way the platform sees its pull requests) +and Cloudflare (every deploy credential below is minted from it) — probed, +waited for up to ten minutes each, so the consent can be clicked while it +waits. + +## What runs + +| hook | what it does | +|---|---| +| `task` (pre) | finds the phase's task and yields its key | +| `retouch` | the redeploy marker on the components `.baseline/tasks/01-product.TaskContract.yaml` names: `cloudflare-kv`, `web`, `web-tests` | +| `git-init`, `stage`, `rebrand` | the tree becomes a repository, then the product's | +| `orun-workspace` | intent.yaml's `workspace:` becomes the product's (or `ws_SET_ME`, which fails loudly) | +| `work-tree` | intent.yaml's `work:` block — this repository's epics and tasks — is removed | +| `promotion`, `dev-lanes` | prod's promotion gate and dev's push-to-main activation deferred until `02-docs` | +| `restage`, `rebrand-verify` | the sweep: no identity of this baseline left anywhere | +| `pnpm-lockfile` | confirms the baseline's complete lockfile against the placed tree | +| `repo` | `orun.repo/ensure@v1` creates `/` (or finds it) | +| `link` | the repository becomes the workspace's; `orun cloud check` is the gate | +| `secret-workers-deploy` | `orun.integrations/reconcile@v1` — `CLOUDFLARE_API_TOKEN` from the `workers-deploy` template: Workers Scripts and KV Storage write, so ONE token applies the namespace and deploys the Worker with its Cron Trigger | +| `secret-account-id` | `CLOUDFLARE_ACCOUNT_ID`, the connection fact both bind | +| `land` | one PR bound to the task, merged once its checks (Checks, and `plan`) are green | +| `converge` (await) | `orun.run/watch@v1` on the merge commit's run; resumes it up to three times | +| `wiring` (await) | `orun.secrets/exists@v1` — `WIRING_CLOUDFLARE_KV` exists on stage and prod | +| `verify` (await) | `orun.http/probe@v1` on both workers.dev URLs | + +## What the convergence does + +`orun plan --changed` on the merge plans, with dev's push activation and the +promotion gate deferred: + +| lane | waits on | does | +|---|---|---| +| `cloudflare-kv · stage` / `· prod` | nothing | `terraform apply` of `stg--app-kv-stage` / `prod--app-kv-prod`, adopting a namespace of that title if one exists (`adopt.tf`), then lease-publishes `WIRING_CLOUDFLARE_KV` = `{app_kv_id, app_kv_title}` on that environment | +| `stage · web` / `prod · web` | that environment's KV apply (`dependsOn: cloudflare-kv`, `mode: enforced` on main) | resolves `WIRING_CLOUDFLARE_KV_` as it starts, renders `wrangler.jsonc` with the real namespace id (and its one trigger), builds with OpenNext, deploys `-web-` with its entry `worker.ts`, and smoke-tests it: `/api/data/1m` must carry a `fetchedAt` from the last ten minutes — a run the trigger recorded through the scheduled handler, read back by the Worker. The smoke retries for ~4.5 minutes while the new trigger starts firing | + +Stage and prod run side by side. `web-tests` verifies on dev only, so on the +merge its gate is the pull request's Checks run, which the landing waited +for. + +## Verified + +The convergence run for the merge commit is green; `WIRING_CLOUDFLARE_KV` +exists on stage and prod; `https://-web-{stage,prod}..workers.dev` +answer. + +## Troubleshooting + +| symptom | cause → fix | +|---|---| +| parks on the `providers` probe | GitHub (on the repository's owner) or Cloudflare is not connected to the workspace. Connect it (console → Integrations), then re-run the phase — the probe is a wait, not a failure | +| stops at `link` | the repository is not linked to the workspace and the credential cannot link it. Allow-list it (console → Settings → Git repos) and re-run the phase | +| KV lane: `a namespace with this account ID and title already exists` (10014) | `adopt.tf` imports a namespace of the same title; if it was removed, restore it. Two products with the same `reponame` in one account share a title — use a distinct `reponame` | +| KV lane or deploy lane: Authentication error (10000) | the connection's token lacks Workers Scripts or KV Storage write. Re-issue it with the permission groups the console's Connect recipe lists, re-connect, re-run the phase | +| deploy lane: the trigger is refused (a Cron Trigger limit) | the account already has five Cron Triggers (the Workers Free limit) from other Workers; this product adds one per environment. Remove a trigger another Worker no longer needs and re-run the phase | +| smoke fails after its retries: no `fetchedAt` on `/api/data/1m` | the every-minute trigger had not fired yet — a new trigger can take up to fifteen minutes to reach every location — or its run threw (the Worker's logs: `wrangler tail -web-`; Hacker News not answering is one cause). `orun.run/watch@v1` resumes the failed lane up to three times; a later attempt finds the run | +| web lane fails resolving `WIRING_CLOUDFLARE_KV_` | that environment's KV apply failed or never ran — read its lane; the web lane waits on it, so it shows as not run on a fresh failure | +| web lane `build-app`: `wire: missing wiring documents` | the job started without the document — the `dependsOn` edge is gone from `apps/web/component.yaml`, or the secretEnv names the wrong key | +| web lane `verify-app-structure`: `test -f wrangler.jsonc` fails | `apps/web/wrangler.jsonc` is not committed (an old `.gitignore` entry); render it with `pnpm run wire:fixture` and commit it | +| `build-app` fails: `Symlink apps/web/node_modules/next is invalid, it points out of the filesystem root` | the site's `intent.yaml` pins stack-tectonic ≥ 0.20.0 (lane-scoped install). Pin 0.19.0 — `intent.yaml`'s comment says why | +| smoke fails right after the FIRST deploy | workers.dev route or trigger propagation; the composition retries the first deploy and the smoke with backoff (stack-tectonic ≥ 0.19.0). A convergence resume clears what is left | +| the watch says green, the probe says 404 | another workflow ran on the push and the watch took its run. Only `ci.yml` may run on a push to main | +| convergence failed AFTER the PR merged; re-running lands nothing | the hooks did not run (`--run-hooks`), or the contract names no component — `node tooling/bootstrap/retouch.mjs --check --affects .baseline/tasks/01-product.TaskContract.yaml` in the site's tree says which | diff --git a/docs/phases/02-docs.md b/docs/phases/02-docs.md new file mode 100644 index 0000000..3749c1d --- /dev/null +++ b/docs/phases/02-docs.md @@ -0,0 +1,40 @@ +# 02-docs — the deployment, recorded + +**Places** nothing. Its work is hooks: it records what `01-product` built, +from probed facts rather than from what the blueprint intended, and it puts +back the two things `01-product` deferred for the bootstrap's sake. + +**Requires** `01-product` placed. (A hook-only phase derives as `unknown`, so +no phase may require this one.) + +## What runs + +| hook | what it does | +|---|---| +| `task` (pre) | finds the phase's task and yields its key | +| `promotion` | restores `environments.prod.promotion` — from now on prod deploys only after stage | +| `dev-lanes` | restores dev's activation on pushes to main | +| `render` | `hooks/render-deployment-docs.sh`: probes `/` and `/api/data/1m` on both environments (how long ago the every-minute trigger recorded a run), lists the secrets by name and the workspace's integrations, and regenerates `ai/context/deployment.md` and the README's live-deployment section | +| `land` | one PR, waited for and merged. It touches no component, so it deploys nothing | +| `verify` (await) | the same probe `01-product` ended on | + +## Re-running it + +Idempotent, and the way to refresh the record after a redeploy or a custom +domain: every generated section is re-rendered from scratch. + +```bash +orun new --blueprint repo-blueprint.yaml --out \ + --run-hooks --phase 02-docs --values +``` + +## If a bootstrap stops before this phase + +The promotion gate and dev's push activation stay deferred: `intent.yaml` +carries a `# @promotion-deferred:…` and a `# @dev-lanes-deferred:…` marker. +Running this phase restores both, or by hand from the baseline checkout: + +```bash +node tooling/bootstrap/promotion.mjs --restore --file /intent.yaml +node tooling/bootstrap/dev-lanes.mjs --restore --file /intent.yaml +``` diff --git a/docs/phases/README.md b/docs/phases/README.md new file mode 100644 index 0000000..47ef6f7 --- /dev/null +++ b/docs/phases/README.md @@ -0,0 +1,107 @@ +# The phases — one blueprint, two selections + +`repo-blueprint.yaml` declares two phases that take a site from **nothing** +to **live on stage and prod, documented**. Run them one at a time with +`--phase `, or the whole sequence unattended with `--resume`. There is +no umbrella workflow and no per-phase document: a phase is a selection on one +artifact, which is what makes running one alone, months later, from a fresh +container the same operation as running them all. + +The product phase follows the contract every deploying phase does: + +> **place its modules → brand them → land them as one pull request → watch +> the convergence that merge triggers (auto-resumed) → check what the +> convergence published → verify the outcome over HTTP.** + +Run from the baseline checkout (the blueprint's source is `path: .`); the +site's repository is wherever `--out` points. + +## Execution order + +| phase | lands | verified by | +|---|---|---| +| [`01-product`](01-product.md) | **the GitHub repo created** and the whole product in ONE pull request: intent, CI, tooling, identity, the KV root, the Worker (page, API routes, Cron Triggers) and its tests | the convergence green (KV applied, then the Worker built, deployed and smoke-tested on a run its every-minute trigger recorded), `WIRING_CLOUDFLARE_KV` on stage and prod, both URLs answering | +| [`02-docs`](02-docs.md) | the live-deployment record; the promotion gate and dev's lanes put back | committed manifest matches probed reality | + +**One landing, not three.** Before the one-landing shape a site like this +landed its scaffold, its data plane and its app as separate pull requests, +because the namespace had to exist before the Worker that binds it. The +plan carries that order now: `apps/web` declares `dependsOn: cloudflare-kv` +with `mode: enforced` on a push to main, so the convergence that follows the +one merge applies the namespace first and deploys the Worker after it — and a +job resolves its secrets when it starts, so the namespace id the apply +published is there. On a pull request the edge is advisory: nothing deploys. +`testing/phases.test.sh` checks the edge; `testing/placement.test.sh` checks +the product's own plan honours it. + +Every landing is a pull request on a branch named for its task +(`orun/BASE--`). On those branches `ci.yml` runs `plan` only — the +intent, every component and every composition resolve — and skips the lanes, +because the merge runs them on main a minute later, for real, and that +convergence is what the phase watches. `checks.yml` (install, the fixture +render, typecheck, lint, test, build) runs on every pull request regardless, +and the product's landing waits for it. + +There is no custom-domain phase. Attaching a domain to a Worker needs zone +permissions the platform's brokered `workers-deploy` token does not carry, so +it is an owner's step after the bootstrap — the site's README, "Custom +domain", says how. Nothing in the repository changes for it: the page builds +its absolute links from the request, and the trigger needs no hostname. + +## Inputs + +`01-product` takes the site's identity once and writes it into the repo +(`.rebrand/values.json`); `02-docs` reads it back from the placed tree. But +the blueprint's **required** inputs — `reponame`, `productname`, +`productdomain`, `githuborg` — are validated before any phase runs, so they +must be supplied on every invocation, single-phase ones included. A +`--values` file is easier than repeating `--set`. + +- `subdomain` — the workers.dev subdomain of the Cloudflare account. It is + in every URL the phases probe. +- `orunWorkspace` — workspace id (`ws_…`). Unset, it is the workspace the + build runs in (`from: workspace`); with none anywhere, a placeholder that + fails loudly rather than silently claiming another tenant's workspace. +- `epicSlug` (default `cron-baselining`) — the epic every phase clubs + its task under. Found by slug, so a fresh run and a resumed run find the + same work. +- `repoPrivate` (default `true`) — the repository's visibility at creation. + +```bash +orun new --blueprint repo-blueprint.yaml \ + --out $HOME/sites/acme-crons --run-hooks --phase 01-product \ + --values ~/acme-crons.values.yaml +``` + +Drop `--run-hooks` (or add `--status`) to preview. Without it a phase places +files and stops: no repo, no landing, no convergence watch, and no probe — +which is exactly what makes a dry instantiation of this baseline possible in +CI with no workspace and no provider (`testing/placement.test.sh`, +`testing/e2e.test.sh`). + +## What the product phase does after it places + +Placement writes the baseline's files as they are here. Before the phase +lands, its `post` hooks make them the site's: + +1. `retouch` — one `# orun: redeploy 01-product ` line at the end of + each component.yaml its task contract names (`cloudflare-kv`, `web`, + `web-tests`), so a re-run after a failed convergence still has a diff to + land and re-plans exactly those components. +2. `git init`, stage, `rebrand`, the workspace rewrite, the work-tree strip, + the two bootstrap deferrals (prod's promotion gate, dev's push lanes), + restage, `rebrand --verify` — the identity rename over the whole tree, + then a sweep that fails on any of this baseline's identity left behind. +3. `pnpm install --lockfile-only` — confirms the baseline's complete + lockfile against the placed tree, so `--frozen-lockfile` installs pass. +4. `repo`, `link`, the brokered Cloudflare credentials, `land`. + +## When a phase fails + +- **Before it lands** (a probe that timed out, a rebrand residue, a refused + link): nothing was merged. Fix what the message names and re-run the phase. +- **After it lands** (the convergence went red): the files are on main. + `orun.run/watch@v1` has already resumed the run up to three times. Re-run + the phase (`--phase 01-product`, `--redo 01-product` under `--resume`, or + the console's Retry): its `retouch` hook gives the landing a diff and the + KV root and the Worker re-plan. diff --git a/hooks/render-deployment-docs.sh b/hooks/render-deployment-docs.sh new file mode 100755 index 0000000..632751c --- /dev/null +++ b/hooks/render-deployment-docs.sh @@ -0,0 +1,191 @@ +#!/usr/bin/env bash +# Render the site's LIVE-DEPLOYMENT documentation from verified state. +# Called by phase 02-docs as a `run:` hook (and safe to run by hand, from the +# site's checkout). Idempotent: the generated file and the README section are +# fully re-rendered on every run, so re-running after a redeploy or a custom +# domain refreshes them. +# +# hooks/render-deployment-docs.sh +# +# What it writes (in ): +# ai/context/deployment.md — REGENERATED: URLs with live probe results (and +# how long ago each Worker's every-minute Cron +# Trigger recorded a run in KV), identity, the +# KV wiring, secrets inventory BY NAME, +# integrations +# ai/context/operations.md — healed from the baseline's copy if absent +# (the static operating contract; never rewritten) +# README.md — the section between +# is replaced (appended after the title if the +# README predates the markers) +# +# No secret VALUE is ever read or written here — inventories are names only. +set -euo pipefail + +out="${1:?usage: render-deployment-docs.sh }" +ws="${2:-}" +L="${3:?usage: render-deployment-docs.sh }" + +cd "$out" +vals=".rebrand/values.json" +[ -f "$vals" ] || { echo "render-docs: $vals missing — is this a scaffolded site?" >&2; exit 1; } +val() { python3 -c "import json,sys;print(json.load(open('$vals')).get(sys.argv[1],'') or '')" "$1"; } + +repo="$(val reponame)" +brand="$(val brandSlug)"; [ -n "$brand" ] || brand="$repo" +sub="$(val subdomain)"; [ -n "$sub" ] || sub="your-workers-subdomain" +[ -n "$ws" ] || ws="$(sed -n 's/^[[:space:]]*workspace:[[:space:]]*\([^[:space:]#]*\).*/\1/p' intent.yaml | head -1)" +[ -n "$ws" ] || ws="?" + +# Workspace slug via the direct backend read; tolerate failure. +slug="$( { orun workspace "$ws" 2>/dev/null || true; } | sed -n 's/^ *slug: *//p' | head -1)" +[ -n "$slug" ] || slug="?" + +# CI lane pin (what version the deploy lanes run). +lanepin="$(sed -n 's/^ *version: *\(v[0-9.]*\) *$/\1/p' .github/workflows/ci.yml 2>/dev/null | head -1)" +[ -n "$lanepin" ] || lanepin="?" + +# The every-minute Cron Trigger runs /api/cron/1m through the Worker's +# scheduled handler, which records `fetchedAt` under `1m` in the KV namespace; +# /api/data/1m reads it back. So a fresh `fetchedAt` there is a trigger that +# fires, a Worker that writes its namespace and one that reads it. curl emits +# the -w format even on connection failure (000) — capture, don't append, or a +# failed probe reads "000000". +probe() { # URL → " " + local body code at + body="$(mktemp)" + code="$(curl -s -o "$body" -w '%{http_code}' --max-time 20 "$1" 2>/dev/null)" || true + at="$(grep -Eo '"fetchedAt":[0-9]{13}' "$body" 2>/dev/null | grep -Eo '[0-9]{13}' | head -1)" || true + if [ -n "$at" ]; then + printf '%s %s' "${code:-000}" "$(( $(date +%s) - at / 1000 ))" + else + printf '%s none' "${code:-000}" + fi + rm -f "$body" +} +badge() { # " " + local code="${1%% *}" age="${1#* }" + case "$code" in + 2*) [ "$age" = none ] && echo "answering $code, no run recorded yet" \ + || echo "LIVE ($code) — the every-minute trigger last recorded a run ${age}s before this probe" ;; + 3*) echo "LIVE ($code)" ;; + 000) echo "unreachable" ;; + *) echo "answering $code" ;; + esac +} +page() { # URL → the page's status + local code + code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 "$1" 2>/dev/null)" || true + case "${code:-000}" in 2*|3*) echo "LIVE (${code})" ;; 000) echo "unreachable" ;; *) echo "answering ${code}" ;; esac +} + +stage_url="https://${brand}-web-stage.${sub}.workers.dev" +prod_url="https://${brand}-web-prod.${sub}.workers.dev" +rows="" +for pair in "stage|$stage_url" "prod|$prod_url"; do + env="${pair%%|*}"; url="${pair#*|}" + rows+="| page (${env}) | ${url} | $(page "$url/") |"$'\n' + rows+="| last cron run (${env}) | ${url}/api/data/1m | $(badge "$(probe "$url/api/data/1m")") |"$'\n' +done + +secrets_list() { { orun secrets list --org "$ws" "$@" 2>/dev/null || true; } | awk 'NR>1 && NF {print " - "$1}'; } +secrets_proj="$(secrets_list --project)"; [ -n "$secrets_proj" ] || secrets_proj=" - (listing unavailable to this credential)" +secrets_stage="$(secrets_list --env stage)"; [ -n "$secrets_stage" ] || secrets_stage=" - (listing unavailable to this credential)" +secrets_prod="$(secrets_list --env prod)"; [ -n "$secrets_prod" ] || secrets_prod=" - (listing unavailable to this credential)" +integrations="$( { orun integrations list --org "$ws" --json 2>/dev/null || true; } | python3 -c " +import json,sys +try: rows=json.load(sys.stdin) +except Exception: rows=[] +out=[f\" - {r.get('provider','?')}: {r.get('status','?')}\" for r in rows] +print('\n'.join(out) if out else ' - (listing unavailable to this credential)')" )" + +now="$(date -u +%Y-%m-%dT%H:%M:%SZ)" + +# Heal the static operating contract when the site predates it. +mkdir -p ai/context +if [ ! -f ai/context/operations.md ] && [ -f "$L/ai/context/operations.md" ]; then + cp "$L/ai/context/operations.md" ai/context/operations.md + git add ai/context/operations.md 2>/dev/null || true + node "$L/tooling/rebrand/rebrand.mjs" --values "$vals" --allow-dirty >/dev/null 2>&1 || true + echo "render-docs: healed ai/context/operations.md" +fi + +cat > ai/context/deployment.md < GENERATED by the \`02-docs\` phase on ${now}; re-run it to refresh +> (idempotent; see [operations.md](operations.md)). Hand-edits here are +> overwritten. No secret values appear in this file — inventories are names +> only. + +## Identity + +| | | +|---|---| +| repository / project slug | \`${repo}\` | +| Orun workspace | \`${ws}\` (slug \`${slug}\`) | +| declared in | \`intent.yaml\` → \`execution.state.workspace\` | +| Workers | \`${brand}-web-stage\`, \`${brand}-web-prod\` on \`${sub}.workers.dev\` | +| Cron Trigger | one per Worker, every minute (\`apps/web/wrangler.template.jsonc\`); it dispatches the seven schedules in \`apps/web/lib/crons.ts\`, every minute to monthly | +| KV namespaces | \`stg-${repo}-app-kv-stage\`, \`prod-${repo}-app-kv-prod\` (\`infra/terraform/cloudflare-kv\`); their ids reach the Workers as \`WIRING_CLOUDFLARE_KV\` on each environment | +| CI lane CLI pin | orun \`${lanepin}\` (\`.github/workflows/ci.yml\`) | + +## Public URLs (probed ${now}) + +| surface | URL | status | +|---|---|---| +${rows} +The \`dev\` environment is verify-only by design — no deployed URL, no +namespace and no triggers. + +## Secrets inventory (names only) + +Project rung: +${secrets_proj} + +Environment \`stage\`: +${secrets_stage} + +Environment \`prod\`: +${secrets_prod} + +Provider secrets are BROKERED (minted per run from the workspace's Cloudflare +connection; no long-lived values at rest). \`WIRING_CLOUDFLARE_KV\` is written +by the KV root's apply and holds ids, not credentials. + +## Workspace integrations + +${integrations} + +## How this deployment changes + +Merges to \`main\` converge automatically: CI plans the changed components and +runs each lane with \`orun run --remote-state\` against the workspace above — +the KV namespace first, then the Worker and its trigger. See [operations.md](operations.md) for +the full operating contract. +EOF +echo "render-docs: wrote ai/context/deployment.md" + +python3 - <<'PY' +import re +begin, end = "", "" +body = f"""{begin} +This site is **live**. Verified URLs, identity and the secrets inventory are +recorded in [ai/context/deployment.md](ai/context/deployment.md) (re-rendered +by the `02-docs` phase); how it deploys and how to operate it: +[ai/context/operations.md](ai/context/operations.md). +{end}""" +s = open("README.md").read() +if begin in s and end in s: + s = re.sub(re.escape(begin) + r".*?" + re.escape(end), lambda _m: body, s, count=1, flags=re.S) +else: + lines = s.splitlines(keepends=True) + at = 1 + while at < len(lines) and lines[at].strip() == "": + at += 1 + lines.insert(at, f"\n## Live deployment\n\n{body}\n") + s = "".join(lines) +open("README.md", "w").write(s) +print("render-docs: README live-deployment section rendered") +PY +echo "render-docs: done" diff --git a/infra/terraform/cloudflare-kv/terraform/adopt.tf b/infra/terraform/cloudflare-kv/terraform/adopt.tf index 49c0f76..7c1fbba 100644 --- a/infra/terraform/cloudflare-kv/terraform/adopt.tf +++ b/infra/terraform/cloudflare-kv/terraform/adopt.tf @@ -11,7 +11,7 @@ # carries the brokered CLOUDFLARE_API_TOKEN/CLOUDFLARE_ACCOUNT_ID and the # TF_HTTP_* state credentials, so no extra secrets and no AWS access. -data "external" "adopt_idempotency_namespace" { +data "external" "adopt_app_kv" { program = ["bash", "-c", <<-EOT set -euo pipefail title="$(jq -r .title)" @@ -32,12 +32,12 @@ data "external" "adopt_idempotency_namespace" { EOT ] query = { - title = local.idempotency_namespace_title + title = local.app_kv_title } } import { - for_each = toset(compact([data.external.adopt_idempotency_namespace.result.id])) + for_each = toset(compact([data.external.adopt_app_kv.result.id])) to = cloudflare_workers_kv_namespace.app_kv id = "${var.cloudflare_account_id}/${each.value}" } diff --git a/infra/terraform/cloudflare-kv/terraform/main.tf b/infra/terraform/cloudflare-kv/terraform/main.tf index 205f53a..31cd0da 100644 --- a/infra/terraform/cloudflare-kv/terraform/main.tf +++ b/infra/terraform/cloudflare-kv/terraform/main.tf @@ -88,26 +88,26 @@ variable "terraformVersion" { default = "1.15.3" } -# --- KV namespace for api-edge idempotency replay store --- +# --- The KV namespace the cron runs record into --- # -# Backs the app's key-value needs (session, cache, counters). Keys are -# scoped by the app and entries TTL'd via the -# Worker (`expirationTtl`); no Terraform-side TTL knob exists -# for KV namespaces themselves — TTL is per-PUT, owned by the Worker. +# Bound by apps/web as KV. Keys are the seven intervals (`1m` … `1mo`), each +# holding its schedule's last run; any expiry is per-PUT (`expirationTtl`), +# owned by the Worker — no Terraform-side TTL knob exists for KV namespaces +# themselves. locals { - # Brand-namespaced with var.repo so the title is unique to this fork. Cloudflare - # KV namespace titles must be unique per account, and this fork shares an account - # with the baseline (which uses the un-branded title) — without the brand the - # create fails with "a namespace with this account ID and title already exists" - # (10014). Workers resolve this KV by ID via the wiring secret, so the title is + # Built on var.repo (the product's repository slug) so the title is unique per + # product. Cloudflare KV namespace titles must be unique per account, and two + # products may share an account — without the slug the second create fails + # with "a namespace with this account ID and title already exists" (10014). + # The Worker binds this namespace by ID via the wiring secret, so the title is # free to change. - idempotency_namespace_title = "${var.namespacePrefix}${var.repo}-app-kv-${var.environment}" + app_kv_title = "${var.namespacePrefix}${var.repo}-app-kv-${var.environment}" } resource "cloudflare_workers_kv_namespace" "app_kv" { account_id = var.cloudflare_account_id - title = local.idempotency_namespace_title + title = local.app_kv_title } # --- Wiring manifest (BF5, via orun secrets) --- @@ -127,7 +127,7 @@ output "wiring" { # --- Outputs (non-secret) --- output "app_kv_id" { - description = "Cloudflare Workers KV namespace ID for api-edge idempotency replay store" + description = "Cloudflare Workers KV namespace ID the cron runs record into" value = cloudflare_workers_kv_namespace.app_kv.id } diff --git a/intent.yaml b/intent.yaml index 1f76a3b..19aa18b 100644 --- a/intent.yaml +++ b/intent.yaml @@ -3,7 +3,7 @@ kind: Intent metadata: name: cron-starter - description: Vercel's Cron Jobs example (seven schedules writing last-run times to KV, a page that polls them) on Cloudflare Workers + Static Assets with Cron Triggers and Workers KV, on the Cirrus baseline conventions + description: Seven cron schedules and the page that shows their last runs — Next.js on Cloudflare Workers + Static Assets, Cron Triggers on the same Worker, the runs in a Workers KV namespace provisioned by Terraform namespace: sourceplane execution: @@ -14,8 +14,9 @@ execution: # enforce claim ⊆ authorized. Declaring it implies strict mode — a # non-interactive run that resolves no workspace fails fast. # - # Replace with this product's own Orun workspace (`orun cloud link`), and - # set the `ORUN_CI` repository variable to `true` to turn `ci.yml` on. + # `ws_CHANGE_ME` is the one value `ci.yml` treats as "not linked yet" and + # plans nothing for. A bootstrap writes the product's workspace here; by + # hand, set it to yours (`orun cloud link`) and the Orun pipeline runs. workspace: ws_CHANGE_ME requireOrg: true # Push the resolved catalog after a successful plan on the default branch, @@ -35,9 +36,19 @@ compositions: # explicit version: a bare repository reference resolves to `:latest`, # which would let a catalog release change this repo's execution contracts # without a commit here. Bumping the tag is the deliberate upgrade step. + # + # 0.19.0, NOT 0.20.0 (cirrus-baseline's pin). 0.20.0 makes the workspace + # install lane-scoped: it runs once in the source checkout and every job's + # staged tree LINKS its top-level node_modules there — out of the tree. Next + # 16 builds with Turbopack, which refuses a dependency that resolves outside + # its root ("Symlink apps/web/node_modules/next is invalid, it points out of + # the filesystem root"). Under 0.19.0 the job installs inside its own tree, + # and the app has one job per lane (`lane: isolated`), so the shared install + # would save nothing anyway. 0.19.0 is also the floor: it retries a first + # deploy through Cloudflare's 10007 race and runs the smoke under backoff. - name: stack-tectonic kind: oci - ref: oci://ghcr.io/sourceplane/stack-tectonic:0.18.2 + ref: oci://ghcr.io/sourceplane/stack-tectonic:0.19.0 resolution: precedence: - stack-tectonic @@ -56,6 +67,11 @@ discovery: # Where the work lives (initiative-lifecycle): an epic is a directory with an # epic.yaml under `epics`, a task a contract under `tasks`; the `orun plan` on # main reconciles the tree into the workspace's work plane after a merge. +# +# THIS BLOCK IS THE BASELINE'S OWN. A product built from this baseline has no +# epics or task contracts of its own (its bootstrap work lives on the +# platform), so the bootstrap removes the block, and this comment with it, +# from the product's copy. work: epics: specs/epics tasks: tasks @@ -162,5 +178,5 @@ repo: docs: overview: README.md pages: - - { path: specs/epics/cron-starter/README.md, role: reference, title: The epic } - - { path: specs/epics/cron-starter/design.md, role: architecture, title: Design } + - { path: ai/context/operations.md, role: runbook, title: Operating contract } + - { path: ai/context/deployment.md, role: reference, title: Live deployment manifest } diff --git a/packages/.gitkeep b/packages/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml new file mode 100644 index 0000000..1217275 --- /dev/null +++ b/repo-blueprint.yaml @@ -0,0 +1,670 @@ +apiVersion: orun.dev/v1 +kind: Blueprint +metadata: + name: cron-starter + description: >- + The cron-starter as a Blueprint of itself — instantiate a new + scheduled-jobs repository (Next.js on Cloudflare Workers + Static Assets, + one Cron Trigger on the same Worker dispatching seven schedules that record + their runs in a Workers KV namespace Terraform provisions per environment, + and the page that shows them) and take it from nothing to live on stage and prod: ONE landing that + places, brands and merges the whole product, one convergence that applies + the namespace before the Worker that binds it, then a hook-only phase that + records what went live. Run one at a time with + `--phase ` or the whole sequence with `--resume`; see + docs/phases/README.md for the contract every phase follows, and + BOOTSTRAP.md for the operator checklist no script can perform. + +# ── INPUTS ──────────────────────────────────────────────────────────────── +# The instance-identity contract, consumed by tooling/rebrand/rebrand.mjs via +# the `.rebrand/values.json` the `rebrand-values` module templates. Every +# input a later phase needs is in that file, because it is committed and so +# survives a fresh container; `.orun/provenance.lock` does not. +# +# The card (blueprint.yaml) declares a subset of these with the patterns the +# console validates; testing/manifest.test.sh fails if a card input is not +# one of these, or if one of these is required and nothing supplies it. +inputs: + reponame: + type: string + pattern: "^[a-z][a-z0-9-]*$" + required: true + description: Repo slug (e.g. acme-crons) — intent metadata.name, the Worker name prefix, the KV namespace titles, the secret project. + productname: + type: string + required: true + description: The site's display name (e.g. "Acme Crons") — the page heading and its title. + productdomain: + type: string + required: true + description: >- + The domain the site will answer on (e.g. acme.dev) — BASE_DOMAIN and the + custom-domain guidance. It does not need to exist: the site answers on + workers.dev from its first deploy. + githuborg: + type: string + pattern: "^[A-Za-z0-9][A-Za-z0-9-]*$" + required: true + description: >- + GitHub owner the site's repository is created under — and the owner in + the source link the page carries. 01-product waits for the App + installation on THIS owner before it creates anything: the platform + learns of a pull request only through the installation on the account + that owns the repository. + subdomain: + type: string + default: "your-workers-subdomain" + description: The workers.dev subdomain of the Cloudflare account the site deploys into — its URLs and the probes. + repoPrivate: + type: boolean + default: true + description: >- + Whether the repository is created private. Private is the safe default; + `orun.repo/ensure@v1` only sets it at creation — an existing repository + keeps the visibility it has. + orunWorkspace: + type: string + default: "" + # Unset, it is the workspace the build runs in (ORUN_WORKSPACE — which a + # console build's sandbox always sets, and which the console form cannot + # send). A value set on the command line or recorded by the tree wins. + from: workspace + description: >- + Orun Cloud workspace (ws_…) for the site's remote state and secrets. + Unset, it is the workspace the build runs in; with none anywhere, + 01-product writes a placeholder that fails loudly rather than silently + claiming another tenant's workspace. + epicSlug: + type: string + pattern: "^[a-z][a-z0-9-]*$" + default: cron-baselining + description: >- + The epic this bootstrap tracks itself under. Found by slug, so a run + that starts fresh and a run that resumes find the same work. + +# ── SOURCES ─────────────────────────────────────────────────────────────── +# The baseline is this repository itself. Run `orun new` from its root so +# `path: .` resolves to it; orun pins it by digest into its object store +# before any module reads it, so an instance is reproducible and provenanced. +sources: + - name: baseline + kind: dir + path: . + +# Derived build output, local secrets, and the factory's own lanes — never +# carried into an instance. +# +# WHAT `ignore` ACTUALLY EXCLUDES: orun matches an entry two ways, and which +# one depends on the entry. A pattern with no glob metacharacter is compared +# against each path SEGMENT; only a pattern containing one is compared against +# the whole relative path. So `apps/web/.env.local` on its own would match +# nothing — it needs the `**/`. testing/coverage.test.sh refuses an entry that +# names a path without a glob. +ignore: + - dist + - coverage + - .turbo + - .next + - .open-next + - .wrangler + - .terraform + - node_modules + - .orun + - plan.json + - "**/*.tsbuildinfo" + - "**/next-env.d.ts" + - "**/*.tfstate" + - "**/*.tfstate.backup" + - "**/.terraform.lock.hcl" + # `orun new` snapshots the WORKING TREE, not the git index: an operator's + # local environment files would otherwise be copied into somebody else's + # repository. `.env.example` is not among them, and ships. + - "**/.env" + - "**/.env.local" + - "**/.env.*.local" + - "**/.dev.vars" + - "**/.dev.vars.*" + # THE FACTORY'S OWN LANES. `github-workflows` copies the whole of `.github`, + # so without these two entries every site built from this baseline would + # carry them — `baseline.yml` runs `testing/*.sh`, which no module places, + # and `tag.yml` cuts baseline tags a site does not have. + # testing/coverage.test.sh fails if a lane reading `testing/` is not here. + - "**/.github/workflows/baseline.yml" + - "**/.github/workflows/tag.yml" + +# ── MODULES ─────────────────────────────────────────────────────────────── +# One module per component or root file. Root files are single-file modules +# rather than one module with an include list: a file shipping to a product +# is a line in a diff, and nothing of the factory (specs/, tasks/, testing/, +# hooks/, docs/phases/, tooling/rebrand/, tooling/bootstrap/, the blueprints, +# BOOTSTRAP.md) can ship by accident. testing/leak.test.sh holds that line. +modules: + # ── the identity file every later phase reads back ─────────────────────── + # The only place blueprint inputs touch the tree; everything else is a + # verbatim copy the `rebrand` hook rewrites. Committed, so a phase run months + # later from a fresh container recovers what the operator answered. + - name: rebrand-values + mode: template + files: + ".rebrand/values.json": | + { + "reponame": "{{ .reponame }}", + "productname": "{{ .productname }}", + "productdomain": "{{ .productdomain }}", + "subdomain": "{{ .subdomain }}", + "orunWorkspace": "{{ .orunWorkspace }}", + "githuborg": "{{ .githuborg }}", + "epicSlug": "{{ .epicSlug }}" + } + + # ── root files ─────────────────────────────────────────────────────────── + - name: root-intent + mode: copy + source: baseline + from: intent.yaml + to: intent.yaml + - name: root-package-json + mode: copy + source: baseline + from: package.json + to: package.json + - name: root-pnpm-workspace + mode: copy + source: baseline + from: pnpm-workspace.yaml + to: pnpm-workspace.yaml + # The baseline's complete lockfile: the whole tree lands at once, so the + # `pnpm-lockfile` hook only confirms it. + - name: root-pnpm-lock + mode: copy + source: baseline + from: pnpm-lock.yaml + to: pnpm-lock.yaml + - name: root-turbo + mode: copy + source: baseline + from: turbo.json + to: turbo.json + - name: root-kiox + mode: copy + source: baseline + from: kiox.yaml + to: kiox.yaml + - name: root-kiox-lock + mode: copy + source: baseline + from: kiox.lock + to: kiox.lock + - name: root-gitignore + mode: copy + source: baseline + from: .gitignore + to: .gitignore + # The SITE's README, not this repository's: this one is about the baseline + # (how to instantiate it, how it is tested), and a site's owner has no use + # for any of that. + - name: root-readme + mode: copy + source: baseline + from: .baseline/product/README.md + to: README.md + - name: github-workflows + mode: copy + source: baseline + from: .github + to: .github + - name: vscode + mode: copy + source: baseline + from: .vscode + to: .vscode + + # The two context pages a site genuinely owns: its operating contract, and + # the deployment manifest 02-docs renders. One module per file, so a new + # file in ai/context/ cannot ship without somebody writing a module for it. + - name: ai-operations + mode: copy + source: baseline + from: ai/context/operations.md + to: ai/context/operations.md + - name: ai-deployment + mode: copy + source: baseline + from: ai/context/deployment.md + to: ai/context/deployment.md + + # ── the discovery roots, declared ──────────────────────────────────────── + # orun's repo-scale gate — and later `orun plan` in the site's own CI — + # discovers apps/, infra/, packages/ and tests/, and a missing root is a + # hard failure. `packages/` has no component in this product, so it exists + # only through this file. A file the tree needs in order to be valid is + # what a module is for. + - name: discovery-roots + mode: template + files: + "apps/.gitkeep": "" + "infra/.gitkeep": "" + "packages/.gitkeep": "" + "tests/.gitkeep": "" + + # ── shared tooling ─────────────────────────────────────────────────────── + # Only what a SITE runs: the TypeScript and ESLint configuration and the + # wrangler renderer its build calls. The factory's tooling (rebrand, + # bootstrap) stays here. + - name: tooling-tsconfig + mode: copy + source: baseline + from: tooling/tsconfig + to: tooling/tsconfig + - name: tooling-eslint + mode: copy + source: baseline + from: tooling/eslint + to: tooling/eslint + - name: tooling-wire + mode: copy + source: baseline + from: tooling/wire + to: tooling/wire + + # ── the data plane ─────────────────────────────────────────────────────── + # INFRA BEFORE APP, twice over: placed before the app that binds it (this + # DAG), and applied before it on every merge to main (apps/web's enforced + # `dependsOn: cloudflare-kv` in the convergence's plan). + - name: cloudflare-kv + mode: copy + source: baseline + from: infra/terraform/cloudflare-kv + to: infra/terraform/cloudflare-kv + + # ── the site ───────────────────────────────────────────────────────────── + - name: web + mode: copy + source: baseline + from: apps/web + to: apps/web + dependsOn: [cloudflare-kv, tooling-eslint, tooling-tsconfig, tooling-wire] + - name: web-tests + mode: copy + source: baseline + from: tests/web + to: tests/web + dependsOn: [web, tooling-eslint, tooling-tsconfig] + +# ── THE WORK, UP FRONT ──────────────────────────────────────────────────── +# The bootstrap is work, so it lives where work lives — and all of it is on +# the plane before the first phase places a file: one epic, one milestone per +# phase in the order the phases run, one task per landing. +# +# `hooks.preInstantiate` (orun >= v2.60) runs under no phase, once per run, on +# a resume too. Everything here is find-or-create BY IDENTITY — the epic by +# slug, a milestone by name within its epic, a task by title within its epic — +# so a second run, a resume and a redo all find what the first run made. The +# milestones are created IN ORDER and BEFORE the tasks: the plane appends each +# new milestone after the last, and a task naming a milestone the epic does +# not have yet would create it out of order. +# +# Each phase's own `pre` hook runs `orun.task/ensure@v1` on its task again. +# Same identity, so it finds rather than creates, and it is how the phase gets +# the task's KEY for its landing. The MILESTONE keeps the phase's name: it is +# the identity the engine's phase events, the plane's evidence and the +# console's rows all meet on, and the card's `programme.milestones` names the +# same list. +hooks: + preInstantiate: + - id: epic + uses: orun.task/ensure@v1 + with: + kind: epic + slug: "{{ .inputs.epicSlug }}" + name: "Cron baselining — {{ .inputs.productname }}" + description: >- + Everything the cron-starter baseline builds for + {{ .inputs.productname }} in {{ .inputs.githuborg }}/{{ .inputs.reponame }}: + the repository, its CI, its KV namespaces and the Worker with its + Cron Trigger live on stage and prod in one landing, then the record + of what went live. One + milestone per phase, in the order the phases run; one task per + landing, each bound to the pull request that lands it. + owner: me + - id: m01 + uses: orun.task/ensure@v1 + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 01-product + exitCriteria: + - repository created under {{ .inputs.githuborg }}, linked to the workspace, the product merged as one pull request + - the KV namespaces applied and their wiring published on stage and prod + - the Worker built and deployed on stage and prod, its Cron Trigger recording runs the page reads + - id: m02 + uses: orun.task/ensure@v1 + with: + kind: milestone + epic: "{{ .inputs.epicSlug }}" + name: 02-docs + exitCriteria: + - ai/context/deployment.md on main matches the probed live URLs + - prod waits on stage again + - id: t01 + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 01-product + name: "Build the product in one landing" + brief: >- + Create {{ .inputs.githuborg }}/{{ .inputs.reponame }} and land the + whole product as its first pull request — intent, CI, tooling, the + KV root, the Worker with its page, API routes and Cron Trigger, and + its tests, branded as {{ .inputs.productname }} — then see one + convergence apply the namespaces and deploy the Worker to stage and + prod, smoke-tested over HTTP on a run its every-minute trigger + recorded. + prefix: BASE + contract: .baseline/tasks/01-product.TaskContract.yaml + - id: t02 + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: 02-docs + name: "Record the live deployment" + brief: >- + Probe every live URL one last time and write the deployment record + into the repository from what actually answered, not from what the + blueprint intended. + prefix: BASE + contract: .baseline/tasks/02-docs.TaskContract.yaml + +# ── PHASES ──────────────────────────────────────────────────────────────── +# A phase is orun's own barrier over the module DAG and the whole of what a +# phase DOES: what it is for a person (`title`), what to budget +# (`expectedMinutes`), what must already be true (`requires`), and the hooks +# that do its work around placement — `pre` before, `post` after, `await` for +# what is still converging when the hooks are done. +# +# THE ORDER HERE IS THE EXECUTION ORDER, and the numbered names are the names +# the task plane's milestones carry. A dependency may never point forward +# across a phase boundary; orun refuses the blueprint if one does. +# +# TWO PHASES. `01-product` places, brands and lands EVERYTHING as one pull +# request, and the convergence that merge triggers deploys it in dependency +# order — the KV namespace before the Worker that binds it, because apps/web +# depends on cloudflare-kv with `mode: enforced` on a push to main. Nothing +# about that order needs a landing of its own; the plan carries it. +# `02-docs` places NO modules: it is hooks only, a separately landable unit +# with its own task and its own PR. +phases: + - name: 01-product + title: The product, built in one landing + description: The whole tree — manifests, CI, tooling, the KV root, the Worker with its page, API routes and Cron Trigger, and its tests — branded, landed as one pull request, and deployed by one convergence. + # An estimate until a bootstrap measures it: the pull request's Checks (a + # full Next.js build), the merge, the KV apply, then the Worker's build, + # deploy and smoke on stage and prod side by side — the smoke waiting up + # to a minute or two for the every-minute trigger's first run. + expectedMinutes: 13 + narrate: + start: "Creating the repository and landing the whole product in one pull request — intent, CI, tooling, the KV namespace and the Worker with its page, routes, Cron Trigger and tests. Then one convergence applies the namespace and deploys the Worker on stage and prod. Usually about {{ .meta.expectedMinutes }} minutes." + await: "One convergence is deploying the product: the KV namespace first, then the Worker built with its id, on stage and prod side by side, each smoke waiting for the every-minute trigger to record a run. The Next.js build is the long pole; nothing is stuck." + done: "{{ .inputs.reponame }} is live on stage and prod — {{ .meta.files }} files on main, branded as {{ .inputs.productname }}, its Cron Trigger recording runs. That took {{ .meta.elapsed }}." + failed: "The product did not come up. The failing lane above names the component — the KV apply, or the Worker's build, deploy or smoke — and a provider error is in its log; whatever deployed is still there." + modules: [ai-deployment, ai-operations, cloudflare-kv, discovery-roots, github-workflows, rebrand-values, root-gitignore, root-intent, root-kiox, root-kiox-lock, root-package-json, root-pnpm-lock, root-pnpm-workspace, root-readme, root-turbo, tooling-eslint, tooling-tsconfig, tooling-wire, vscode, web, web-tests] + # THE PLATFORM MUST BE ABLE TO SEE THE REPOSITORY BEFORE IT EXISTS. Every + # phase lands a pull request that files under its task, and the platform + # learns of a PR only through the GitHub App installation on the account + # that OWNS the repository. So the owner's connection is asked for here, + # before a repository is created, and waited for like any other consent. + # And the Cloudflare connection, which every deploy credential below is + # minted from — asked for here too, since this phase is the one that + # deploys. + requires: + probe: + - id: providers + uses: orun.doctor/check@v1 + with: + providers: [github, cloudflare] + githubOwner: "{{ .inputs.githuborg }}" + waitSeconds: 600 + pollSeconds: 20 + hooks: + pre: + # The epic, the milestones and the tasks already exist (the run-level + # list above). This finds the task and yields its key, which the + # landing binds the pull request to. + - id: task + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: "{{ .phase.name }}" + name: "Build the product in one landing" + prefix: BASE + contract: .baseline/tasks/01-product.TaskContract.yaml + # The whole tree is placed when these run. rebrand.mjs enumerates it + # with `git ls-files`, so the output has to be a git repository with a + # populated index BEFORE it runs. `git add -A` only stages; the landing + # commits. + post: + # A RE-RUN MUST HAVE SOMETHING TO LAND. A convergence can fail AFTER + # its PR merged, and the merge has already put every file this phase + # places on main; orun derives phase state from the tree, so a forced + # re-run lands an EMPTY diff while the site's CI plans `--changed`. So + # the phase rewrites ONE trailing marker line in each component.yaml + # its contract names — `# orun: redeploy ` — and the + # landing has a diff that re-plans exactly those components. The + # marker is a deploy trigger, not state: nothing reads it back. + - id: retouch + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/retouch.mjs", "--phase", "{{ .phase.name }}", "--affects", "{{ .baseline.dir }}/.baseline/tasks/01-product.TaskContract.yaml"] + - id: git-init + run: ["git", "init", "-q"] + - id: stage + run: ["git", "add", "-A"] + - id: rebrand + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--values", ".rebrand/values.json", "--allow-dirty"] + # Re-tenant the site. rebrand.mjs treats the orun state backend as + # org-owned and leaves it alone, so intent.yaml would keep THIS + # repository's `workspace:` — the site's CI would then claim another + # tenant's workspace on every remote op. Hook argv is not templated, + # so the value travels through .rebrand/values.json, which IS. + - id: orun-workspace + run: + - node + - -e + - | + const fs = require("fs"); + const values = JSON.parse(fs.readFileSync(".rebrand/values.json", "utf8")); + const ws = String(values.orunWorkspace || "").trim() || "ws_SET_ME"; + const before = fs.readFileSync("intent.yaml", "utf8"); + // Look for the line rather than for a change: a site built into + // a workspace already named there rewrites the line to the value + // it already has, and "unchanged" is not "missing". + const line = /^(\s*workspace:\s*).*$/m; + if (!line.test(before)) { + console.error("orun-workspace: no `workspace:` line in intent.yaml — refusing to guess"); + process.exit(1); + } + fs.writeFileSync("intent.yaml", before.replace(line, "$1" + ws)); + console.log( + ws === "ws_SET_ME" + ? "orun-workspace: wrote placeholder ws_SET_ME — set your Orun Cloud workspace before enabling remote state" + : "orun-workspace: intent.yaml workspace -> " + ws, + ); + # The site carries no work tree of this repository's: `specs/` and + # `tasks/` never ship, so intent.yaml's `work:` block would point its + # every plan at two directories that do not exist. + - id: work-tree + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/work-tree.mjs", "--strip"] + # STAGE AND PROD DEPLOY SIDE BY SIDE UNTIL THE BOOTSTRAP IS DONE. The + # promotion gate makes prod wait out stage's deploy; during a + # bootstrap both are empty and the landing is watched to green, so it + # protects nothing and doubles the convergence. Deferred here, + # restored by 02-docs. tooling/bootstrap/promotion.mjs. + - id: promotion + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/promotion.mjs", "--defer"] + # DEV'S VERIFY LANES STAY OFF MAIN UNTIL THE BOOTSTRAP IS DONE, by the + # same mechanism: a third Next.js build on the merge proves nothing + # the baseline's own CI did not. Pull requests keep their dev lanes. + # tooling/bootstrap/dev-lanes.mjs. + - id: dev-lanes + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/dev-lanes.mjs", "--defer"] + # Re-stage so `git ls-files` and `rebrand --verify` see the rewritten tree. + - id: restage + run: ["git", "add", "-A"] + - id: rebrand-verify + run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] + # root-pnpm-lock places the baseline's complete lockfile and the whole + # tree is here, so this only confirms it; the lanes and Checks install + # with --frozen-lockfile. The lockfile carries no identity. + - id: pnpm-lockfile + run: ["pnpm", "install", "--lockfile-only"] + # The repo has to exist before there is anywhere to land. + - id: repo + uses: orun.repo/ensure@v1 + narrate: "The repository exists at {{ .inputs.githuborg }}/{{ .inputs.reponame }}." + with: + owner: "{{ .inputs.githuborg }}" + name: "{{ .inputs.reponame }}" + private: "{{ .inputs.repoPrivate }}" + # THE REPOSITORY MUST BE THE WORKSPACE'S before anything lands in it, + # or the site's own CI cannot reach the platform: every convergence + # lane authenticates over GitHub OIDC, resolved through the repo link. + # `link` may be refused where the credential cannot write links (a + # workspace key) and the platform has linked the repository already, + # so it is best effort and `check` is the gate — an unlinked + # repository stops here, naming the fix, instead of in every lane. + - id: link + run: + - bash + - -c + - | + orun cloud link --org "$1" || true + orun cloud check --org "$1" || { + echo "$2 is not linked to workspace $1 — its CI cannot authenticate. Link it (orun cloud link --org $1, or the console's Git Repos) and re-run this phase." >&2 + exit 1 + } + - link + - "{{ .inputs.orunWorkspace }}" + - "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" + # The deploy credentials, brokered, one hook per template: + # `integrations/reconcile` mints from ONE connection with ONE scope + # template. `workers-deploy` covers both halves of this product — + # Workers Scripts for the page's deploy and KV Storage for the + # namespace's apply — so one token serves the KV root and the deploy + # lane alike; the account id is a connection fact both bind. Keys that + # already exist are kept. After the link, before the landing whose + # convergence uses them. + - id: secret-workers-deploy + uses: orun.integrations/reconcile@v1 + with: + provider: cloudflare + keys: [CLOUDFLARE_API_TOKEN] + template: workers-deploy + - id: secret-account-id + uses: orun.integrations/reconcile@v1 + with: + provider: cloudflare + keys: [CLOUDFLARE_ACCOUNT_ID] + template: account-id + # THE PRODUCT IS A PULL REQUEST THAT IS CHECKED, THEN MERGED. This + # landing waits for its PR's whole CI run (orun >= v2.58.6): Checks + # (install, the fixture render, typecheck, lint, test, build) and + # `plan` — on a bootstrap branch (`orun/BASE-…`) the lanes are skipped + # (ci.yml), because the merge runs every one of them on main a minute + # later, for real, and that convergence is what `await` watches. + - id: land + uses: orun.pr/land@v1 + narrate: "The product is merged into main." + with: + task: "{{ .phase.hooks.task.outputs.key }}" + epic: "{{ .inputs.epicSlug }}" + branchSlug: "{{ .phase.name }}" + title: "feat: {{ .inputs.productname }}, the whole product from the cron-starter baseline" + await: + - id: converge + uses: orun.run/watch@v1 + narrate: "The KV namespace applied, the Worker built with its id and deployed, its every-minute trigger recorded a run the smoke read back, and the convergence run came back green." + with: + # The run for the commit THIS landing merged — the branch's newest + # run, read the moment the merge returns, may be another push's. + # Only ci.yml runs on a push to main, so it is that workflow's run. + sha: "{{ .phase.hooks.land.outputs.mergeSha }}" + repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" + resumeBudget: 3 + waitSeconds: 1800 + # The KV root's apply lease-publishes its wiring document to the + # project's ENVIRONMENT rungs (stage and prod), not to the workspace; + # every later deploy of the Worker reads it back. Asked of the platform + # directly, because a green convergence says the lanes passed, not + # that the document a FUTURE deploy needs is where it will look. + - id: wiring + uses: orun.secrets/exists@v1 + narrate: "The KV wiring the Worker's deploys read is published on stage and prod." + with: + keys: [WIRING_CLOUDFLARE_KV] + project: "{{ .inputs.reponame }}" + environments: [stage, prod] + - id: verify + uses: orun.http/probe@v1 + narrate: "The page answered on stage and prod." + with: + urls: + - "https://{{ .inputs.reponame }}-web-stage.{{ .inputs.subdomain }}.workers.dev" + - "https://{{ .inputs.reponame }}-web-prod.{{ .inputs.subdomain }}.workers.dev" + + # Places nothing. It records what 01-product built, from PROBED facts rather + # than from what the blueprint intended — which is why it runs last and why + # its verify is the probe 01-product ends on. + - name: 02-docs + title: The deployment, recorded + description: The live-deployment manifest, rendered from probed reality, and the promotion gate and dev's lanes put back. + expectedMinutes: 2 + narrate: + start: "Now recording what was actually built — probing every URL and writing the deployment manifest into the repository." + await: "Probing the live endpoints one last time." + done: "ai/context/deployment.md now records the live deployment, written from probed facts, and prod waits on stage again. {{ .meta.elapsed }}." + failed: "The deployment record did not land. The site is still live; only the write-up is missing." + modules: [] + requires: + phases: [01-product] + hooks: + pre: + - id: task + uses: orun.task/ensure@v1 + with: + kind: task + epic: "{{ .inputs.epicSlug }}" + milestone: "{{ .phase.name }}" + name: "Record the live deployment" + prefix: BASE + contract: .baseline/tasks/02-docs.TaskContract.yaml + post: + # THE SITE GOES LIVE WITH ITS PROMOTION GATE. 01-product deferred + # `prod.promotion.dependsOn: [stage]`; this, the last landing, puts it + # back, and from here on a change reaches prod only after stage. + # Restoring touches only intent.yaml's `environments` section, which + # `orun plan --changed` maps to no component, so this landing + # redeploys nothing. + - id: promotion + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/promotion.mjs", "--restore"] + # And dev verifies every merge to main again (01-product deferred it). + - id: dev-lanes + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/dev-lanes.mjs", "--restore"] + - id: render + run: ["bash", "{{ .baseline.dir }}/hooks/render-deployment-docs.sh", ".", "{{ .inputs.orunWorkspace }}", "{{ .baseline.dir }}"] + - id: land + uses: orun.pr/land@v1 + narrate: "The deployment record is merged into main." + with: + task: "{{ .phase.hooks.task.outputs.key }}" + epic: "{{ .inputs.epicSlug }}" + branchSlug: "{{ .phase.name }}" + title: "docs(deployment): record the live deployment state" + await: + - id: verify + uses: orun.http/probe@v1 + narrate: "Every live URL answered on the final probe." + with: + urls: + - "https://{{ .inputs.reponame }}-web-stage.{{ .inputs.subdomain }}.workers.dev" + - "https://{{ .inputs.reponame }}-web-prod.{{ .inputs.subdomain }}.workers.dev" diff --git a/specs/epics/README.md b/specs/epics/README.md index cd199e0..155824f 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 | |------|---------|--------|------------| -| [`cron-starter/`](./cron-starter/) | **CR** | ✅ Shipped | Vercel's Cron Jobs example, equivalent in code and function, on Cloudflare Workers with Cron Triggers driving the same API routes and Workers KV holding the timestamps | +| [`cron-starter/`](./cron-starter/) | **CR** | ✅ Shipped | Vercel's Cron Jobs example, equivalent in code and function, on Cloudflare Workers with Cron Triggers driving the same API routes and Workers KV holding the timestamps — and an Orun baseline that instantiates it in one landing (CR4) | As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`. diff --git a/specs/epics/cron-starter/IMPLEMENTATION-STATUS.md b/specs/epics/cron-starter/IMPLEMENTATION-STATUS.md index b853aef..e9d0df8 100644 --- a/specs/epics/cron-starter/IMPLEMENTATION-STATUS.md +++ b/specs/epics/cron-starter/IMPLEMENTATION-STATUS.md @@ -9,6 +9,7 @@ the code departed from `design.md` or from the upstream template. | CR1 — the crons on Workers | ✅ Shipped | [#2](https://github.com/sourceplane/cron-starter/pull/2) | | CR2 — the KV namespace from Terraform | ✅ Shipped (validated; apply gated on a linked workspace) | [#3](https://github.com/sourceplane/cron-starter/pull/3) | | CR3 — ready to instantiate | ✅ Shipped | [#4](https://github.com/sourceplane/cron-starter/pull/4) | +| CR4 — a baseline, in one landing | ✅ Shipped (offline-proven; no live bootstrap yet, risk CR-K) | this PR (CR-5), to be tagged `baseline-v1` | ## Departures from the upstream template @@ -96,7 +97,114 @@ and fixture. Upstream's `turbo.json`, `pnpm-lock.yaml`, `vercel.json`, `.gitignore` and `.env.example` are not carried; `apps/web/README.md` is upstream's, verbatim. -## Verified +### The page's name and source link come from `lib/site.ts` (CR4) + +`SITE_NAME` is the heading ("Cron Triggers on Cloudflare") and now the +`` too; `SOURCE_URL` is the layout's repository link and its "Clone & +Deploy" button. It lives in `lib/`, not beside the pages: anything under +`pages/` is a route. `pages/_app.tsx` renders the `<title>` and the +description meta itself and no longer passes the layout its `title` and +`description` props: the e2e tier found that `@vercel/examples-ui`'s own +`<Head>` (it imports `next/head.js`) does not reach the server-rendered page +— with the props passed, the served HTML carried no description meta, and +CR3's title went through that same `<Head>` — and the layout would have +suffixed the name with " - Vercel Examples". + +### `.wrangler/` is not linted (CR4) + +`wrangler dev` (which the README tells a reader to run in `apps/web`) writes +its bundles to `apps/web/.wrangler/tmp`, and `pnpm lint` then failed on +them; `eslint.config.mjs` ignores the directory with `.next` and `.open-next`. + +### The page renders per request, for an absolute Open Graph image (CR4) + +`og:image` / `twitter:image` were the relative `/thumbnail.png`, which Open +Graph does not accept. `pages/index.tsx` has a `getServerSideProps` that +reads the request's origin (`requestOrigin` in `lib/site.ts`) and nothing +else; the image is `<origin>/thumbnail.png` on workers.dev, a custom domain +or `wrangler dev`, with no configured site URL. `/` is therefore dynamic +(it was static); the cron data still loads in the browser through SWR, as +upstream. The unused `data: any` prop went with it, and so did its +`no-explicit-any` lint override and the one upstream lint warning. + +### `apps/web/README.md` is the app's, not the template's (CR4) + +Upstream's advertised "Deploy with Vercel" and Vercel KV, and it ships into +every product. + +## Departures from the port (CR4) + +| What | Before | After | Why | +|---|---|---|---| +| `apps/web/wrangler.jsonc` | git-ignored, rendered by the build | committed as the fixture render, GENERATED banner; Checks diffs it | the deploy lane checks it exists before the build (risk CR-H) | +| dev's render | `live.mjs --env dev` → no document → red | `--fixture wiring.fixture.json --fixture-envs dev`; the fixture has a `dev` entry | dev is verify-only; no root applies there (CR-I) | +| `apps/web` → `cloudflare-kv` | `dependsOn` in the default mode (a PR's web lane waited on the KV plan) | `mode: enforced`, `modeRules` advisory on `github-pull-request` | the one landing's order on main; a PR deploys nothing (cirrus-baseline v22's shape) | +| `apps/web` smoke | `grep 'Cron Triggers on Cloudflare'` on `/` | `/api/data/1m` carries a `fetchedAt` from the last ten minutes | the cron's effect, read back: the every-minute trigger ran the route through the scheduled handler and the Worker reads its namespace. The name is the owner's (risk CR-J) | +| `ci.yml` gate | `vars.ORUN_CI == 'true'` | skip only while `intent.yaml` names `ws_CHANGE_ME` | a bootstrap cannot set a repository variable | +| `checks.yml` | push to main + PRs | PRs + `workflow_dispatch` | `orun.run/watch@v1` takes the newest run on the merge sha from ANY workflow | +| Cron Triggers | seven per Worker (fourteen per product), the handler mapping the expression that fired to its interval (`intervalFor`) | ONE per Worker, `* * * * *` (`TRIGGER`); the handler runs every schedule in `lib/crons.ts` whose expression matches the trigger's `scheduledTime` (UTC), one after another, and fails the invocation naming any route that failed | Cloudflare counts Cron Triggers per account — five on Workers Free — and the platform cannot check a plan before a deploy; two triggers per product fit Free (risk CR-B, CR-N) | +| stack-tectonic | 0.18.2 | 0.19.0 | first-deploy retry and smoke backoff; not 0.20.0, whose lane-scoped install Next 16's Turbopack refuses | +| orun lane pin | v2.78.0 | v2.78.4 | cirrus-baseline's and portfolio's pin | +| `packages/` | absent — `orun plan` failed: `failed to access discovery root packages` | `packages/.gitkeep` | the discovery roots are required | +| `intent.yaml` docs pages | `specs/epics/…` | `ai/context/*` | the pages must exist in a product | +| the KV root's prose and names | Cirrus's "api-edge idempotency replay store", "this fork"; `idempotency_namespace_title`, `adopt_idempotency_namespace` | the cron runs' namespace; `app_kv_title`, `adopt_app_kv` | it ships into every product; no resource address changed | +| `tooling/wire/render.mjs` | copied the template's header comment | writes a GENERATED banner | the committed render must say it is one | +| `tasks/CR-1..4` | no `metadata` | `metadata.name` and `title` | `orun work check` (≥ v2.79) refused them | + +## Verified (CR4) + +- `orun new --status` reads the blueprint at v2.58.11 (the bootstrap floor), + v2.78.4 (the lane pin) and v2.79.0: `01-product` 72 files, `02-docs` + hook-only. `orun validate` and `orun work check` (1 epic, 5 contracts, + prefix CR) clean. +- `testing/{manifest,phases,coverage,rebrand,retouch,bootstrap-defer,wire}.test.sh` + green. +- `testing/leak.test.sh` (v2.58.11 and v2.79.0): 72 files derived; nothing + of the factory, nothing local or built, no provenance prose; 65 shipped + sources name no factory path; `worker.ts`, `lib/scheduled.ts` and + `lib/crons.ts` ship. +- `testing/placement.test.sh` (fixture "Sam's Crons & Schedules" / + `acme-inc/acme-cron-jobs`; v2.78.4 and v2.79.0): two landings; rebrand + `--verify` clean; the page, the Worker, the KV titles and every secret ref + the product's; `main: worker.ts` and the one `* * * * *` trigger kept in + the template and the committed render; no file names a factory path; + workspace re-tenanted, `work:` stripped, promotion and dev lanes restored; + record rendered. The product's own `orun plan --trigger github-push-main` + for the 01-product merge: `cloudflare-kv` apply on stage and prod at lane + level 0, `web` deploy at level 1, each waiting on its own environment's + apply alone, its smoke reading `/api/data/1m`; on a pull request `web` + waits on nothing; the 02-docs merge plans 0 jobs; `--resume` changes + nothing. Refused under v2.58.11 by design (risk CR-L). +- `testing/e2e.test.sh` (v2.79.0 and v2.78.4): the 01-product landing passes + the Checks sequence (the committed config is the fixture render); in the + job tree staged as orun stages it, the stage lane's `verify-app-structure`, + `build-app` (the live render, from a stage document in the job's + environment), `verify-build-output` and `deploy-dry-run` pass, binding `KV` + to the document's id; the built config keeps `main: worker.ts` and its one + trigger and `.open-next/worker.js` exists for it. `wrangler dev + --test-scheduled` serves the built Worker: the component's own smoke + REFUSES it before any trigger fired; `/__scheduled?cron=*+*+*+*+*` runs + `/api/cron/1m` (logged `200 "OK"` by the scheduled handler); at eight + crafted scheduled times (`/cdn-cgi/local/scheduled?…&time=`, since + `/__scheduled` always stamps the present) exactly the schedules due then + run — 1m always, 10m, 1h, 12h, 1d, 1w on a Sunday and not a Monday, 1mo + on the 1st — and every other record stays; every record reads back + through `/api/data/<interval>`; a foreign expression runs nothing; the + smoke then PASSES. `/` + carries the product's name (heading and `<title>`), its repository links, + a description, the seven schedules and an Open Graph image absolute on + the origin asked; `GET /api/cron/1h` runs that schedule on request; the + thumbnail, the favicon and a 404 are served. +- Repository checks: `pnpm install --frozen-lockfile`, `wire:fixture` (no + diff), typecheck, lint (no warnings), test (34: the matcher at crafted + times, the dispatcher, the routes, the seam), build (`/` and both API + routes dynamic; Worker + assets) green. +- `terraform validate` green on `infra/terraform/cloudflare-kv` (1.15.3). +- Not verified: a live bootstrap against a workspace — the KV apply, a real + deploy registering its trigger, the trigger firing on Cloudflare's clock, + the probes (risk CR-K). + +## Verified (CR0–CR3) - Local: `pnpm run wire:fixture`, `pnpm typecheck`, `pnpm lint` (0 errors, 1 upstream warning), `pnpm test` (16 tests: the cron table equals the diff --git a/specs/epics/cron-starter/README.md b/specs/epics/cron-starter/README.md index 051f942..b3f3933 100644 --- a/specs/epics/cron-starter/README.md +++ b/specs/epics/cron-starter/README.md @@ -8,13 +8,13 @@ The port keeps the template's pages, API routes, component, styles and `@vercel/ | Field | Value | |-------|-------| -| Status | ✅ Shipped — CR0–CR3 landed (#1–#4); KV apply and live deploy gated on a linked workspace | -| Cluster | **CR** (CR0–CR3) | +| Status | ✅ Shipped — CR0–CR3 landed (#1–#4); CR4 — a baseline, in one landing (CR-5); KV apply, live deploy and triggers on Cloudflare's clock proven only by a live bootstrap | +| Cluster | **CR** (CR0–CR4) | | Owner(s) | `apps/web` (the page, the routes, the worker entry) · `tests/web` · `infra/terraform/cloudflare-kv` | | Builds on | `cirrus-baseline` conventions: the `cloudflare-kv` root and the `@@wiring(...)@@` deploy-time render; `kv-redis-starter`'s shape for a KV-bound Next app | | Upstream | [vercel/examples `solutions/cron`](https://github.com/vercel/examples/tree/main/solutions/cron) | | Changes | What runs the routes on schedule (Vercel Cron → Cron Triggers through a custom worker entry), where they write (Vercel KV → Workers KV behind `lib/kv.ts`), analytics (beacon), the Workers build, tests, the KV root and the deploy contract; page copy says Cron Triggers and Workers KV | -| Decisions locked | (1) One Worker: the triggers sit on the Next Worker and the scheduled handler calls the OpenNext fetch handler in-process with a synthetic request — not a second Worker calling the routes over HTTP. (2) The routes stay as written: `lib/kv.ts` mirrors `kv.set`/`kv.get` (JSON values, `"OK"` from `set`). (3) `wrangler.jsonc` is rendered per environment from the wiring document; never committed. (4) The seven schedules are the template's, verbatim, in `triggers.crons` and in `lib/crons.ts`; a test holds the two together. | +| Decisions locked | (1) One Worker: the triggers sit on the Next Worker and the scheduled handler calls the OpenNext fetch handler in-process with a synthetic request — not a second Worker calling the routes over HTTP. (2) The routes stay as written: `lib/kv.ts` mirrors `kv.set`/`kv.get` (JSON values, `"OK"` from `set`). (3) `wrangler.jsonc` is rendered per environment from the wiring document — and, since CR4, committed as the fixture render, because the deploy lane checks it exists before the build (risk CR-H). (4) The seven schedules are the template's, verbatim, in `lib/crons.ts` (and, until CR4, in `triggers.crons`); a test holds the trigger and the template together. (5) CR4: one landing — the plan, not a landing boundary, orders the namespace before the Worker; the deploy's smoke reads a run the trigger recorded. (6) CR4: one Cron Trigger per Worker (`* * * * *`), the seven schedules dispatched from its scheduled time — two triggers per product, inside Workers Free's five per account. | | Gate | CR1 is the first user-visible rung. CR2 applies only with a linked workspace; it is verified by `terraform validate`. | | Shipped as | `main` after [#4](https://github.com/sourceplane/cron-starter/pull/4); verified locally under `wrangler dev --test-scheduled` with a local namespace | @@ -33,3 +33,4 @@ The port keeps the template's pages, API routes, component, styles and `@vercel/ | CR1 — the crons on Workers | `apps/web` (routes, `lib/`, `worker.ts`, the wrangler template + fixture), `tests/web` | `wrangler dev --test-scheduled` runs a trigger through the route and the page reads it back; Checks green | | CR2 — the KV namespace from Terraform | `infra/terraform/cloudflare-kv` | the root validates; the wiring keys match the template | | CR3 — ready to instantiate | README, as-built status | a reader can run, test, preview, fire a trigger and deploy it | +| CR4 — a baseline, in one landing | card, build document, rename, bootstrap tooling, tests | a new product goes from nothing to live in one landing, the KV namespace applied before the Worker, its smoke on a recorded run; Baseline CI green | diff --git a/specs/epics/cron-starter/design.md b/specs/epics/cron-starter/design.md index 51d8e6c..b25b9e0 100644 --- a/specs/epics/cron-starter/design.md +++ b/specs/epics/cron-starter/design.md @@ -20,43 +20,53 @@ Tailwind the styles. |---|---| | Next.js hosting (a static page, two API routes) | Cloudflare Workers + Static Assets; the Worker is `@opennextjs/cloudflare`'s output, the pages-router API routes run inside it | | Serverless Functions (`pages/api/*`) | The same route modules, unchanged, executed by the OpenNext handler in the Worker | -| Vercel Cron Jobs (`vercel.json` `crons`: a schedule requests a path over HTTPS) | Cron Triggers (`triggers.crons` in `wrangler.template.jsonc`) on the same Worker; a custom entry `worker.ts` re-exports the generated fetch handler and adds `scheduled`, which turns the expression that fired into a synthetic `GET /api/cron/<interval>` through that handler (`lib/scheduled.ts`, `lib/crons.ts`) | +| Vercel Cron Jobs (`vercel.json` `crons`: a schedule requests a path over HTTPS) | ONE Cron Trigger, every minute (`triggers.crons` in `wrangler.template.jsonc`), on the same Worker (since CR4; seven before); a custom entry `worker.ts` re-exports the generated fetch handler and adds `scheduled`, which turns every schedule due at the trigger's scheduled minute into a synthetic `GET /api/cron/<interval>` through that handler (`lib/scheduled.ts`, `lib/crons.ts`) | | Vercel KV (`@vercel/kv`'s `kv.set` / `kv.get`) | Workers KV namespace bound as `KV`; `lib/kv.ts` offers the same `set`/`get` over `getCloudflareContext().env.KV` with JSON values, so the routes change only their import | | `KV_URL`, `KV_REST_API_URL`, `KV_REST_API_TOKEN`, … | No env vars: the binding's id is rendered into `wrangler.jsonc` from the `cloudflare-kv` root's wiring document | | A KV store created in the dashboard | `infra/terraform/cloudflare-kv`: one namespace per environment, id and title published as the `WIRING_CLOUDFLARE_KV` secret | | `@vercel/analytics` | `components/analytics.tsx`: the Cloudflare Web Analytics beacon, rendered when `NEXT_PUBLIC_CF_BEACON_TOKEN` is set at build | | `@vercel/examples-ui` (layout, nav, text, code, link) | Kept: it is an npm package with no Vercel runtime dependency; its deploy button and repository link point at this repository | -| Deploy on push | Orun: `apps/web/component.yaml` (`cloudflare-workers-assets-turbo`) renders the config for `$ORUN_ENVIRONMENT`, builds, and deploys `cron-starter-web-{stage,prod}` on merge to `main` once the product is linked; the triggers are part of the Worker's config, so each environment's Worker carries its own seven | +| Deploy on push | Orun: `apps/web/component.yaml` (`cloudflare-workers-assets-turbo`) renders the config for `$ORUN_ENVIRONMENT`, builds, and deploys `cron-starter-web-{stage,prod}` on merge to `main` once the product is linked; the trigger is part of the Worker's config, so each environment's Worker carries its own | -The seven schedules, side by side (identical — Cron Triggers take the -same five-field expressions, in UTC, as Vercel Cron): +The seven schedules, side by side (identical five-field expressions, in +UTC, as Vercel Cron evaluates them): -| Interval | `vercel.json` `crons[].path` → `schedule` | `wrangler.template.jsonc` `triggers.crons` | `lib/crons.ts` | +| Interval | `vercel.json` `crons[].path` → `schedule` | `lib/crons.ts` | Due (UTC) | |---|---|---|---| -| 1m | `/api/cron/1m` ← `* * * * *` | `* * * * *` | `{ interval: '1m', cron: '* * * * *' }` | -| 10m | `/api/cron/10m` ← `*/10 * * * *` | `*/10 * * * *` | `{ interval: '10m', cron: '*/10 * * * *' }` | -| 1h | `/api/cron/1h` ← `0 * * * *` | `0 * * * *` | `{ interval: '1h', cron: '0 * * * *' }` | -| 12h | `/api/cron/12h` ← `0 */12 * * *` | `0 */12 * * *` | `{ interval: '12h', cron: '0 */12 * * *' }` | -| 1d | `/api/cron/1d` ← `0 0 * * *` | `0 0 * * *` | `{ interval: '1d', cron: '0 0 * * *' }` | -| 1w | `/api/cron/1w` ← `0 0 * * 0` | `0 0 * * 0` | `{ interval: '1w', cron: '0 0 * * 0' }` | -| 1mo | `/api/cron/1mo` ← `0 0 1 * *` | `0 0 1 * *` | `{ interval: '1mo', cron: '0 0 1 * *' }` | - -Vercel keyed each job by its path; Cloudflare keys each by its expression. -`lib/crons.ts` is the table that turns one back into the other, and a test -asserts it is exactly what `wrangler.template.jsonc` registers. +| 1m | `/api/cron/1m` ← `* * * * *` | `{ interval: '1m', cron: '* * * * *' }` | every minute | +| 10m | `/api/cron/10m` ← `*/10 * * * *` | `{ interval: '10m', cron: '*/10 * * * *' }` | minute % 10 = 0 | +| 1h | `/api/cron/1h` ← `0 * * * *` | `{ interval: '1h', cron: '0 * * * *' }` | minute 0 | +| 12h | `/api/cron/12h` ← `0 */12 * * *` | `{ interval: '12h', cron: '0 */12 * * *' }` | 00:00 and 12:00 | +| 1d | `/api/cron/1d` ← `0 0 * * *` | `{ interval: '1d', cron: '0 0 * * *' }` | 00:00 | +| 1w | `/api/cron/1w` ← `0 0 * * 0` | `{ interval: '1w', cron: '0 0 * * 0' }` | Sunday 00:00 | +| 1mo | `/api/cron/1mo` ← `0 0 1 * *` | `{ interval: '1mo', cron: '0 0 1 * *' }` | the 1st, 00:00 | + +Until CR4 each schedule was its own Cron Trigger (seven per Worker, and +`lib/crons.ts` turned the expression that fired back into the interval). +Cloudflare counts Cron Triggers per ACCOUNT — five on Workers Free — so +fourteen across stage and prod refused the first deploy on a Free account, +and the platform cannot see a plan before it deploys. Since CR4 the Worker +registers one trigger, `* * * * *` (`TRIGGER` in `lib/crons.ts`, the only +entry in `triggers.crons`; a test holds the two equal), and the handler +evaluates the seven expressions against the trigger's `scheduledTime`: two +triggers per product, and the schedules are the template's, verbatim, still +the ones the page shows. ## 3. The scheduled flow ``` -Cron Trigger fires on cron-starter-web-<env> with controller.cron = "*/10 * * * *" +Cron Trigger "* * * * *" fires on cron-starter-web-<env>, controller.scheduledTime = 12:10:00Z └─ worker.ts scheduled(controller, env, ctx) (lib/scheduled.ts) - ├─ intervalFor("*/10 * * * *") → "10m" (lib/crons.ts) - ├─ handler.fetch(new Request("https://cron.internal/api/cron/10m"), env, ctx) + ├─ controller.cron === TRIGGER, else warn and return + ├─ dueIntervals(scheduledTime) → ["1m", "10m"] (lib/crons.ts, UTC) + ├─ for each, in turn: + │ handler.fetch(new Request("https://cron.internal/api/cron/10m"), env, ctx) │ └─ @opennextjs/cloudflare's generated worker → Next pages API route │ pages/api/cron/[cron].ts (unchanged) │ ├─ fetch hacker-news newstories.json │ └─ kv.set("10m", { fetchedAt, id }) → env.KV.put (lib/kv.ts) - └─ 2xx → log "/api/cron/10m 200 "OK""; otherwise throw (the invocation fails) + │ 2xx → log "/api/cron/10m 200 "OK""; otherwise noted, and the rest still run + └─ any noted → throw, naming each (the invocation fails) Browser: <Post interval="10m"> polls GET /api/data/10m └─ handler.fetch (the generated worker's own fetch export) @@ -68,7 +78,9 @@ the route reads only the path (`req.url.split('/')[3]`, as upstream). The OpenNext handler runs the route inside the same `cloudflareContext` it uses for real requests, so `getCloudflareContext()` in `lib/kv.ts` sees `env.KV`. `wrangler dev --test-scheduled` exposes `GET /__scheduled?cron=<expression>` -to fire the handler locally; in production the Worker's logs show each run. +to fire the handler locally at the present minute, and +`/cdn-cgi/local/scheduled?cron=<expression>&time=<ms>` at any scheduled time; +in production the Worker's logs show each run. ## 4. The wiring flow @@ -82,7 +94,10 @@ apps/web/component.yaml secretEnv WIRING_CLOUDFLARE_KV_<ENV> ``` `wrangler.template.jsonc` carries `@@wiring(cloudflare-kv/__ENV__:app_kv_id)@@`; -the rendered `wrangler.jsonc` is git-ignored. `next dev` reaches the local +the rendered `wrangler.jsonc` is committed as the fixture render (CR4: the +deploy lane checks it exists before it builds — risk CR-H) and re-rendered +by every lane's build, `main` and `triggers.crons` included. `dev`, which no +root applies to, renders the fixture (CR-I). `next dev` reaches the local KV through `initOpenNextCloudflareForDev()` (wrangler's platform proxy), so the fixture render is enough for local work; `next dev` has no scheduler, so firing a trigger locally is `opennextjs-cloudflare preview` or @@ -95,13 +110,15 @@ apps/web the template (pages/, components/, public/) + the pages/api/cron/[cron].ts unchanged but for the kv import pages/api/data/[interval].ts unchanged but for the kv import lib/kv.ts @vercel/kv's set/get over the KV binding (JSON) - lib/crons.ts the seven schedules ↔ intervals - lib/scheduled.ts the scheduled handler factory (expression → GET /api/cron/<interval>) + lib/crons.ts the seven schedules ↔ intervals, the one TRIGGER, the UTC matcher (dueIntervals) + lib/scheduled.ts the scheduled handler factory (each schedule due → GET /api/cron/<interval>) + lib/site.ts the site's name and source link (CR4: the rename seam) + the request origin worker.ts wrangler `main`: OpenNext's fetch + scheduled components/analytics.tsx the Cloudflare Web Analytics beacon - wrangler.template.jsonc worker name, nodejs_compat, ASSETS, triggers.crons, the KV binding as a wiring token - wiring.fixture.json offline ids for the verify lane - component.yaml render for the environment, build with turbo, deploy, smoke / + wrangler.template.jsonc worker name, nodejs_compat, ASSETS, the one trigger, the KV binding as a wiring token + wiring.fixture.json offline ids for local work and the verify lanes (dev, stage, prod) + wrangler.jsonc the fixture render, committed (CR4) + component.yaml render for the environment, build with turbo, deploy, smoke /api/data/1m cloudflare-env.d.ts the bindings' types and the runtime slice the entry uses infra/terraform/cloudflare-kv the namespace per environment (Cirrus's root, generic name) tests/web vitest: the table, the scheduled handler, the kv shim, the two routes — all against mocks @@ -135,3 +152,80 @@ requesting a URL. Rejected because: The custom entry is the adapter's documented way to add a `scheduled` handler (its "custom worker" howto); wrangler bundles the generated `.open-next/worker.js` into it, and nothing about the Next build changes. + +## 8. The baseline (CR4) + +The repository instantiates new products the way +[cirrus-baseline](https://github.com/sourceplane/cirrus-baseline) does since +its one-landing bootstrap (`baseline-v22`): a console card (`blueprint.yaml`) +the platform renders, a build document (`repo-blueprint.yaml`) `orun new` +runs, and a rename engine that makes the copy somebody else's. What a small +product carries besides — the product README, the context pack, the +deployment-record hook, the bootstrap helpers and the offline test suite — +is `portfolio-starter-kit`'s `baseline-v2`, as `kv-redis-starter` (KR4) +ported it for a KV-bound Next app; this is that port with a scheduled +handler. + +| | portfolio-starter-kit (`baseline-v2`) | cirrus-baseline (`baseline-v22`) | here | +|---|---|---|---| +| phases | three: `01-scaffold`, `02-site`, `03-docs` | `01-product`, `07-domain` (optional), `08-docs` | two: `01-product`, `02-docs` | +| the order a landing used to hold | the scaffold before the site | the data plane before the fleet, the fleet before its bindings | the KV namespace before the Worker that binds it (and whose triggers write to it) | +| how the plan holds it instead | — | enforced `dependsOn` on main (advisory on a PR) | `apps/web` `dependsOn: cloudflare-kv`, `mode: enforced` with `modeRules` advisory on `github-pull-request` | +| brokered secrets | `CLOUDFLARE_API_TOKEN` (`workers-deploy`), `CLOUDFLARE_ACCOUNT_ID` | + `CLOUDFLARE_D1_TOKEN` (`d1-edit`) | the portfolio's two: `workers-deploy` covers KV Storage write and the Worker's triggers, so one token applies the namespace and deploys the Worker | +| the landing's await | watch, probe | watch, `WIRING_CLOUDFLARE_D1`/`_KV` exist on stage and prod, probe | watch, `WIRING_CLOUDFLARE_KV` exists on stage and prod, probe | +| the deploy's smoke | the page's marker text | each Worker's own health | a run the trigger recorded, read back from KV (`/api/data/1m`) | +| Cron Triggers | — | — | one per Worker (`* * * * *`), two per product — inside Workers Free's five per account; the seven schedules are dispatched from its scheduled time | +| stack-tectonic | 0.19.0 | 0.20.0 | 0.19.0 (Next 16's Turbopack) | + +**One landing.** `01-product` places every module, brands the tree, and +lands it as one pull request whose checks it waits for (Checks: install, the +fixture render, typecheck, lint, test, build). The convergence after the +merge plans `cloudflare-kv` (apply) and `web` (deploy) on stage and prod; the +web lanes are one level below the KV lanes, so each Worker deploy starts +after its environment's apply — and since a job resolves its secrets when it +starts, the `WIRING_CLOUDFLARE_KV_<ENV>` it renders from is there. Each +deploy registers its Worker's one Cron Trigger, and its smoke waits (with +backoff, ~4.5 minutes) for it to record a `1m` run (CR-J). +Stage and prod run side by side (the promotion gate is deferred until +`02-docs`), and dev's push lanes are deferred too. The landing then waits on +the convergence (`orun.run/watch@v1`, resuming failed lanes up to three +times), asks the platform that the wiring exists on both environments +(`orun.secrets/exists@v1`), and probes both URLs. `02-docs` places nothing: +it restores the two deferrals, renders the deployment record (with each +environment's last recorded run) and lands it. + +**The cron path survives the staged build.** The scheduled handler is not in +OpenNext's generated worker; it is in the committed entry `worker.ts`, which +wrangler bundles with the generated `.open-next/worker.js`, and the +schedules it dispatches are in `lib/crons.ts`, bundled with it. The trigger +is in the template the build re-renders. So nothing the build generates +carries any of them: the entry is a source file the job tree is staged +with, the re-render keeps `main` and the one `triggers.crons` entry (the +placement and e2e tiers assert both, the latter on the config the lane's own +build wrote), and the dry run bundles the entry with the generated worker. + +**Identity in the app** is `apps/web/lib/site.ts`: `SITE_NAME` (the heading +and `<title>`) and `SOURCE_URL` (the layout's repository link and its +"Clone & Deploy" button). The name is written with `JSON.stringify`, so any +name the card's pattern admits stays a valid string. The slug also names the +KV namespace titles (`stg-<slug>-app-kv-stage`) through terraform's `repo`, +so two products in one account never collide on a title. + +**No `SITE_URL`.** The only absolute link the page renders to itself is the +Open Graph image. `pages/index.tsx` renders per request and takes the +request's own origin (`getServerSideProps` → `requestOrigin`): right on +workers.dev, on a custom domain and under `wrangler dev`, with nothing to +configure. The Cron Triggers need no hostname at all: the scheduled handler +calls the fetch handler in-process. + +**Testing without the platform.** `testing/lib/bootstrap.sh` places both +phases and runs the blueprint's own `run:` hooks, read out of the document; +`testing/placement.test.sh` plans the product's own merge (the KV apply +first) and a pull request (nothing waits); `testing/wire.test.sh` holds the +wiring path together; `testing/e2e.test.sh` builds the product in the tree +orun stages, with the stage wiring document in the job's environment, +dry-deploys it, serves it with `wrangler dev --test-scheduled`, checks that +the component's own smoke refuses it before any trigger fired, fires the +trigger through the scheduled handler on the clock and at eight crafted +scheduled times — each must run exactly the schedules due then — reads every +record back and runs the smoke again. diff --git a/specs/epics/cron-starter/epic.yaml b/specs/epics/cron-starter/epic.yaml index 90272ec..5452d48 100644 --- a/specs/epics/cron-starter/epic.yaml +++ b/specs/epics/cron-starter/epic.yaml @@ -8,7 +8,7 @@ metadata: key: CR spec: title: "Vercel's Cron Jobs example on Cloudflare Workers with Cron Triggers and Workers KV" - summary: "Vercel's Cron Jobs example — seven cron schedules, each requesting /api/cron/<interval> to record the newest Hacker News story and the run time in Vercel KV, and a page that polls /api/data/<interval> for them — runs on Cloudflare Workers + Static Assets through @opennextjs/cloudflare. The seven schedules are Cron Triggers on the same Worker: a custom worker entry re-exports the generated fetch handler and adds a scheduled handler that turns the expression that fired back into the request Vercel used to make, so the template's own route runs on schedule. The timestamps live in a Workers KV namespace provisioned by Terraform through Orun and bound through the Cirrus baseline's wiring documents." + summary: "Vercel's Cron Jobs example — seven cron schedules, each requesting /api/cron/<interval> to record the newest Hacker News story and the run time in Vercel KV, and a page that polls /api/data/<interval> for them — runs on Cloudflare Workers + Static Assets through @opennextjs/cloudflare. The seven schedules run on the same Worker: a custom worker entry re-exports the generated fetch handler and adds a scheduled handler that turns each schedule due at a Cron Trigger's scheduled time back into the request Vercel used to make, so the template's own route runs on schedule — since CR4 from one every-minute trigger per Worker, which keeps a product inside Workers Free's Cron Trigger limit. The timestamps live in a Workers KV namespace provisioned by Terraform through Orun and bound through the Cirrus baseline's wiring documents." state: completed milestones: - name: "CR0 — the spec" @@ -32,3 +32,12 @@ spec: - "the README says how to run, test, preview and deploy it, lists the schedules, and says how to watch a trigger fire" - "the as-built status records every departure from the upstream template" tasks: [CR-4] + - name: "CR4 — a baseline, in one landing" + exitCriteria: + - "blueprint.yaml (the console card) and repo-blueprint.yaml (the build) take a new product from nothing to live on stage and prod in ONE landing (01-product) and a hook-only record (02-docs)" + - "the product's own push-to-main plan applies cloudflare-kv before it deploys web, and the landing's await finds WIRING_CLOUDFLARE_KV on stage and prod" + - "the Worker registers ONE Cron Trigger (every minute) and dispatches the seven schedules from its scheduled time, so a product fits the Workers Free plan" + - "the deploy's smoke reads a run the trigger recorded; the end-to-end tier fires the scheduled handler in the built Worker at times that make each schedule due and reads every record back" + - "a product built from it carries the product only, renamed throughout to its own name, repository, Worker and namespace titles" + - "Baseline CI is green: contract tests, the blueprint read by the pinned orun, the leak gate, the offline bootstrap and the end-to-end tier" + tasks: [CR-5] diff --git a/specs/epics/cron-starter/implementation-plan.md b/specs/epics/cron-starter/implementation-plan.md index 07b2250..9aa25d5 100644 --- a/specs/epics/cron-starter/implementation-plan.md +++ b/specs/epics/cron-starter/implementation-plan.md @@ -9,7 +9,7 @@ This doc set, `epic.yaml` and the task contracts, merged to `main`. **Done when** - the five documents and `epic.yaml` are on `main` -- `tasks/CR-1..CR-4.TaskContract.yaml` exist +- `tasks/CR-1..CR-4.TaskContract.yaml` exist (CR-5 joined with CR4) ## CR1 — the crons on Workers ✅ @@ -39,9 +39,46 @@ README (run, test, preview, fire a trigger, deploy; the schedules table), - the README quick start works from a fresh clone - the status file lists every PR and departure +## CR4 — a baseline, in one landing ✅ + +`blueprint.yaml`, `repo-blueprint.yaml` (two phases: `01-product`, +`02-docs`), `.baseline/` (identity, task contracts, the product's README), +`tooling/rebrand`, `tooling/bootstrap`, `hooks/render-deployment-docs.sh`, +`ai/context/`, `docs/phases/`, `BOOTSTRAP.md`, `testing/`, `baseline.yml` +and `tag.yml` (design §8); and what the product needed to deploy from a +fresh repository: `wrangler.jsonc` committed, dev rendering the fixture, +`apps/web`'s enforced `dependsOn: cloudflare-kv` on main, `packages/`, a +smoke on a recorded run, ONE Cron Trigger per Worker with the seven +schedules dispatched from its scheduled time (inside Workers Free), the +`lib/site.ts` seam and an absolute Open Graph image from the request. + +**Done when** +- orun at the bootstrap floor (v2.58.11), the lane pin (v2.78.4) and the + current CLI (v2.79.0) reads `repo-blueprint.yaml`, and + `testing/manifest.test.sh` holds the card to it +- the product's own push-to-main plan applies `cloudflare-kv` before it + deploys `web` on stage and prod (`testing/placement.test.sh`) +- `Baseline CI` is green: the contract tests, the wiring path, the leak gate, + the offline bootstrap and the end-to-end tier — which fires the trigger + through the scheduled handler in the built Worker at times that make each + schedule due and reads each record back +- the status file records what is proven offline and what only a live + bootstrap can prove + +## After CR4 (outside this repository) + +1. Cut `baseline-v1` with `tag.yml` from the merged `main`. +2. Register the row in orun-cloud's `infra/baselines-registry/baselines.yaml` + (unlisted) with the card vendored at the tag. +3. Bootstrap one product from the tag against a workspace; record its + timings and how long the first trigger took to fire; then flip the row to + public with a page on orunbase.com. + ## Sequencing note CR1's component already names the root's wiring secret; CR2 makes the name true. Applying CR2 needs a workspace with a Cloudflare connection; until -then the Orun lane is gated and `Checks` is the merge gate. The triggers -register on the first real deploy — nothing fires until then. +then the Orun lane plans nothing (`ws_CHANGE_ME`) and `Checks` is the merge +gate. The trigger registers on the first real deploy — nothing fires until +then. CR4 packages CR1–CR2 as a baseline whose one landing applies CR2's +root before it deploys CR1's Worker. diff --git a/specs/epics/cron-starter/risks-and-open-questions.md b/specs/epics/cron-starter/risks-and-open-questions.md index 1802d54..0d94e99 100644 --- a/specs/epics/cron-starter/risks-and-open-questions.md +++ b/specs/epics/cron-starter/risks-and-open-questions.md @@ -9,7 +9,7 @@ when wanted, is a Worker secret the scheduled handler sends as a header and the route checks — `lib/scheduled.ts` already builds the `Request`, so it is one header there and one comparison in the route. -## CR-B — Cron Triggers per account (OPEN until linked) +## CR-B — Cron Triggers per account (RESOLVED in CR4: one trigger per Worker) Seven triggers per Worker, one Worker per environment: fourteen on the account for stage + prod. Cloudflare caps Cron Triggers per account by plan @@ -17,7 +17,17 @@ account for stage + prod. Cloudflare caps Cron Triggers per account by plan account that hosts stage and prod needs the Paid plan, or the deploy fails loudly when the cap is hit. The schedules are the template's, verbatim; a product that only needs some of them trims `triggers.crons` and -`lib/crons.ts` together (the test holds them equal). +`lib/crons.ts` together (the test holds them equal). Since CR4 the +baseline's card, its BOOTSTRAP and the product's README and operating +contract all said the account needed Workers Paid — but the platform has no +way to check a plan before the deploy, so on Free the first deploy was what +refused. Resolved instead: the Worker registers ONE Cron Trigger, every +minute, and the scheduled handler runs every schedule whose expression +matches the trigger's `scheduledTime` (UTC). Two triggers per product, stage +and prod, inside Free's five; the seven schedules unchanged, and still the +expressions the page shows. An account that already holds four or five +triggers from other Workers can still refuse one more; the product's docs +name that case. ## CR-C — KV is not Redis (ACCEPTED) @@ -58,3 +68,93 @@ the deploy button and the Vercel-hosted thumbnail URL read "Cron Triggers on Cloudflare", link to Cloudflare's docs, point at this repository, and serve the thumbnail from `public/`. Layout, styles and structure are untouched; `@vercel/examples-ui`'s nav still shows its own "Vercel Examples" chrome. + +## CR-H — The deploy lane checked for a config only the build makes (RESOLVED in CR4) + +stack-tectonic's `cloudflare-workers-assets-turbo` runs `verify-app-structure` +— `test -f package.json`, `test -f <wranglerConfig>` — BEFORE `build-app`, in +a job tree staged from the checkout. `wrangler.jsonc` was git-ignored and +rendered only by the build, so every Orun lane of the product (dev, stage, +prod; pull request or merge) would have failed at that step: no lane had +ever run (`ORUN_CI` was never set). Fix: commit `wrangler.jsonc` as the +fixture render of `wrangler.template.jsonc` (with a GENERATED banner); the +build still re-renders it for its environment, keeping `main: worker.ts` and +its `triggers.crons`. Checks fails when the two disagree +(`git diff --exit-code` after `wire:fixture`), and `testing/wire.test.sh` +checks the same. `testing/e2e.test.sh` runs the step in a staged tree. + +## CR-I — The dev lane had no wiring document to render (RESOLVED in CR4) + +`buildCommand` rendered with `live.mjs --env "${ORUN_ENVIRONMENT}"`, which +needs `WIRING_CLOUDFLARE_KV_<ENV>`. `dev` subscribes `web` (verify) but no +root applies there, so `WIRING_CLOUDFLARE_KV_DEV` never exists: every dev +lane would have failed in `build-app`. Fix: `live.mjs --fixture +wiring.fixture.json --fixture-envs dev` renders the fixture for the +verify-only environment, and only for it; the fixture gained a `dev` entry. +stage and prod still need the real document and refuse without it +(`testing/wire.test.sh`). + +## CR-J — The deploy's smoke waits on a trigger (ACCEPTED) + +The smoke reads `/api/data/1m` and requires a `fetchedAt` from the last ten +minutes: a run of the every-minute schedule, which the Cron Trigger runs +through the scheduled handler at every firing. On every later deploy the schedule is already running and the +smoke passes at once. On the FIRST deploy it passes only once the new +trigger has fired; Cloudflare says a trigger change "may take several +minutes (up to 15 minutes)" to propagate, and the composition's smoke +retries for about 4.5 minutes. Usually that is enough. When it is not, the +lane fails, and `01-product`'s `orun.run/watch@v1` resumes failed lanes up to +three times (`resumeBudget: 3`, each attempt a fresh build, deploy and 4.5 +minute smoke), by which time the trigger fires. Hacker News is on the same +path (CR-D): the record's story is fetched as the route answers, so an +outage there fails the smoke too, and the resumes cover it the same way. A +smoke that only fetched `/` would pass sooner and prove neither the trigger +nor the binding. + +## CR-K — No live bootstrap yet (OPEN) + +Everything short of the platform is proven on every pull request: the card +against the build, the blueprint read by three orun versions, the leak gate, +the wiring path, the offline bootstrap with the blueprint's own hooks, the +product's own plan (the KV apply before the Worker's deploy; nothing waiting +on a pull request), and the produced product built in the job tree, +dry-deployed with the stage document's namespace id, served under +`wrangler dev --test-scheduled` with the trigger fired through the +scheduled handler at crafted times that make each schedule due and every +record read back, and smoke-tested. NOT proven: the +repository created and linked, the token minted by `integrations/reconcile`, +a real `terraform apply` (the root is held to `terraform validate`; its +`adopt.tf` lookup calls the Cloudflare API), the lease-published document, a +real `wrangler deploy` registering its trigger, the trigger firing on +Cloudflare's clock, the probes. Hence the +registry row is `unlisted` until one bootstrap from the tag has come up. + +## CR-L — The bootstrap floor plans every edge enforced (ACCEPTED) + +orun v2.58.11 — the floor for RUNNING a bootstrap — does not apply a +`dependsOn` edge's `modeRules`: it plans a pull request with `web` waiting on +the KV plan. That CLI never plans the product's CI (its `ci.yml` pins +v2.78.4, which applies them), and on a push to main both agree. The +placement tier plans as the product does: `baseline.yml` runs it under the +lane pin, and the test refuses an orun older than `ci.yml`'s pin. + +## CR-M — A custom domain is the owner's step (ACCEPTED) + +Attaching a domain to a Worker needs zone permissions the brokered +`workers-deploy` token does not carry, and `dns-edit` needs zone ids a build +does not have. The product's README says how to attach one; nothing in the +repository changes, because the page takes its origin from the request and +the trigger needs no hostname. + +## CR-N — Seven schedules on one trigger (ACCEPTED) + +Every schedule now depends on the one every-minute invocation. If Cloudflare +drops the invocation for a minute, every schedule due in that minute misses +its run (the daily run at 00:00, say) — before CR4 each had its own trigger, +which could drop just as well, one at a time. Within an invocation the +schedules run one after another, and a route that fails does not stop the +rest; the invocation then fails, naming each. Due-ness is computed from +`scheduledTime`, the minute the run was scheduled for, not the clock when it +starts, so a late start still runs the right schedules. The weekly schedule +is `0 0 * * 0` — Sunday, as in the template's `vercel.json` and on the page — +not Monday. diff --git a/tasks/CR-1.TaskContract.yaml b/tasks/CR-1.TaskContract.yaml index 9454c32..de6636d 100644 --- a/tasks/CR-1.TaskContract.yaml +++ b/tasks/CR-1.TaskContract.yaml @@ -1,5 +1,8 @@ apiVersion: orun.io/v1 kind: TaskContract +metadata: + name: CR-1 + title: "The spec" spec: goal: The cron-starter epic — declaration, doc set and task contracts — is on main affects: diff --git a/tasks/CR-2.TaskContract.yaml b/tasks/CR-2.TaskContract.yaml index a40e7d8..5b23d73 100644 --- a/tasks/CR-2.TaskContract.yaml +++ b/tasks/CR-2.TaskContract.yaml @@ -1,5 +1,8 @@ apiVersion: orun.io/v1 kind: TaskContract +metadata: + name: CR-2 + title: "The crons on Workers" spec: goal: The upstream cron example runs on Cloudflare Workers with its seven schedules as Cron Triggers driving the same API routes, the records in Workers KV, a per-environment rendered wrangler config and green checks affects: diff --git a/tasks/CR-3.TaskContract.yaml b/tasks/CR-3.TaskContract.yaml index 6ba4626..8043322 100644 --- a/tasks/CR-3.TaskContract.yaml +++ b/tasks/CR-3.TaskContract.yaml @@ -1,5 +1,8 @@ apiVersion: orun.io/v1 kind: TaskContract +metadata: + name: CR-3 + title: "The KV namespace from Terraform" spec: goal: The KV namespace per environment is provisioned by Terraform through Orun and publishes the wiring document the app renders from affects: diff --git a/tasks/CR-4.TaskContract.yaml b/tasks/CR-4.TaskContract.yaml index 8dbe526..9fe2ef2 100644 --- a/tasks/CR-4.TaskContract.yaml +++ b/tasks/CR-4.TaskContract.yaml @@ -1,5 +1,8 @@ apiVersion: orun.io/v1 kind: TaskContract +metadata: + name: CR-4 + title: "Ready to instantiate" spec: goal: A reader can run, test, preview, fire a trigger and deploy the port from the README; the as-built status is complete affects: diff --git a/tasks/CR-5.TaskContract.yaml b/tasks/CR-5.TaskContract.yaml new file mode 100644 index 0000000..061dce5 --- /dev/null +++ b/tasks/CR-5.TaskContract.yaml @@ -0,0 +1,36 @@ +apiVersion: orun.io/v1 +kind: TaskContract +metadata: + name: CR-5 + title: "A baseline, in one landing" +spec: + goal: The repository is an Orun baseline — a card and a build document that take a new product from nothing to live on stage and prod in ONE landing, the KV namespace applied before the Worker that binds it and whose Cron Triggers write to it, branded as its own, with gates that prove it offline + affects: + - blueprint.yaml + - repo-blueprint.yaml + - BOOTSTRAP.md + - README.md + - .baseline/** + - tooling/rebrand/** + - tooling/bootstrap/** + - tooling/wire/** + - hooks/** + - testing/** + - docs/phases/** + - ai/context/** + - .github/workflows/** + - .gitignore + - intent.yaml + - packages/.gitkeep + - apps/web/** + - tests/web/** + - infra/terraform/cloudflare-kv/** + - specs/** + - tasks/** + doneWhen: + - orun (the bootstrap floor, the lane pin and the current CLI) reads repo-blueprint.yaml, and the card agrees with it + - the product's own push-to-main plan applies cloudflare-kv before it deploys web, on stage and prod, and a pull request waits on nothing + - the leak gate, the wiring contract, the offline bootstrap and the end-to-end tier (the scheduled handler fired in the built Worker, its record read back) are green in Baseline CI + - the as-built status records the departures and what is not yet proven live + gates: + - checks diff --git a/testing/bootstrap-defer.test.sh b/testing/bootstrap-defer.test.sh new file mode 100755 index 0000000..526e2b4 --- /dev/null +++ b/testing/bootstrap-defer.test.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# The two things a bootstrap turns off in intent.yaml and puts back — +# `prod.promotion` (tooling/bootstrap/promotion.mjs) and dev's push-to-main +# activation (tooling/bootstrap/dev-lanes.mjs) — must each defer, be +# idempotent both ways, leave a parseable intent while deferred, and restore +# the file BYTE-FOR-BYTE: a restore that reproduced the block by hand would +# be a second place the intent is authored. +set -euo pipefail +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +root="$(cd "$here/.." && pwd)" +fail=0 +ok() { echo " ok $1"; } +bad() { echo " ✕ $1" >&2; fail=1; } + +tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT +cp "$root/intent.yaml" "$tmp/intent.yaml" + +for tool in promotion dev-lanes; do + f="$tmp/intent.yaml"; cp "$root/intent.yaml" "$f" + echo "── $tool.mjs" + node "$root/tooling/bootstrap/$tool.mjs" --check --file "$f" | grep -q -E 'enforced|active' && ok "starts enforced/active" || bad "starts enforced/active" + node "$root/tooling/bootstrap/$tool.mjs" --defer --file "$f" >/dev/null + node "$root/tooling/bootstrap/$tool.mjs" --check --file "$f" | grep -q deferred && ok "--defer defers" || bad "--defer defers" + python3 -c "import yaml,sys; yaml.safe_load(open(sys.argv[1]))" "$f" && ok "deferred intent still parses" || bad "deferred intent still parses" + cp "$f" "$tmp/once.yaml"; node "$root/tooling/bootstrap/$tool.mjs" --defer --file "$f" >/dev/null + cmp -s "$f" "$tmp/once.yaml" && ok "a second --defer changes nothing" || bad "a second --defer changes nothing" + node "$root/tooling/bootstrap/$tool.mjs" --restore --file "$f" >/dev/null + cmp -s "$f" "$root/intent.yaml" && ok "--restore is byte-exact" || bad "--restore is byte-exact" + node "$root/tooling/bootstrap/$tool.mjs" --restore --file "$f" >/dev/null + cmp -s "$f" "$root/intent.yaml" && ok "a second --restore changes nothing" || bad "a second --restore changes nothing" +done + +echo "── what each deferral means to a push-to-main plan" +f="$tmp/intent.yaml"; cp "$root/intent.yaml" "$f" +node "$root/tooling/bootstrap/dev-lanes.mjs" --defer --file "$f" >/dev/null +python3 - "$f" <<'PY' && ok "dev is no longer activated by github-push-main while deferred" || bad "dev is no longer activated by github-push-main while deferred" +import sys, yaml +d = yaml.safe_load(open(sys.argv[1])) +refs = d["environments"]["dev"]["activation"]["triggerRefs"] +assert "github-push-main" not in refs and "github-pull-request" in refs, refs +PY +f="$tmp/intent.yaml"; cp "$root/intent.yaml" "$f" +node "$root/tooling/bootstrap/promotion.mjs" --defer --file "$f" >/dev/null +python3 - "$f" <<'PY' && ok "prod has no promotion gate while deferred" || bad "prod has no promotion gate while deferred" +import sys, yaml +d = yaml.safe_load(open(sys.argv[1])) +assert "promotion" not in d["environments"]["prod"], d["environments"]["prod"].keys() +PY + +echo "── work-tree.mjs — the baseline's work tree does not ship" +f="$tmp/intent.yaml"; cp "$root/intent.yaml" "$f" +node "$root/tooling/bootstrap/work-tree.mjs" --check --file "$f" | grep -q declared && ok "this repository declares a work tree" || bad "this repository declares a work tree" +node "$root/tooling/bootstrap/work-tree.mjs" --strip --file "$f" >/dev/null +node "$root/tooling/bootstrap/work-tree.mjs" --check --file "$f" | grep -q absent && ok "--strip removes it" || bad "--strip removes it" +python3 - "$f" "$root/intent.yaml" <<'PY' && ok "everything else in the intent is untouched" || bad "everything else in the intent is untouched" +import sys, yaml +after, before = (yaml.safe_load(open(p)) for p in sys.argv[1:3]) +assert "work" not in after, list(after) +before.pop("work") +assert after == before, "a key other than work: changed" +PY +grep -q 'Where the work lives' "$f" && bad "the block's own comment is left behind" || ok "the block's own comment goes with it" +cp "$f" "$tmp/once.yaml"; node "$root/tooling/bootstrap/work-tree.mjs" --strip --file "$f" >/dev/null +cmp -s "$f" "$tmp/once.yaml" && ok "a second --strip changes nothing" || bad "a second --strip changes nothing" + +if [ "$fail" -ne 0 ]; then echo "bootstrap-defer.test.sh: failure(s)" >&2; exit 1; fi +echo "bootstrap-defer.test.sh: ok" diff --git a/testing/coverage.test.sh b/testing/coverage.test.sh new file mode 100755 index 0000000..1ee1577 --- /dev/null +++ b/testing/coverage.test.sh @@ -0,0 +1,177 @@ +#!/usr/bin/env bash +# EVERY COMPONENT THIS REPO SHIPS IS PLACED BY EXACTLY ONE PHASE +# (saas-bootstrap-engine BE5, Tier 0). +# +# `repo-blueprint.yaml` decides what a product is made of. A component that no +# module names is not a component a product gets — and nothing would say so. +# The failure is quiet and late: the fork builds, its CI goes green, and the +# missing piece surfaces when somebody looks for a worker that was never +# copied. +# +# orun already enforces the other half — every MODULE belongs to exactly one +# phase, and a module naming an unknown module is a parse error. What it cannot +# know is what this repository contains, because a blueprint declares what to +# place and not what exists. That is this file's job. +# +# bash + python3 + PyYAML. No network, no orun, no credential. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +echo "── every component against the blueprint that places it" +python3 - "$root" <<'PY' +import pathlib, sys + +try: + import yaml +except ImportError: + sys.exit("PyYAML is required for the coverage gate (pip install pyyaml)") + +root = pathlib.Path(sys.argv[1]) +problems = [] +def bad(m): problems.append(m) + +# A component directory this repository deliberately keeps to itself. Declared +# with its reason rather than skipped by a pattern: "tests/*" would also hide +# the test suite a product genuinely needs, and the next +# baseline-only directory should have to be argued for in a diff. +# EMPTY: every component here is a product's. The baseline's own suites live in +# `testing/`, which is not a component at all and so is not one this gate can +# miss. The map stays so that the next baseline-only directory has to be +# argued for in a diff; the check below refuses an exemption whose directory is +# absent, so a stale entry cannot linger. +BASELINE_ONLY: dict[str, str] = {} + +bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text()) + +# Where each module takes its content from, and which phase places it. +placed_by = {} +for m in bp.get("modules") or []: + src = (m.get("from") or "").rstrip("/") + if src: + placed_by.setdefault(src, []).append(m["name"]) +phase_of = {n: ph["name"] for ph in (bp.get("phases") or []) for n in ph["modules"]} + +components = sorted( + p.parent.relative_to(root).as_posix() + for p in root.rglob("component.yaml") + if "node_modules" not in p.parts and ".git" not in p.parts +) +if not components: + sys.exit("no component.yaml anywhere — this check has gone blind") + +for comp in components: + modules = placed_by.get(comp, []) + reason = BASELINE_ONLY.get(comp) + + if reason and modules: + bad(f"{comp} is declared baseline-only ({reason}) and yet {modules[0]} " + f"places it — one of the two is wrong") + continue + if reason: + continue + if not modules: + bad(f"{comp} is a component and no module places it. Either add one, or " + f"declare it baseline-only in this file with the reason.") + continue + if len(modules) > 1: + bad(f"{comp} is placed by {len(modules)} modules ({', '.join(modules)}) " + f"— a component comes from one place") + continue + if modules[0] not in phase_of: + bad(f"{comp} is placed by {modules[0]}, which is in no phase") + +# The other direction: a module naming a path this repo does not have places +# nothing, silently. orun resolves `from` against the source tree and an absent +# path is an empty module, not an error. +for src, modules in sorted(placed_by.items()): + if not (root / src).exists(): + bad(f"module {modules[0]} takes its content from {src}, which does not " + f"exist — it would place nothing, and say nothing") + +# A directory named baseline-only must actually BE one, or the exemption is +# protecting nothing and will outlive the thing it was written for. +for comp in BASELINE_ONLY: + if not (root / comp).exists(): + bad(f"{comp} is declared baseline-only and does not exist — drop the entry") + +# ── WHAT `ignore` ACTUALLY EXCLUDES (BE6) ────────────────────────────────── +# +# orun matches an ignore entry two ways, and WHICH ONE depends on the entry: +# a pattern containing no glob metacharacter is compared against each path +# SEGMENT, and only a pattern containing one is compared against the whole +# relative path. So `apps/admin-worker/wrangler.jsonc` matches nothing at all — +# no segment is ever equal to it — and the entry is INERT while reading exactly +# like a rule. +# +# That was not hypothetical. Twelve such entries were inert in this file's own +# blueprint, and a canary written to `apps/admin-worker/wrangler.jsonc` was +# placed straight into a product — which is the leak their comment says they +# exist to prevent. An `ignore` list that silently does nothing is worse than +# no list, because the comment above it reads as a defence. +for entry in bp.get("ignore") or []: + if "/" in entry and not any(c in entry for c in "*?["): + bad(f'ignore entry "{entry}" names a path and has no glob character, so orun ' + f'matches it against path SEGMENTS and it excludes nothing. Write it as ' + f'"**/{entry}".') + +# A workflow that runs the FACTORY must not ship to the factory's products. +# `github-workflows` copies the whole `.github` directory, so a lane added for +# this repository travels to every product built from it — and one that reads a +# path under `testing/` cannot work there, because `testing/` is not placed. +# A nightly lane did exactly this once: shipped, on a cron, reading an intent +# file no product has. +ignored = set(bp.get("ignore") or []) +workflows = sorted((root / ".github" / "workflows").glob("*.y*ml")) +for wf in workflows: + text = wf.read_text(encoding="utf-8") + if "testing/" not in text: + continue + rel = f".github/workflows/{wf.name}" + if f"**/{rel}" not in ignored and rel not in ignored: + bad(f"{rel} reads a path under testing/, which no product is placed with, " + f"and is not in the blueprint's ignore list — so it ships into every " + f'product and fails there. Add "**/{rel}" to ignore.') + +# ONE WORKFLOW ON A PUSH TO MAIN, in what a product carries. The bootstrap +# watches each phase's convergence with `orun.run/watch@v1` and `sha:`, which +# takes the newest workflow run for the merge commit — from any workflow. A +# second one on push (checks.yml did this) can be the run it finds: the first +# live bootstrap watched Checks go green while ci.yml's deploy lanes had +# failed. So every shipped workflow but ci.yml stays off pushes to main. +import yaml as _yaml +on_push = [] +for wf in workflows: + rel = f".github/workflows/{wf.name}" + if f"**/{rel}" in ignored or rel in ignored: + continue # the factory's own; never in a product + doc = _yaml.safe_load(wf.read_text(encoding="utf-8")) or {} + on = doc.get("on", doc.get(True)) # PyYAML reads a bare `on:` key as True + if isinstance(on, str): + on = {on: None} + elif isinstance(on, list): + on = {k: None for k in on} + push = (on or {}).get("push", "absent") + if push == "absent": + continue + branches = (push or {}).get("branches") if isinstance(push, dict) else None + if branches is None or "main" in branches: + on_push.append(wf.name) +if on_push != ["ci.yml"]: + bad(f"the workflows a product runs on a push to main are {on_push or 'none'}; " + f"it must be exactly ci.yml — orun.run/watch@v1 watches the newest run " + f"for a commit from ANY workflow, so a second one hides the convergence") + +if problems: + print("FAIL: the blueprint and this repository disagree about what a product is:", + file=sys.stderr) + for p in problems: + print(f" - {p}", file=sys.stderr) + sys.exit(1) + +shipped = len(components) - len(BASELINE_ONLY) +print(f" {shipped} of {len(components)} components placed, " + f"{len(BASELINE_ONLY)} baseline-only by declaration") +PY + +echo "coverage.test.sh: ok" diff --git a/testing/e2e.test.sh b/testing/e2e.test.sh new file mode 100755 index 0000000..01dc53d --- /dev/null +++ b/testing/e2e.test.sh @@ -0,0 +1,414 @@ +#!/usr/bin/env bash +# TIER 2 — the product a bootstrap produces builds, deploys (dry), serves, and +# runs its schedules. +# +# placement.test.sh proves the tree a bootstrap ends with is the right tree. +# This proves it WORKS, by doing to it what its own pipelines will: +# +# 1. at the 01-product landing (the commit its one pull request merges), +# run what `checks.yml` runs on that PR — install with the lockfile the +# phase confirmed, render the wrangler fixture and check the committed +# config IS that render, typecheck, lint, test, build. The landing WAITS +# on those checks, so a product they refuse is a bootstrap that never +# merges; +# 2. the stage lane's own steps, rendered by `orun plan` in the product for +# a pull request (the verify profile: the deploy profile has no dry run) +# — `verify-app-structure` (which checks the wrangler config exists +# BEFORE anything is built), `build-app` (the component's buildCommand: +# the live wiring render, then the build), `verify-build-output` and +# `deploy-dry-run` (`wrangler deploy --dry-run --name <reponame>-web-stage`). +# They run IN THE TREE THE RUNNER STAGES for the job +# (testing/lib/stage-job.py), with the dependency layout the pinned +# composition produces, and with the stage wiring document in the job's +# environment as the platform resolves it (the component's secretEnv) — +# so the namespace id in the built config is asserted to be the +# document's, not the fixture's — and the config the build rendered is +# asserted to keep the Worker's custom entry (`worker.ts`, which adds the +# scheduled handler) and its ONE Cron Trigger (every minute; the seven +# schedules are dispatched from it); +# 3. serve the built Worker from that tree with `wrangler dev +# --test-scheduled` and exercise THE CRON PATH: the component's OWN +# `smokeCommand` (the check the real deploy ends with), verbatim, must +# REFUSE the Worker before any trigger has fired; then the trigger is +# fired through the scheduled handler — `GET /__scheduled?cron=*+*+*+*+*` +# on the clock, then at crafted scheduled times through wrangler's local +# trigger route (`/cdn-cgi/local/scheduled?cron=…&time=…`, because +# `/__scheduled` always stamps the present) — and at each time exactly +# the schedules due then must run `/api/cron/<interval>` through the +# OpenNext fetch handler, every other record staying as it was; each +# record is read back through `/api/data/<interval>` — the route only +# the Worker answers, reading its KV binding (wrangler dev provides the +# namespace locally); then the smoke must PASS. Then every +# other route the page promises: the heading and title carry the +# product's name, the links its repository, the Open Graph image is +# absolute on the origin it was asked on, the static assets are served, +# the public cron route runs a schedule on request as Vercel's did, and +# an unknown path is a 404. +# +# What it cannot do is the platform's half: create the repository, mint the +# brokered Cloudflare token, apply the namespace, deploy for real, have +# Cloudflare's clock fire the trigger, and probe workers.dev. The KV root is +# verified to `terraform validate` (CR2) and its plan is part of every pull +# request's lanes; the apply needs an account. +# +# Needs: orun, node, pnpm, python3 (+PyYAML), git, curl, and the network for +# `pnpm install` and for Hacker News, which every scheduled run calls (as +# upstream). A few minutes: two installs and builds. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" +# shellcheck source=lib/bootstrap.sh +source "$here/lib/bootstrap.sh" + +for bin in orun node pnpm python3 git curl; do + command -v "$bin" >/dev/null || { echo "e2e.test.sh needs $bin on PATH" >&2; exit 1; } +done + +scratch="$(mktemp -d)" +dev_pid="" +# wrangler dev runs under pnpm, node and two workerd processes; a TERM to the +# first does not reach the rest, and waiting on it then never returns. So it is +# started as its own process group (setsid) and the whole group is stopped. +cleanup() { + if [ -n "$dev_pid" ]; then + kill -TERM -- "-$dev_pid" 2>/dev/null || true + for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 -- "-$dev_pid" 2>/dev/null || break; sleep 0.5; done + kill -KILL -- "-$dev_pid" 2>/dev/null || true + fi + rm -rf "$scratch" +} +trap cleanup EXIT +values="$here/fixtures/acme.json" +repo="$(python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['reponame'])" "$values")" +export CI=1 WRANGLER_SEND_METRICS=false NEXT_TELEMETRY_DISABLED=1 TURBO_TELEMETRY_DISABLED=1 + +# What checks.yml runs, step for step, read out of the workflow the product +# carries so the two cannot drift: every `run:` of its one job, in order. +checks() { # DIR LOG + local dir="$1" log="$2" cmd + while IFS= read -r cmd; do + echo " \$ $cmd" | tee -a "$log" + if ! (cd "$dir" && bash -c "$cmd") >> "$log" 2>&1; then + echo "FAIL: \`$cmd\` failed in $dir" >&2; tail -40 "$log" >&2; return 1 + fi + done < <(python3 - "$dir/.github/workflows/checks.yml" <<'PY' +import sys, yaml +wf = yaml.safe_load(open(sys.argv[1])) +for job in wf["jobs"].values(): + for step in job["steps"]: + if "run" in step: + print(step["run"].strip()) +PY +) +} + +echo "── the offline bootstrap (testing/lib/bootstrap.sh)" +tree="$scratch/$repo" +bootstrap_offline "$root" "$tree" "$values" "$scratch/logs" > "$scratch/bootstrap.log" 2>&1 || { + echo "FAIL: the offline bootstrap stopped" >&2; tail -40 "$scratch/bootstrap.log" >&2; exit 1; } +echo " 2 phases placed and landed" +s01="$(git -C "$tree" rev-parse HEAD~1)" + +# ── 1. the product's one pull request ────────────────────────────────────── +echo "── 01-product's landing, under the checks its PR waits on" +git -C "$tree" worktree add -q "$scratch/at-01" "$s01" +checks "$scratch/at-01" "$scratch/checks-01.log" +# The first Checks build is done; its tree is not needed again, and the disk is shared. +git -C "$tree" worktree remove --force "$scratch/at-01" + +# ── 2. the stage lane's steps, in the job's own tree ────────────────────── +echo "── the stage lane: verify-app-structure, build-app, verify-build-output, deploy-dry-run" +# A pull request that changes the page: the lane `orun plan` gives it. +git -C "$tree" checkout -q -b e2e-pr +echo "<!-- a change to the page's component -->" >> "$tree/apps/web/README.md" +git -C "$tree" -c user.email=e2e@example.invalid -c user.name=e2e commit -qam "a pull request" +(cd "$tree" && orun plan --intent intent.yaml --trigger github-pull-request --changed \ + --base main --head HEAD --env stage --output "$scratch/plan.json") > "$scratch/plan.log" 2>&1 \ + || { echo "FAIL: orun plan" >&2; tail -15 "$scratch/plan.log" >&2; exit 1; } +python3 - "$scratch/plan.json" "$scratch/steps" <<'PY' +import json, pathlib, sys +plan = json.load(open(sys.argv[1])) +out = pathlib.Path(sys.argv[2]); out.mkdir() +job = next(j for j in plan["jobs"] if j["component"] == "web" and j["environment"] == "stage") +for s in job["steps"]: + if s["id"] in ("verify-app-structure", "build-app", "verify-build-output", "deploy-dry-run"): + (out / f"{s['id']}.sh").write_text(s.get("run") or "") + if s["id"] == "install-workspace-dependencies": + (out / "install.sh").write_text(s.get("run") or "") + (out / "install.wd").write_text(s.get("working-directory") or ".") + (out / "install.scope").write_text(s.get("scope") or "job") +(out / "path").write_text(job.get("path") or "apps/web") +for k, v in (job.get("env") or {}).items(): + (out / "env").open("a").write(f"export {k}={json.dumps(v)}\n") +(out / "secrets").write_text("\n".join(r["asEnv"] for r in job.get("secretRefs") or [])) +PY +# The job's private tree, staged as orun stages it. The source checkout +# carries no build output (nothing was built in it), and its dependencies are +# what the pinned composition says: a lane-scoped install ran once in the +# source tree and is linked in, or the job installs its own. +work="$tree/.orun/runs/e2e/web.stage.verify-deploy/work" +[ -f "$scratch/steps/install.sh" ] || { echo "FAIL: the stage lane has no install step" >&2; exit 1; } +if [ "$(cat "$scratch/steps/install.scope")" = lane ]; then + (cd "$tree" && bash -e "$scratch/steps/install.sh") > "$scratch/install.log" 2>&1 \ + || { echo "FAIL: the lane's install step" >&2; tail -30 "$scratch/install.log" >&2; exit 1; } + python3 "$here/lib/stage-job.py" "$tree" "$work" --shared-deps + [ -L "$work/node_modules" ] || { echo "FAIL: the staged tree's node_modules is not the lane's symlink" >&2; exit 1; } + echo " staged: $(realpath --relative-to="$tree" "$work"); install scope: lane — node_modules → the source tree's" +else + python3 "$here/lib/stage-job.py" "$tree" "$work" + echo " staged: $(realpath --relative-to="$tree" "$work"); install scope: job — installing inside it" + echo " ▸ install-workspace-dependencies" + (cd "$work/$(cat "$scratch/steps/path")/$(cat "$scratch/steps/install.wd")" && bash -e "$scratch/steps/install.sh") \ + > "$scratch/install.log" 2>&1 || { echo "FAIL: the lane's install step" >&2; tail -30 "$scratch/install.log" >&2; exit 1; } + [ -d "$work/node_modules" ] && [ ! -L "$work/node_modules" ] \ + || { echo "FAIL: the job's install did not land inside its own tree" >&2; exit 1; } +fi +[ ! -e "$work/apps/web/.open-next" ] || { echo "FAIL: the staged tree carries build output" >&2; exit 1; } +# What the platform resolves into the job before its first step: the wiring +# documents the KV root lease-published (the component's secretEnv). Ids no +# fixture carries, so the built config proves which one it was rendered from. +for env in stage prod; do + key="WIRING_CLOUDFLARE_KV_$(echo "$env" | tr a-z A-Z)" + grep -qx "$key" "$scratch/steps/secrets" || { echo "FAIL: the stage lane does not resolve $key" >&2; exit 1; } +done +export WIRING_CLOUDFLARE_KV_STAGE='{"app_kv_id":"5ca1ab1e5ca1ab1e5ca1ab1e0000a001","app_kv_title":"stg-'"$repo"'-app-kv-stage"}' +export WIRING_CLOUDFLARE_KV_PROD='{"app_kv_id":"5ca1ab1e5ca1ab1e5ca1ab1e0000a003","app_kv_title":"prod-'"$repo"'-app-kv-prod"}' +for step in verify-app-structure build-app verify-build-output deploy-dry-run; do + [ -f "$scratch/steps/$step.sh" ] || { echo "FAIL: the stage verify lane has no $step step" >&2; exit 1; } + echo " ▸ $step" + # The runner's per-job environment: the job's env (intent environment + # `env:`), its resolved secrets, and ORUN_ENVIRONMENT; the step runs in the + # component's directory. + if ! (cd "$work/$(cat "$scratch/steps/path")" && \ + { [ -f "$scratch/steps/env" ] && source "$scratch/steps/env"; true; } && \ + export ORUN_ENVIRONMENT=stage && bash -e "$scratch/steps/$step.sh") > "$scratch/$step.log" 2>&1; then + echo "FAIL: the deploy lane's $step step" >&2; tail -40 "$scratch/$step.log" >&2; exit 1 + fi +done +grep -q '"5ca1ab1e5ca1ab1e5ca1ab1e0000a001"' "$work/apps/web/wrangler.jsonc" \ + || { echo "FAIL: the lane's build did not render the stage namespace id from its wiring document" >&2; exit 1; } +grep -q 'env.KV' "$scratch/deploy-dry-run.log" && grep -q '5ca1ab1e5ca1ab1e5ca1ab1e0000a001' "$scratch/deploy-dry-run.log" \ + || { echo "FAIL: the dry run does not bind KV to the stage namespace" >&2; tail -20 "$scratch/deploy-dry-run.log" >&2; exit 1; } +# THE CRON PATH SURVIVES THE BUILD. The scheduled handler lives in the custom +# entry, not in OpenNext's generated worker, and the trigger in the config the +# build re-renders: both must come out of the lane's build intact, and the +# generated worker the entry imports must exist beside them (the composition's +# verify-build-output checks only the entry, which is a source file). +python3 - "$work/apps/web" <<'PY2' || exit 1 +import json, pathlib, re, sys +app = pathlib.Path(sys.argv[1]) +conf = json.loads(re.sub(r"^\s*//.*$", "", (app / "wrangler.jsonc").read_text(), flags=re.M)) +problems = [] +if conf.get("main") != "worker.ts": + problems.append(f"the built config's main is {conf.get('main')!r}, not worker.ts — no scheduled handler") +if (conf.get("triggers") or {}).get("crons") != ["* * * * *"]: + problems.append(f"the built config's triggers.crons are {(conf.get('triggers') or {}).get('crons')}, not the one every-minute trigger") +if not (app / ".open-next/worker.js").is_file(): + problems.append("the build left no .open-next/worker.js for worker.ts to import") +if "scheduled" not in (app / "worker.ts").read_text(): + problems.append("worker.ts exports no scheduled handler") +for p in problems: + print(f"FAIL: {p}", file=sys.stderr) +sys.exit(1 if problems else 0) +PY2 +echo " the built config binds KV to the stage document's namespace id, keeps worker.ts (fetch + scheduled)" +echo " and its one trigger; .open-next/worker.js is there for it; the dry run accepts the bundle" + +# ── 3. serve it, fire its schedules, and smoke it as the deploy does ─────── +echo "── wrangler dev --test-scheduled over the built Worker" +port=$(python3 -c "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print(s.getsockname()[1]);s.close()") +(cd "$work/apps/web" && exec setsid pnpm exec wrangler dev --config wrangler.jsonc --ip 127.0.0.1 --port "$port" \ + --name "$repo-web-stage" --test-scheduled --show-interactive-dev-session=false) > "$scratch/dev.log" 2>&1 < /dev/null & +dev_pid=$! +url="http://127.0.0.1:$port" +for _ in $(seq 1 90); do + curl -s -o /dev/null "$url/favicon.ico" && break + kill -0 "$dev_pid" 2>/dev/null || { echo "FAIL: wrangler dev exited" >&2; tail -30 "$scratch/dev.log" >&2; exit 1; } + sleep 1 +done +curl -s -o /dev/null "$url/favicon.ico" || { echo "FAIL: wrangler dev never answered" >&2; tail -30 "$scratch/dev.log" >&2; exit 1; } + +# The component's own smoke, verbatim, under the shell options the +# composition's smoke step sets (it wraps it in a retry loop; here it runs once). +smoke="$(python3 -c "import yaml,sys;print(yaml.safe_load(open(sys.argv[1]))['spec']['parameters']['smokeCommand'])" "$tree/apps/web/component.yaml")" +run_smoke() { DEPLOYED_URL="$url" bash -uo pipefail -c "$smoke"; } + +echo " ▸ the component's own smokeCommand, DEPLOYED_URL=$url, before any trigger fired" +if run_smoke > "$scratch/smoke-before.log" 2>&1; then + echo "FAIL: the deploy's smoke passed on a Worker no trigger has run — it does not prove the cron" >&2; exit 1 +fi +echo " refused: no run recorded yet" + +echo " ▸ the one trigger fired through the scheduled handler, on the clock and at crafted times" +python3 - "$url" "$tree/apps/web/lib/crons.ts" "$scratch/dev.log" <<'PY' +import json, re, sys, time, urllib.error, urllib.parse, urllib.request +from datetime import datetime, timezone +base, crons_ts, devlog = sys.argv[1], sys.argv[2], sys.argv[3] +src = open(crons_ts).read() +crons = re.findall(r"\{ interval: '([^']+)', cron: '([^']+)' \}", src) +intervals = [i for i, _ in crons] +trigger = re.search(r"export const TRIGGER = '([^']+)'", src).group(1) +problems = [] +def bad(m): problems.append(m) +def get(path): + try: + with urllib.request.urlopen(base + path, timeout=120) as r: + return r.status, r.read().decode() + except urllib.error.HTTPError as e: + return e.code, e.read().decode() +def records(): + out = {} + for i in intervals: + s, body = get(f"/api/data/{i}") + try: + out[i] = json.loads(body).get("fetchedAt") if s == 200 else ("error", s) + except ValueError: + out[i] = ("error", s) + return out +def log(): + return open(devlog, errors="replace").read() +if len(crons) != 7 or trigger != "* * * * *": + sys.exit(f"lib/crons.ts lists {len(crons)} schedules and the trigger {trigger!r}") +q = urllib.parse.quote + +# Nothing is recorded before a trigger fires: the namespace is the job tree's own. +for i, at in records().items(): + if at is not None: + bad(f"/api/data/{i} answered {at!r} before any trigger fired") + +# An expression that is not the Worker's trigger runs nothing, and fails nothing. +s, body = get("/__scheduled?cron=" + q("30 4 * * *")) +if s != 200: + bad(f"a foreign expression made the scheduled handler answer {s}: {body[:120]!r}") +time.sleep(1) +if 'no route for cron "30 4 * * *"' not in log(): + bad("the foreign expression was not reported by the scheduled handler") +if any(at is not None for at in records().values()): + bad("a foreign expression wrote a record") + +# The trigger, on the clock: /__scheduled (wrangler dev --test-scheduled). +fired = int(time.time() * 1000) +s, body = get("/__scheduled?cron=" + q(trigger)) +if s != 200: + bad(f"/__scheduled?cron={trigger} answered {s}: {body[:160]!r}") +time.sleep(1) +at = records()["1m"] +if not isinstance(at, int) or not (fired - 5_000 <= at <= int(time.time() * 1000) + 5_000): + bad(f"/__scheduled ran no /api/cron/1m: /api/data/1m's fetchedAt is {at!r}") +if '/api/cron/1m 200 "OK"' not in log(): + bad("the scheduled handler did not log a 200 from /api/cron/1m") + +# The trigger at crafted scheduled times: exactly the schedules due then run. +CASES = [ + ("2026-10-14T09:07:00Z", ["1m"]), # an ordinary minute + ("2026-10-14T09:10:00Z", ["1m", "10m"]), # minute % 10 == 0 + ("2026-10-14T10:00:00Z", ["1m", "10m", "1h"]), # the top of an hour + ("2026-10-14T12:00:00Z", ["1m", "10m", "1h", "12h"]), # noon + ("2026-10-15T00:00:00Z", ["1m", "10m", "1h", "12h", "1d"]), # midnight, a Thursday + ("2026-10-19T00:00:00Z", ["1m", "10m", "1h", "12h", "1d"]), # midnight, a Monday + ("2026-10-18T00:00:00Z", ["1m", "10m", "1h", "12h", "1d", "1w"]), # midnight, a Sunday (0 0 * * 0) + ("2026-12-01T00:00:00Z", ["1m", "10m", "1h", "12h", "1d", "1mo"]), # midnight on the 1st, a Tuesday +] +for iso, due in CASES: + when = int(datetime.fromisoformat(iso.replace("Z", "+00:00")).timestamp() * 1000) + before = records() + time.sleep(0.05) + s, body = get(f"/cdn-cgi/local/scheduled?cron={q(trigger)}&time={when}&format=json") + if s != 200: + bad(f"the trigger at {iso} answered {s}: {body[:200]!r}"); continue + after = records() + ran = [i for i in intervals if after[i] != before[i]] + if ran != due: + bad(f"the trigger at {iso} ran {ran}; due then: {due}") + for i in due: + if not isinstance(after[i], int): + bad(f"/api/data/{i} answered {after[i]!r} after the trigger at {iso}") + +final = records() +for i in intervals: + s, body = get(f"/api/data/{i}") + record = json.loads(body) if s == 200 else {} + if not isinstance(record.get("fetchedAt"), int) or not isinstance(record.get("id"), int): + bad(f"/api/data/{i} does not read its run back (fetchedAt and a Hacker News story id): {body[:120]!r}") +if problems: + for p in problems: + print(f" ✕ {p}", file=sys.stderr) + sys.exit(1) +print(f" /__scheduled?cron={trigger} ran /api/cron/1m; at {len(CASES)} crafted times exactly the due schedules ran") +print(f" (1m always · 10m · 1h · 12h · 1d · 1w on Sunday · 1mo on the 1st), the rest untouched; a foreign") +print(f" expression runs nothing; all {len(intervals)} records read back through /api/data/<interval>") +PY + +echo " ▸ the component's own smokeCommand, after the trigger fired" +run_smoke > "$scratch/smoke-after.log" 2>&1 \ + || { echo "FAIL: the deploy's smoke refused a Worker whose every-minute trigger has run" >&2; cat "$scratch/smoke-after.log" >&2; exit 1; } +echo " passed: /api/data/1m carries the run the trigger recorded" + +echo " ▸ every other route the page promises" +python3 - "$url" "$values" <<'PY' +import html, json, re, sys, time, urllib.error, urllib.request +base, values = sys.argv[1], json.load(open(sys.argv[2])) +name, repo, org = values["productname"], values["reponame"], values["githuborg"] +problems = [] +def bad(m): problems.append(m) +def get(path): + try: + with urllib.request.urlopen(base + path, timeout=60) as r: + return r.status, r.headers.get("content-type", ""), r.read() + except urllib.error.HTTPError as e: + return e.code, e.headers.get("content-type", ""), e.read() + +status, _, body = get("/") +page = body.decode() +if status != 200: + bad(f"/ answered {status}") +h1 = re.search(r"<h1[^>]*>(.*?)</h1>", page, re.S) +if not h1 or html.unescape(re.sub(r"<[^>]+>", "", h1.group(1))).strip() != name: + bad(f"the page's heading is {h1 and h1.group(1)!r}, not {name!r}") +head = page[:page.find("</head>")] +title = re.search(r"<title[^>]*>(.*?)", head, re.S) +if not title or html.unescape(title.group(1)) != name: + bad(f"the page's is {title and title.group(1)!r}, not {name!r}") +if not re.search(r'<meta name="description" content="[^"]+"', head): + bad("the page's head carries no description") +# The layout's repository link and its "Clone & Deploy" button: the product's. +links = [l for l in re.findall(r'href="(https://github\.com/[^"]*)"', page) + if not l.startswith(("https://github.com/vercel/examples", "https://github.com/HackerNews/"))] +if links != [f"https://github.com/{org}/{repo}"] * 2: + bad(f"the page's repository links are {links}, not github.com/{org}/{repo} twice") +if re.search(r"(?<![\w-])cron-starter(?![\w-])", page) or "Cron Triggers on Cloudflare" in page: + bad("the page still carries the baseline's name") +og = re.search(r'<meta property="og:image" content="([^"]+)"', page) +if not og or og.group(1) != f"{base}/thumbnail.png": + bad(f"og:image is {og and og.group(1)!r} — not absolute on the origin it was asked on ({base})") +# The seven schedules, as the page lists them, are the seven the Worker runs. +for cron in ("* * * * *", "*/10 * * * *", "0 * * * *", "0 */12 * * *", "0 0 * * *", "0 0 * * 0", "0 0 1 * *"): + if html.escape(cron, quote=False) not in page and cron not in page: + bad(f"the page does not list the schedule {cron!r}") + +# The cron route is public, as Vercel's was: requested over HTTP, it runs the +# schedule now and the record moves forward. +before = json.loads(get("/api/data/1h")[2]).get("fetchedAt") or 0 +time.sleep(0.01) +s, _, b = get("/api/cron/1h") +after = json.loads(get("/api/data/1h")[2]).get("fetchedAt") or 0 +if s != 200 or b.decode().strip() != '"OK"' or not after > before: + bad(f"GET /api/cron/1h answered {s} {b[:40]!r} and moved fetchedAt {before} → {after}") + +for path, want, ctype in (("/thumbnail.png", 200, "image/png"), ("/favicon.ico", 200, "image/"), + ("/no-such-page", 404, "text/html")): + s, ct, b = get(path) + if s != want or not ct.startswith(ctype): + bad(f"{path} answered {s} {ct}, want {want} {ctype}") + if path.endswith(".png") and b[:8] != b"\x89PNG\r\n\x1a\n": + bad(f"{path} is not a PNG") + +if problems: + for p in problems: + print(f" ✕ {p}", file=sys.stderr) + sys.exit(1) +print(f" / (the product's name, links, origin and seven schedules), the public cron route,") +print(f" the Open Graph image, the static assets and a 404 — the product's own") +PY + +echo "e2e.test.sh: ok" diff --git a/testing/fixtures/acme.json b/testing/fixtures/acme.json new file mode 100644 index 0000000..4fab39a --- /dev/null +++ b/testing/fixtures/acme.json @@ -0,0 +1,23 @@ +{ + "_comment": [ + "The inputs the placement, leak and e2e gates render with. Acme is not a", + "real site and never becomes one: this tree is placed into a temp", + "directory, asserted against, and deleted. The values are chosen to be", + "AWKWARD rather than tidy — a site name with an apostrophe and an", + "ampersand (both legal in the card's pattern, both special in TypeScript", + "strings and HTML), a hyphenated repo slug that CONTAINS a word of the", + "baseline's own (`cron`), an owner other than the baseline's, and a", + "multi-label domain — because a fixture that only uses values the", + "templates were written against proves the templates work on the values", + "they were written against.", + "Every key here is an input repo-blueprint.yaml declares. A key it does not", + "declare is a fixture that has drifted, and orun refuses it." + ], + "reponame": "acme-cron-jobs", + "productname": "Sam's Crons & Schedules", + "productdomain": "crons.acme.dev", + "githuborg": "acme-inc", + "subdomain": "acme", + "orunWorkspace": "ws_0000000000000000000000000000000f", + "epicSlug": "cron-baselining" +} diff --git a/testing/fixtures/baseline-identity.cron-starter.json b/testing/fixtures/baseline-identity.cron-starter.json new file mode 100644 index 0000000..404ebc0 --- /dev/null +++ b/testing/fixtures/baseline-identity.cron-starter.json @@ -0,0 +1,9 @@ +{ + "_comment": "THE IDENTITY testing/rebrand.test.sh PINS ITS FIXTURES TO. That suite tests the rename ENGINE, and its fixtures spell this baseline's identity out literally; passed as --baseline-identity, a later change to .baseline/identity.json (a baseline promoted under a new name) cannot silently turn every case into a comparison against the wrong FROM side.", + "slug": "cron-starter", + "pascal": "CronStarter", + "productName": "Cron Triggers on Cloudflare", + "domain": "cron-starter.example.com", + "subdomain": "your-workers-subdomain", + "githubOwner": "sourceplane" +} diff --git a/testing/leak.test.sh b/testing/leak.test.sh new file mode 100755 index 0000000..269811c --- /dev/null +++ b/testing/leak.test.sh @@ -0,0 +1,166 @@ +#!/usr/bin/env bash +# THE LEAK GATE — what a site carries, and what stays in the factory. +# +# A site built from this baseline is somebody's site, not a copy of this +# repository. It gets the product: the app, its KV root, its tests, its CI, +# its tooling, its README and its two context pages. It does NOT get the +# factory: the blueprints, the bootstrap and rebrand tooling, the test gates, +# the task contracts and identity under `.baseline/`, this repository's own +# epic and task tree, or BOOTSTRAP.md — and no file it does get may so much +# as NAME one of those paths, because in the product they do not exist. +# +# This asks orun to DERIVE the placement — every file every phase would write +# — and gates that set and the sources it is copied from. Derivation runs no +# hooks, contacts nothing and writes nothing. testing/placement.test.sh gates +# the same rules over a tree that is actually placed and branded. +# +# Needs: orun + python3. No network, no credential. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +command -v orun >/dev/null || { echo "leak.test.sh needs orun on PATH" >&2; exit 1; } + +scratch="$(mktemp -d)" +trap 'rm -rf "$scratch"' EXIT + +echo "── deriving what every phase would place" +sets=() +while IFS=$'\t' read -r k v; do sets+=( --set "$k=$v" ); done < <( + python3 - "$here/fixtures/acme.json" <<'PY' +import json, sys +for k, v in json.load(open(sys.argv[1])).items(): + if not k.startswith("_"): + print(f"{k}\t{'true' if v is True else 'false' if v is False else v}") +PY +) +orun new --blueprint "$root/repo-blueprint.yaml" --status --json \ + --out "$scratch/empty" "${sets[@]}" > "$scratch/status.json" + +# intent.yaml's `work:` block names this repository's epic and task tree; the +# product's copy has it stripped by a 01-product hook before it lands, so the +# source is gated as the product receives it. +cp "$root/intent.yaml" "$scratch/intent.yaml" +node "$root/tooling/bootstrap/work-tree.mjs" --strip --file "$scratch/intent.yaml" >/dev/null + +python3 - "$scratch/status.json" "$root" "$scratch/intent.yaml" <<'PY' +import json, pathlib, re, sys +import yaml + +status = json.load(open(sys.argv[1])) +root = pathlib.Path(sys.argv[2]) +stripped_intent = pathlib.Path(sys.argv[3]) +problems = [] +def bad(m): problems.append(m) + +# Against an empty output directory every file a phase places is "missing", so +# the union of those lists IS the site's file set. +placed = sorted({f for ph in status["phases"] for f in (ph.get("missing") or [])}) +if len(placed) < 50: + sys.exit(f"only {len(placed)} files derived — the tree is not a site") + +# ── the context pack, exactly ───────────────────────────────────────────── +ALLOWED_AI = {"ai/context/deployment.md", "ai/context/operations.md"} +shipped_ai = {p for p in placed if p.startswith("ai/")} +for extra in sorted(shipped_ai - ALLOWED_AI): + bad(f"{extra} ships to the site and is this repository's own state") +for missing in sorted(ALLOWED_AI - shipped_ai): + bad(f"{missing} is declared a product file and would not ship") + +# ── the factory never ships ─────────────────────────────────────────────── +NEVER = (".baseline/", "specs/", "tasks/", "testing/", "hooks/", "docs/phases/", + "tooling/rebrand/", "tooling/bootstrap/", ".github/workflows/baseline.yml", + ".github/workflows/tag.yml", "BOOTSTRAP.md", "repo-blueprint.yaml", + "blueprint.yaml", "flows/", "agents/") +for p in placed: + for never in NEVER: + if p == never or p.startswith(never): + bad(f"{p} would ship — it is the factory, not the site") + +# ── nothing local and nothing built ─────────────────────────────────────── +LOCAL = re.compile(r"(^|/)(\.env(\.[^/]*\.local|\.local)?|\.dev\.vars(\..*)?|node_modules|\.next|" + r"\.open-next|\.wrangler|\.turbo|\.orun|\.terraform|next-env\.d\.ts|[^/]*\.tsbuildinfo|" + r"[^/]*\.tfstate(\.backup)?|\.terraform\.lock\.hcl)(/|$)") +for p in placed: + if LOCAL.search(p): + bad(f"{p} would ship — a local or built file of whoever ran the bootstrap") + +# ── the site's README, not this repository's ────────────────────────────── +if "README.md" not in placed: + bad("README.md would not ship") +for must in (".github/workflows/ci.yml", ".github/workflows/checks.yml", + "apps/web/component.yaml", "apps/web/lib/site.ts", "tests/web/component.yaml", + ".rebrand/values.json", "apps/web/.env.example", "packages/.gitkeep", + # the cron path: the Worker's custom entry (wrangler `main`), the + # scheduled handler it adds, and the table of the seven schedules + "apps/web/worker.ts", "apps/web/lib/scheduled.ts", "apps/web/lib/crons.ts", + # the wiring path: the template, its fixture, the committed render + # the deploy lane checks for, and the renderer the build calls + "apps/web/wrangler.template.jsonc", "apps/web/wiring.fixture.json", + "apps/web/wrangler.jsonc", "tooling/wire/live.mjs", "tooling/wire/render.mjs", + # the KV root the page binds + "infra/terraform/cloudflare-kv/component.yaml", + "infra/terraform/cloudflare-kv/terraform/main.tf", + "infra/terraform/cloudflare-kv/terraform/adopt.tf"): + if must not in placed: + bad(f"{must} would not ship, and a site needs it") + +# ── no shipped file names the factory ───────────────────────────────────── +# Read from the SOURCE each placed file is copied from (the module's `from`). +# A product's file that points a reader at `testing/` or `repo-blueprint.yaml` +# points at nothing: those paths do not exist in the product. +FACTORY = re.compile(r"repo-blueprint|BOOTSTRAP\.md|(?<![\w-])(testing|specs|tasks|docs/phases|" + r"tooling/rebrand|tooling/bootstrap)/|(?<![\w/])\.baseline/") +bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text()) +sources = [] +for m in bp.get("modules") or []: + if m.get("mode") != "copy": + continue + frm, to = (m.get("from") or "").rstrip("/"), (m.get("to") or "").rstrip("/") + for p in placed: + if p == to or p.startswith(to + "/"): + sources.append((p, frm + p[len(to):])) +scanned = 0 +for shipped, src in sources: + path = stripped_intent if src == "intent.yaml" else root / src + try: + text = path.read_text() + except (UnicodeDecodeError, FileNotFoundError): + continue + scanned += 1 + for n, line in enumerate(text.splitlines(), 1): + if FACTORY.search(line): + bad(f"{shipped} (from {src}:{n}) names a factory path: {line.strip()[:90]}") +if scanned < 40: + bad(f"only {scanned} shipped sources scanned for factory paths — this check has gone blind") + +# ── PROVENANCE, which rebrand has no rule for ───────────────────────────── +# Not a search for this baseline's name: the rebrand rewrites that, and this +# gate reads the sources before it runs. What the rebrand cannot rewrite is a +# sentence about where the site CAME FROM, or one about being a baseline. +PROVENANCE = re.compile( + r"\bfork(ed)? (of|from)\b|\bbaseline (repo|repository|commit|tag)\b|\bthis baseline\b" + r"|BOOTSTRAP\.md|repo-blueprint|specs/epics|\.baseline/", + re.I, +) +SOURCES = {"README.md": ".baseline/product/README.md", + "ai/context/operations.md": "ai/context/operations.md", + "ai/context/deployment.md": "ai/context/deployment.md"} +for shipped, src in SOURCES.items(): + for n, line in enumerate((root / src).read_text(errors="replace").splitlines(), 1): + if PROVENANCE.search(line): + bad(f"{shipped} (from {src}:{n}) tells the site about the factory: {line.strip()[:80]}") + +if problems: + print("FAIL: the site would carry the baseline:", file=sys.stderr) + for p in problems: + print(f" - {p}", file=sys.stderr) + sys.exit(1) + +print(f" {len(placed)} files derived across every phase") +print(f" ai/context is exactly {len(ALLOWED_AI)} declared file(s); none of the " + f"{len(NEVER)} factory paths; nothing local or built; no provenance prose") +print(f" {scanned} shipped sources name no factory path") +PY + +echo "leak.test.sh: ok" diff --git a/testing/lib/bootstrap.sh b/testing/lib/bootstrap.sh new file mode 100644 index 0000000..43bfd4e --- /dev/null +++ b/testing/lib/bootstrap.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# The offline bootstrap: every phase of repo-blueprint.yaml, placed by orun and +# finished by the blueprint's own `run:` hooks, in order, the way a real +# `orun new --run-hooks --resume` takes a site from nothing to its last +# landing — minus the platform. Sourced by placement.test.sh and e2e.test.sh. +# +# bootstrap_offline <root> <tree> <values.json> <log-dir> [until-phase] +# +# What stands in for the platform: +# - the typed actions (`uses:` — task, repo, reconcile, land, watch, probe) +# are skipped; a landing becomes a commit on `main`, which is what the +# next phase's placement sees on the real thing too; +# - `link` (a `run:` hook that calls `orun cloud`) is skipped — it needs a +# workspace; +# - `{{ .inputs.* }}` render from the fixture. +# Everything else — the rebrand, the re-tenant, the work-tree strip, the +# deferrals and their restore, the retouch marker, the lockfile seed and +# prune, the deployment-docs render — runs exactly as declared. +# +# Needs: orun, node, pnpm, python3 (+PyYAML), git. + +bootstrap_offline() { + local root="$1" tree="$2" values="$3" logs="$4" until="${5:-}" + local sets=() k v phase + while IFS=$'\t' read -r k v; do sets+=( --set "$k=$v" ); done < <( + python3 - "$values" <<'PY' +import json, sys +for k, v in json.load(open(sys.argv[1])).items(): + if not k.startswith("_"): + print(f"{k}\t{'true' if v is True else 'false' if v is False else v}") +PY + ) + mkdir -p "$tree"/{apps,infra,packages,tests} "$logs" + for d in apps infra packages tests; do touch "$tree/$d/.gitkeep"; done + + for phase in $(python3 -c "import yaml,sys;print(' '.join(p['name'] for p in yaml.safe_load(open(sys.argv[1]))['phases']))" "$root/repo-blueprint.yaml"); do + echo "── $phase: place" + if ! orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" --phase "$phase" \ + "${sets[@]}" > "$logs/place-$phase.log" 2>&1; then + echo "FAIL: $phase did not place" >&2; tail -20 "$logs/place-$phase.log" >&2; return 1 + fi + echo "── $phase: post hooks" + if ! python3 "$root/testing/lib/run-hooks.py" "$root/repo-blueprint.yaml" "$phase" post \ + "$tree" "$root" "$values" --skip link > "$logs/hooks-$phase.log" 2>&1; then + echo "FAIL: $phase's post hooks" >&2; tail -30 "$logs/hooks-$phase.log" >&2; return 1 + fi + sed 's/^/ /' "$logs/hooks-$phase.log" + # The landing: what the PR merges is what the next phase is placed onto. + ( + cd "$tree" + git config user.email bootstrap@example.invalid + git config user.name "offline bootstrap" + git checkout -q -B main 2>/dev/null || true + git add -A + git commit -q -m "land $phase" --allow-empty + ) || { echo "FAIL: $phase did not commit" >&2; return 1; } + [ "$phase" = "$until" ] && break + done + return 0 +} diff --git a/testing/lib/run-hooks.py b/testing/lib/run-hooks.py new file mode 100755 index 0000000..31a1ea3 --- /dev/null +++ b/testing/lib/run-hooks.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Run one phase's `run:` hooks EXACTLY as repo-blueprint.yaml declares them. + + run-hooks.py <blueprint> <phase> <slot> <tree> <baseline-dir> <values.json> [--skip id,id] + +The offline bootstrap (testing/lib/bootstrap.sh) uses this so that what it +exercises is the blueprint's own hook list, not a transcription of it: a hook +added, removed or reordered in the blueprint is added, removed or reordered +here with no edit. Argv templates are rendered the way orun renders them for +the hooks this baseline uses — `{{ .baseline.dir }}`, `{{ .phase.name }}`, +`{{ .inputs.<key> }}` — and anything else left between braces is an error, so +a hook that starts using a template this cannot render fails loudly rather +than running with a literal `{{ … }}` in its argv. + +`uses:` hooks are the platform's typed actions (task, repo, land, watch, +probe, reconcile). They need a workspace and the network, and are reported as +skipped; the caller stands in for the ones whose effect the tree needs (a +landing is a commit). +""" +import json +import pathlib +import re +import subprocess +import sys + +import yaml + + +def main() -> int: + args = sys.argv[1:] + skip = set() + if "--skip" in args: + i = args.index("--skip") + skip = {s for s in args[i + 1].split(",") if s} + args = args[:i] + args[i + 2:] + blueprint, phase_name, slot, tree, baseline_dir, values_path = args + bp = yaml.safe_load(pathlib.Path(blueprint).read_text()) + phase = next((p for p in bp.get("phases") or [] if p.get("name") == phase_name), None) + if phase is None: + print(f"run-hooks: no phase {phase_name!r}", file=sys.stderr) + return 2 + inputs = {k: v for k, v in json.loads(pathlib.Path(values_path).read_text()).items() if not k.startswith("_")} + + def render(arg: str) -> str: + out = arg.replace("{{ .baseline.dir }}", baseline_dir).replace("{{ .phase.name }}", phase_name) + out = re.sub(r"\{\{ \.inputs\.([A-Za-z0-9_]+) \}\}", lambda m: str(inputs.get(m.group(1), "")), out) + if "{{" in out: + raise SystemExit(f"run-hooks: cannot render {arg!r} — a template this harness does not know") + return out + + for hook in ((phase.get("hooks") or {}).get(slot) or []): + hid = hook.get("id") + if "uses" in hook: + print(f" · {phase_name}/{slot}/{hid}: {hook['uses']} (platform action — skipped offline)") + continue + if hid in skip: + print(f" · {phase_name}/{slot}/{hid}: skipped by the caller") + continue + argv = [render(a) for a in hook.get("run") or []] + print(f" ▸ {phase_name}/{slot}/{hid}") + r = subprocess.run(argv, cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + for line in (r.stdout or "").splitlines()[-6:]: + print(f" {line}") + if r.returncode != 0: + print(f"run-hooks: {phase_name}/{slot}/{hid} exited {r.returncode}", file=sys.stderr) + print(r.stdout, file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/testing/lib/stage-job.py b/testing/lib/stage-job.py new file mode 100755 index 0000000..1f80c10 --- /dev/null +++ b/testing/lib/stage-job.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Stage a job's private tree the way orun's runner does. + + stage-job.py <source-tree> <work-dir> [--shared-deps] + +orun runs every job of a run in an isolated copy of the source checkout, +`.orun/runs/<exec>/<job>/work` (orun internal/runner/workspace.go, +`materializeTree`). What it does with installed dependencies depends on the +composition the component's lane runs: + + default the job installs them itself, so `node_modules` is left out + at every level and the job's install step recreates it + INSIDE the work tree (stack-tectonic < 0.20.0, or a + composition with no lane-scoped install); + --shared-deps a `scope: lane` install ran once in the source checkout + (stack-tectonic >= 0.20.0, orun >= 2.78.2): the TOP-LEVEL + `node_modules` is a SYMLINK to the source tree's, and every + nested one is COPIED with its pnpm symlinks intact — so they + resolve up through that link, OUT of the work tree. + +Either way `.git` and `.orun` are left out, and so are build outputs and +caches (.next, .nuxt, .turbo, .svelte-kit, dist, build, target, .venv, venv, +__pycache__, .terraform, .pytest_cache, .mypy_cache). + +Why a test builds here rather than in a plain checkout: the first live +bootstrap of this baseline died in the --shared-deps layout — Next.js 16's +Turbopack refuses a dependency that resolves outside its project root +("Symlink … points out of the filesystem root") — in a lane that +testing/e2e.test.sh had run green over a plain checkout. +""" +import os +import shutil +import sys + +OUTPUT_DIRS = {".next", ".nuxt", ".turbo", ".svelte-kit", "dist", "build", "target", + ".venv", "venv", "__pycache__", ".terraform", ".pytest_cache", ".mypy_cache"} +SKIP = {".git", ".orun"} + + +def stage(src: str, dst: str, top: bool, shared_deps: bool) -> None: + os.makedirs(dst, exist_ok=True) + for entry in os.scandir(src): + name = entry.name + s, d = entry.path, os.path.join(dst, name) + if name in SKIP: + continue + if entry.is_symlink(): + os.symlink(os.readlink(s), d) + continue + if entry.is_dir(): + if name in OUTPUT_DIRS: + continue + if name == "node_modules": + if not shared_deps: + continue # the job installs its own + if top: + os.symlink(os.path.abspath(s), d) # the lane's one install + else: + shutil.copytree(s, d, symlinks=True) # copied, links intact + continue + stage(s, d, False, shared_deps) + continue + shutil.copy2(s, d) + + +def main() -> int: + args = sys.argv[1:] + shared = "--shared-deps" in args + paths = [a for a in args if a != "--shared-deps"] + if len(paths) != 2: + print("usage: stage-job.py <source-tree> <work-dir> [--shared-deps]", file=sys.stderr) + return 2 + src, dst = (os.path.abspath(p) for p in paths) + if os.path.exists(dst): + print(f"stage-job: {dst} exists", file=sys.stderr) + return 2 + stage(src, dst, True, shared) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/testing/manifest.test.sh b/testing/manifest.test.sh new file mode 100755 index 0000000..3fd6af8 --- /dev/null +++ b/testing/manifest.test.sh @@ -0,0 +1,432 @@ +#!/usr/bin/env bash +# The manifest must state what THE BLUEPRINT does (saas-bootstrap-console +# BC2/BC3; repointed from the flows by saas-bootstrap-engine BE4). +# +# `blueprint.yaml` is the contract the platform's bootstrap door reads and the +# console renders screen for screen. A manifest that drifts is a console that +# lies — showing an operator secrets that will not be created, or a programme +# that will not be laid out, with nothing failing until a customer's build is +# already running. +# +# Every check compares the manifest to THE THING THAT DOES THE WORK, never to +# another copy of the same claim. `spec.source.tag` sat at `baseline-v1` against +# a live `baseline-v4` for three releases (and `baseline-v17` against +# `baseline-v27` in lumen — ten) because nothing compared it to anything that +# moved. A drift test between two files catches nothing. +# +# ## What the thing that does the work IS, now +# +# It used to be shell: `flows/common/create-secrets.sh`'s `create` calls, and +# the umbrella's `ensure-milestone` lines, grepped out of scripts. BE4 deleted +# those, and the work moved into `repo-blueprint.yaml` — so this file now reads +# the blueprint's own hooks. +# +# That is a STRONGER comparison, not a weaker one. Grepping a shell script for +# `create FOO cloudflare … workers-deploy` matched a line's shape; reading +# `orun.integrations/reconcile@v1`'s `with:` reads the declaration orun actually +# executes. The action's own documentation says as much — "a script walks that +# table calling create for each … it is a reconcile written out longhand, and +# this is the verb it was reaching for". +# +# TWO SHAPES OF REPO, one test. A repo may carry more than one baseline: stratus +# serves both the `stratus` and `stratus-coolify` registry rows from one tree. +# So every `blueprint*.yaml` at the root is checked. +# +# And a baseline need not have every mechanism. Stratus mints no secrets and +# lays out no milestones, so it declares neither block. That is allowed — but +# only BOTH-OR-NEITHER, checked in both directions: if the mechanism exists the +# block must match it, and if the block exists the mechanism must be there to +# realize it. "Absent" is never permission to skip a check silently; it is a +# fact that must agree with the other side. +# +# bash + python3 + PyYAML. No network, no fakes, no credential. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +echo "── blueprint manifests against the blueprint that realizes them" +python3 - "$root" <<'PY' +import pathlib, re, sys + +try: + import yaml +except ImportError: + sys.exit("PyYAML is required for the manifest contract test (pip install pyyaml)") + +root = pathlib.Path(sys.argv[1]) +problems = [] +def bad(m): problems.append(m) + +manifests = sorted(root.glob("blueprint*.yaml")) +if not manifests: + sys.exit("no blueprint*.yaml at the repo root — this check has gone blind") + +# ── what the blueprint actually mints, and what it actually lays out ────── +# +# One read of `repo-blueprint.yaml`, shared across a repo's baselines. A repo +# with no blueprint at the root has no mechanism to compare against, and that +# is a fact the both-or-neither rule below handles rather than a reason to skip. +bp_path = root / "repo-blueprint.yaml" +bp = yaml.safe_load(bp_path.read_text()) if bp_path.exists() else None +bp_phases = (bp or {}).get("phases") or [] + +def hooks_of(phase): + """Every hook a phase declares, in the order orun runs them.""" + h = phase.get("hooks") or {} + if isinstance(h, list): + return list(h) + return [x for slot in ("pre", "post", "await") for x in (h.get(slot) or [])] + +def uses(phase, action): + for hook in hooks_of(phase): + if (hook.get("uses") or "").startswith(action): + yield hook + +# THE SECRETS THE BOOTSTRAP MINTS. `orun.integrations/reconcile@v1` is what +# `create-secrets.sh` was written out longhand as: one connection, one scope +# template, the keys it ensures. Read per key so a hook minting two keys under +# one template is three facts rather than one. +blueprint_secrets = {} +for phase in bp_phases: + for hook in uses(phase, "orun.integrations/reconcile@v1"): + w = hook.get("with") or {} + for key in (w.get("keys") or []): + blueprint_secrets[key] = (w.get("provider"), w.get("template")) + +if bp is not None and not bp_phases: + bad("repo-blueprint.yaml declares no phases — this check has gone blind") + +checked = [] +for path in manifests: + name = path.name + spec = (yaml.safe_load(path.read_text()) or {}).get("spec") or {} + def B(m): bad(f"{name}: {m}") + + # ── the field that cannot be true ───────────────────────────────────── + if "tag" in (spec.get("source") or {}): + B("spec.source.tag is back. The registry pins the tag; this file is fetched at it.") + + # ── blocks every baseline must carry ────────────────────────────────── + for key in ("source", "overview", "requires", "inputs", "bootstrap"): + if key not in spec: + B(f"spec.{key} is missing — the console renders it") + + # ── inputs v3: every input is collected by the console (BE3) ────────── + # + # `askedBy` is gone with the agent. It split inputs into ones a form + # collects and ones asked for in a session, and the second half no longer + # exists — so the field could only ever hold one value. + # + # The exemption it carried is what these checks replace: an `askedBy: + # agent` input needed no `pattern`, because prose asked for it and prose + # does not validate. + input_keys = {f.get("key") for f in (spec.get("inputs") or [])} + ACTION_ID = re.compile(r"^[a-z][a-z0-9.]*/[a-z][a-z0-9-]*@v[0-9]+$") + REBRAND = "tooling/rebrand/rebrand.mjs" + # THE KEY CHARSET THE PLATFORM'S PARSER ENFORCES, mirrored here. + # + # `INPUT_KEY_RE = /^[a-z][a-z0-9_]{0,38}$/` in orun-cloud's + # `blueprint-manifest.ts`. Nothing in this repository ran that parser: the + # `blueprint-parses` job reads `repo-blueprint.yaml` with ORUN, which + # accepts camelCase happily, and this file is a hand-rolled reader of the + # card. So a card key orun likes and the platform refuses passed every + # check here and failed at the pin: + # + # line 98: input key "githubOrg" must be lowercase letters, digits + # and underscores + # + # It cost a baseline tag — v6 was already cut and a baseline tag is never + # moved — which is the whole argument for mirroring the rule rather than + # trusting that the two readers agree. + # + # It also constrains `repo-blueprint.yaml`: a card key must be an input the + # blueprint accepts (checked below), so any input the CARD declares must be + # named in this charset on BOTH sides. The blueprint's own camelCase + # inputs — `epicSlug`, `orunWorkspace`, `pascalName` — are untouched, + # because the card does not declare them. + INPUT_KEY = re.compile(r"^[a-z][a-z0-9_]{0,38}$") + for i, field in enumerate(spec.get("inputs") or []): + key = field.get("key", f"#{i}") + if not INPUT_KEY.match(str(key)): + B(f"inputs[{key}] is not a key the platform's parser accepts — it " + f"must match ^[a-z][a-z0-9_]{{0,38}}$ (lowercase letters, digits " + f"and underscores). The console would refuse the whole manifest.") + if "askedBy" in field: + B(f"inputs[{key}] declares askedBy — there is no agent to ask, so " + f"every input is collected by the console") + if not field.get("pattern"): + B(f"inputs[{key}] declares no pattern — it is collected in a form " + f"and validated before Continue, so it must say what a valid " + f"value looks like") + + # from / derive / probe each answer "where does this value come from + # when nobody types it". Two of them is two answers. + sources = [k for k in ("from", "derive", "probe") if k in field] + if len(sources) > 1: + B(f"inputs[{key}] declares {' and '.join(sources)} — an input has " + f"one source") + + # A derivation must name inputs this manifest actually declares. + derive = field.get("derive") + if derive is not None: + refs = re.findall(r"\{([a-z][a-z0-9_]*)\}", derive) + if not refs: + B(f"inputs[{key}].derive has no {{key}} reference — a constant " + f"is a default, not a derivation") + for ref in refs: + if ref == key: + B(f"inputs[{key}].derive references itself") + elif ref not in input_keys: + B(f"inputs[{key}].derive references {{{ref}}}, which is not " + f"a declared input") + + # A DERIVATION HAS A SECOND IMPLEMENTATION, and they must agree. + # + # `rebrand.mjs` has computed this value since long before the manifest + # could say so: + # + # const apibaseurl = values.apibaseurl ?? `https://api.${productdomain}`; + # + # Both paths are live. The console resolves `derive` and the flow hands + # it down, so on a console bootstrap the manifest's rule wins; a phase + # run by hand passes nothing and rebrand's fallback wins. One rule, two + # implementations — which is the thing this file's header warns about, + # unless something holds them equal. This does. + if derive is not None and (root / REBRAND).exists(): + js = (root / REBRAND).read_text(errors="replace") + for m in re.finditer(r"const (\w+) = values\.\w+ \?\? `([^`]+)`", js): + # `${productdomain}` there is `{productdomain}` here. + want = re.sub(r"\$\{([A-Za-z]+)\}", lambda g: "{" + g.group(1).lower() + "}", m.group(2)) + if m.group(1).lower() == key and want != derive: + B(f"inputs[{key}].derive is {derive!r} and {REBRAND} falls back " + f"to {want!r} — one value, two rules, and which one a " + f"product gets depends on whether the console resolved it") + + # A probe names an orun action. Shape only — this repository does not + # own the registry and cannot know which ids a runner has. The id being + # WELL-FORMED is what it can check; whether it is REGISTERED is the + # runner's answer, at parse time, where the real list lives. + probe = field.get("probe") + if probe is not None: + uses = (probe or {}).get("uses") + if not uses or not ACTION_ID.match(uses): + B(f"inputs[{key}].probe.uses is {uses!r} — not an action id " + f"(<namespace>/<verb>@v<major>)") + + # `from` says the CONSOLE already holds this value, so it renders no + # field for it (saas-bootstrap-console BC-K5). Two ways to get it + # wrong, and the platform refuses both — check them here too, so the + # mistake is caught in this repo rather than at a live bootstrap. + src = field.get("from") + if src is not None and src not in ("repo.name", "repo.owner", "repo.fullName"): + B(f"inputs[{key}].from is {src!r} — must be repo.name, repo.owner or repo.fullName") + + # ── secrets: BOTH or NEITHER, checked both ways ─────────────────────── + declared = {s.get("key"): (s.get("provider"), s.get("template")) for s in (spec.get("secrets") or [])} + if bp is None: + if declared: + B(f"declares {len(declared)} secret(s) but the repo has no " + f"repo-blueprint.yaml to mint them") + elif not blueprint_secrets: + if declared: + B(f"declares {len(declared)} secret(s) and repo-blueprint.yaml has no " + f"orun.integrations/reconcile@v1 hook to mint any") + else: + if "secrets" not in spec: + B("repo-blueprint.yaml mints keys and the manifest declares no secrets") + for k in sorted(set(blueprint_secrets) - set(declared)): + B(f"repo-blueprint.yaml mints {k} and the manifest does not declare it") + for k in sorted(set(declared) - set(blueprint_secrets)): + B(f"declares secret {k} and repo-blueprint.yaml never mints it") + for k in sorted(set(blueprint_secrets) & set(declared)): + if blueprint_secrets[k] != declared[k]: + B(f"{k}: manifest says provider/template {declared[k]}, " + f"repo-blueprint.yaml mints it as {blueprint_secrets[k]}") + + # ── bootstrap: what is left of it, and what BE4 removed ─────────────── + # + # `umbrella` and `agentBrief` named two files BE4 deleted. orun-cloud + # BE-K1c made both OPTIONAL in the manifest contract for exactly this, so + # this file no longer declares them — and must not, because a path that + # does not exist is the drift this whole test is about. + boot = spec.get("bootstrap") or {} + for field in ("umbrella", "agentBrief"): + rel = boot.get(field) + if rel is None: + continue + B(f"bootstrap.{field} is back, naming {rel}. The shell layer is gone " + f"(BE4): every phase is declared in repo-blueprint.yaml and orun runs " + f"it, so there is no umbrella to name and no session to brief.") + if not boot.get("expectedMinutes"): + B("bootstrap.expectedMinutes is missing — the console renders it") + + # ── …and what BE-K1e added in their place ───────────────────────────── + # + # With no umbrella and no brief, `blueprint` is the ONLY entry point: it + # names the document whose phases a runner places after fetching this repo + # at its pinned tag. The registry row's `manifestPath` names the console + # CARD — this file — so without this key a runner has nothing to run. + # + # Checked the way everything else here is checked: against the thing that + # does the work, not against another copy of the claim. The file must + # exist, and it must be the one that actually declares the phases — a path + # to some other YAML would satisfy a mere existence check and fail a real + # bootstrap at the only moment that matters. + build = boot.get("blueprint") + if not build: + B("bootstrap.blueprint is missing. This baseline has no umbrella and " + "no agentBrief (BE4), so nothing else names the document a runner " + "places — a fetch at the pinned tag would find no entry point.") + else: + target = root / build + if not target.is_file(): + B(f"bootstrap.blueprint names {build}, which does not exist") + else: + try: + doc = yaml.safe_load(target.read_text()) or {} + except yaml.YAMLError as exc: + doc = {} + B(f"bootstrap.blueprint names {build}, which does not parse: {exc}") + if doc and not (doc.get("phases") or (doc.get("spec") or {}).get("phases")): + B(f"bootstrap.blueprint names {build}, which declares no phases. " + f"A runner would fetch it and place nothing.") + if doc and doc.get("kind") != "Blueprint": + B(f"bootstrap.blueprint names {build}, whose kind is " + f"{doc.get('kind')!r} rather than Blueprint") + + # ── every declared input is one the BLUEPRINT accepts ───────────────── + # + # This used to check the manifest's keys against the UMBRELLA's inputs, + # because a flow was what consumed them and orun's flow engine fails closed + # on an undeclared `--set`. The blueprint is what consumes them now, and it + # fails closed the same way: + # + # ✕ unknown input "reponame" (not declared in blueprint inputs) + # + # That equivalence is why open question 10 had to be settled in the same + # commit that deleted the flows: the umbrella's lowercase input names were + # the ONLY thing translating this file's keys into the blueprint's + # camelCase ones, so deleting it without renaming would have left every key + # refused. + # + # ONE DIRECTION ONLY. The blueprint declares more than this file does — + # `githuborg`, `epicSlug`, `domain`, `orunWorkspace` and the identity + # defaults are how a BUILD is driven, not what a product is configured + # with. What must hold is that nothing this file declares arrives at an + # engine that cannot take it. + if bp is not None: + bp_inputs = set((bp.get("inputs") or {}).keys()) + if not bp_inputs: + B("repo-blueprint.yaml declares no inputs — this check has gone blind") + for key in [f.get("key") for f in (spec.get("inputs") or [])]: + if key and key not in bp_inputs: + B(f"inputs[{key}] is not an input of repo-blueprint.yaml — the " + f"console would resolve it and the engine would refuse it " + f"(orun fails closed on an undeclared --set)") + + # ── …AND THE OTHER DIRECTION, for REQUIRED inputs only ─────────────── + # + # The check above is one-directional on purpose: the blueprint declares + # more than this card does, because `epicSlug`, `domain` and the identity + # defaults are how a BUILD is driven rather than what a product is + # configured with. That tolerance had no floor, and `githuborg` fell + # through it — `required: true` in the blueprint, absent from this card, + # so a platform build resolved the card's inputs, handed them to the + # runner and died on its first step: + # + # ✕ input "githuborg" is required + # + # An input the blueprint REQUIRES and gives no default to is one somebody + # must supply, and the only things that supply inputs to a hosted build + # are this card's fields and its `from`/`derive` sources. So "more" may + # not include one of those. + # + # Defaulted inputs stay out of it: a default IS the supply. + if bp is not None: + for key, spec_in in (bp.get("inputs") or {}).items(): + if not isinstance(spec_in, dict): + continue + if not spec_in.get("required"): + continue + if "default" in spec_in: + continue + if key not in input_keys: + B(f"repo-blueprint.yaml requires input {key!r} and gives it no " + f"default, and this card does not declare it — a hosted build " + f"would collect every field it shows and still die with " + f'\'input "{key}" is required\'') + + # ── programme: BOTH or NEITHER, against the blueprint's own hooks ───── + # + # A milestone is what a phase CLUBS ITS TASK UNDER, which the phase states + # as `orun.task/ensure@v1`'s `milestone:`, which is why a phase that is + # the second landing of one unit of work would name its predecessor's + # milestone rather than one of its own (`04-workers-restore` did, before + # the bootstrap folded it into `05-edge`). + # + # Distinct, in phase order. The old check grepped the umbrella's + # `ensure-milestone` lines for the same list. + ensured, seen = [], set() + for phase in bp_phases: + for hook in uses(phase, "orun.task/ensure@v1"): + # Not `name`: that is the manifest's file name, which the summary + # line below prints (it printed the last milestone instead). + ms_name = ((hook.get("with") or {}).get("milestone") or "") + ms_name = ms_name.replace("{{ .phase.name }}", phase.get("name", "")).strip() + if ms_name and ms_name not in seen: + seen.add(ms_name) + ensured.append(ms_name) + + # A phase's `when:` is what made a milestone conditional; the umbrella + # carried the same fact as a shell `[ != "true" ] ||` guard. + conditional = { + p_["name"] for p_ in bp_phases + if p_.get("when") and p_.get("name") in seen + } + + prog = spec.get("programme") + if not ensured: + if prog: + B("declares a programme but repo-blueprint.yaml opens no milestones") + else: + if not prog: + B(f"repo-blueprint.yaml opens {len(ensured)} milestone(s) and the " + f"manifest declares no programme") + else: + ms = prog.get("milestones") or [] + if any(not isinstance(m, dict) or "name" not in m for m in ms): + B("every programme.milestones entry must be a mapping with a `name` " + "(so a conditional one can carry its `when`)") + else: + names = [m["name"] for m in ms] + dcond = {m["name"] for m in ms if m.get("when")} + if names != ensured: + B(f"programme.milestones {names} != repo-blueprint.yaml's {ensured}") + if dcond != conditional: + B(f"conditional milestones disagree: manifest says {sorted(dcond) or '[]'}, " + f"the blueprint guards {sorted(conditional) or '[]'}") + slug = ((bp.get("inputs") or {}).get("epicSlug") or {}).get("default") + if slug and prog.get("epicSlug") != slug: + B(f"programme.epicSlug {prog.get('epicSlug')!r} != the blueprint's " + f"default {slug!r}") + + # ── verify is optional, but must not name an input that is not there ── + input_keys = {f.get("key") for f in (spec.get("inputs") or [])} | {"env"} + for url in ((spec.get("verify") or {}).get("urls") or []): + for ph in re.findall(r"\{([a-zA-Z0-9_]+)\}", url): + if ph not in input_keys: + B(f"verify url interpolates {{{ph}}}, which is not an input") + + checked.append((name, len(declared), len((prog or {}).get("milestones") or []))) + +if problems: + print("FAIL: a manifest and the blueprint disagree:", file=sys.stderr) + for p in problems: + print(f" - {p}", file=sys.stderr) + sys.exit(1) + +for name, ns, nm in checked: + print(f" {name}: {ns} secret(s), {nm} milestone(s) agree with repo-blueprint.yaml") +PY + +echo "manifest.test.sh: ok" diff --git a/testing/phases.test.sh b/testing/phases.test.sh new file mode 100755 index 0000000..5307316 --- /dev/null +++ b/testing/phases.test.sh @@ -0,0 +1,351 @@ +#!/usr/bin/env bash +# The phases in `repo-blueprint.yaml` must be the phases the bootstrap runs, +# placing what they are meant to place, saying what they are, and naming only +# what the engine can resolve. +# +# The partition below is the bootstrap's order, written down a second time on +# purpose. It is the one-landing shape (cirrus-baseline v22): `01-product` +# places EVERY module and is the one phase that deploys; `02-docs` places +# nothing. The order that used to need separate landings — the KV namespace +# before the Worker that binds it — is carried by the plan instead, and this +# file checks the edges that carry it: every component that reads a wiring +# document waits, on a merge to main, for the infra component that publishes +# it, and the landing's await checks that document exists afterwards. A +# module that drifts into another phase, or an edge that goes missing, fails +# at landing time, live, with nothing in this repository having looked wrong. +# +# Adapted from sourceplane/cirrus-baseline's testing/phases.test.sh: the +# narration rules and the hook-only rule are Cirrus's, unchanged. +# +# bash + python3 + PyYAML. No network, no fakes, no credential. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" + +echo "── repo-blueprint.yaml phases against what the bootstrap runs" +python3 - "$root" <<'PY' +import pathlib, re, sys + +try: + import yaml +except ImportError: + sys.exit("PyYAML is required for the phase contract test (pip install pyyaml)") + +root = pathlib.Path(sys.argv[1]) +problems = [] +def bad(m): problems.append(m) + +bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text()) +phases = bp.get("phases") or [] +if not phases: + sys.exit("repo-blueprint.yaml declares no phases — this check has gone blind") + +PARTITION = { + "01-product": ["ai-deployment", "ai-operations", "cloudflare-kv", "discovery-roots", + "github-workflows", "rebrand-values", "root-gitignore", "root-intent", + "root-kiox", "root-kiox-lock", "root-package-json", "root-pnpm-lock", + "root-pnpm-workspace", "root-readme", "root-turbo", "tooling-eslint", + "tooling-tsconfig", "tooling-wire", "vscode", "web", "web-tests"], + "02-docs": [], +} +HOOK_ONLY = {"02-docs"} +# The phases that DEPLOY, and so must give a re-run something to land. +DEPLOYS = {"01-product"} +# Each phase's post and await hooks, in order — the one-landing recipe. The +# `secret-*` reconciles are matched as a group (one per brokered key) and the +# `wiring` await only when infra publishes wiring; both are checked below. +POST = { + "01-product": ["retouch", "git-init", "stage", "rebrand", "orun-workspace", "work-tree", + "promotion", "dev-lanes", "restage", "rebrand-verify", "pnpm-lockfile", + "repo", "link", "secret-*", "land"], + "02-docs": ["promotion", "dev-lanes", "render", "land"], +} +AWAIT = {"01-product": ["converge", "wiring", "verify"], "02-docs": ["verify"]} + +by_name = {p["name"]: p for p in phases} +names = [p["name"] for p in phases] + +# ── the order IS the execution order ────────────────────────────────────── +if names != sorted(names): + bad(f"phases are not in execution order: {names}. The numbered name IS the " + f"order; a phase out of sequence is a barrier in the wrong place.") +if names != list(PARTITION): + bad(f"phases are {names}; the bootstrap runs {list(PARTITION)}") + +# ── the partition has not drifted ───────────────────────────────────────── +for name, want in PARTITION.items(): + if name not in by_name: + continue + now = sorted(by_name[name].get("modules") or []) + if now != sorted(want): + bad(f"phase {name} no longer places what it placed: gained " + f"{sorted(set(now) - set(want)) or '[]'}, lost {sorted(set(want) - set(now)) or '[]'}") +declared = {m["name"] for m in bp.get("modules") or []} +placed = {m for p in phases for m in (p.get("modules") or [])} +for m in sorted(declared - placed): + bad(f"module {m} is declared and no phase places it") +for name in HOOK_ONLY: + if by_name.get(name, {}).get("modules"): + bad(f"phase {name} places modules — it is declared as hooks only") + +# ── nothing may GATE on a phase the tree cannot answer for ──────────────── +# A hook-only phase places no files, so orun derives it as `unknown`, and +# `requires.phases` fails closed on `unknown`: a requirement naming one can +# never be satisfied. +for p in phases: + for need in ((p.get("requires") or {}).get("phases") or []): + if need in HOOK_ONLY: + bad(f"phase {p['name']} requires {need}, which places no files — require " + f"its predecessor instead") + if need not in by_name or names.index(need) >= names.index(p["name"]): + bad(f"phase {p['name']} requires {need}, which does not run before it") + +# ── every phase says what it is and what to budget ──────────────────────── +for p in phases: + for field in ("title", "expectedMinutes"): + if not p.get(field): + bad(f"phase {p['name']} declares no {field} — an operator reads both") + if not (p.get("hooks") or {}): + bad(f"phase {p['name']} declares no hooks — a phase that only places files " + f"still has to land them") + +def hooks_of(p): + h = p.get("hooks") or {} + if isinstance(h, list): + return list(h) + return [x for slot in ("pre", "post", "await") for x in (h.get(slot) or [])] + +run_hooks = list((bp.get("hooks") or {}).get("preInstantiate") or []) + +# ── every phase lands, and every landing is bound to its task ───────────── +for p in phases: + ids = [h.get("id") for h in hooks_of(p)] + lands = [h for h in hooks_of(p) if (h.get("uses") or "").startswith("orun.pr/land@")] + if len(lands) != 1: + bad(f"phase {p['name']} has {len(lands)} landing(s); a phase is ONE pull request") + continue + w = lands[0].get("with") or {} + if w.get("task") != "{{ .phase.hooks.task.outputs.key }}": + bad(f"phase {p['name']} lands without binding the PR to its task key") + if "task" not in ids or ids.index("task") > ids.index(lands[0].get("id")): + bad(f"phase {p['name']} must ensure its task before it lands") + if p["name"] in DEPLOYS: + if not any("retouch.mjs" in " ".join(h.get("run") or []) for h in hooks_of(p)): + bad(f"phase {p['name']} deploys and has no retouch hook — a re-run after a " + f"failed convergence would land an empty diff and redeploy nothing") + awaits = (p.get("hooks") or {}).get("await") or [] + watch = [h for h in awaits if (h.get("uses") or "").startswith("orun.run/watch@")] + if not watch or (watch[0].get("with") or {}).get("sha") != "{{ .phase.hooks.land.outputs.mergeSha }}": + bad(f"phase {p['name']} deploys and does not watch the convergence of the " + f"commit it merged (orun.run/watch@v1 with sha: mergeSha)") + +# ── the hooks run in the one-landing order ──────────────────────────────── +def collapse(ids): + out = [] + for i in ids: + i = "secret-*" if i.startswith("secret-") else i + if not out or out[-1] != i or i != "secret-*": + out.append(i) + return out +for name, want in POST.items(): + got = collapse([h.get("id") for h in ((by_name.get(name, {}).get("hooks") or {}).get("post") or [])]) + if got != want: + bad(f"phase {name}'s post hooks are {got}; the one-landing order is {want}") +for name, want in AWAIT.items(): + got = [h.get("id") for h in ((by_name.get(name, {}).get("hooks") or {}).get("await") or [])] + if got != want: + bad(f"phase {name}'s await hooks are {got}; want {want}") +for p in phases: + if p["name"] not in DEPLOYS: + for h in hooks_of(p): + if (h.get("uses") or "").startswith(("orun.integrations/reconcile@", "orun.run/watch@")): + bad(f"phase {p['name']} deploys nothing and runs {h['uses']} ({h.get('id')})") + +# ── INFRA BEFORE APP: the order the one landing relies on ───────────────── +# Every infra component that lease-publishes a wiring document +# (`secretOutputs: "WIRING_X=wiring"`), and every component that reads one +# (`WIRING_X_<ENV>` in secretEnv). A reader must wait for its publisher on a +# merge to main — `mode: enforced` — and not on a pull request, which deploys +# nothing (`modeRules` advisory on github-pull-request): a job resolves its +# secrets when it STARTS, so without the edge the first convergence's deploy +# would start before the apply had published the id it binds. +comps = {} +for f in root.rglob("component.yaml"): + if "node_modules" in f.parts: + continue + d = yaml.safe_load(f.read_text()) or {} + comps[(d.get("metadata") or {}).get("name")] = (f.relative_to(root).as_posix(), d.get("spec") or {}) +publishes = {} +for name, (rel, spec) in comps.items(): + outs = str((spec.get("parameters") or {}).get("secretOutputs") or "") + for pair in filter(None, (x.strip() for x in outs.split(","))): + key = pair.split("=", 1)[0] + if key.startswith("WIRING_"): + publishes[key] = name +if not publishes: + bad("no infra component lease-publishes a WIRING_* document — this check has gone blind") +readers = 0 +for name, (rel, spec) in comps.items(): + keys = {re.sub(r"_(DEV|STAGE|PROD)$", "", k) for k in (spec.get("secretEnv") or {}) if k.startswith("WIRING_")} + for key in sorted(keys): + readers += 1 + pub = publishes.get(key) + if not pub: + bad(f"{rel} reads {key}, which no infra component publishes") + continue + edge = next((d for d in spec.get("dependsOn") or [] if d.get("component") == pub), None) + rules = (edge or {}).get("modeRules") or [] + advisory_on_pr = any(r.get("mode") == "advisory" + and ((r.get("when") or {}).get("triggerRef") == "github-pull-request") + for r in rules) + if not edge or edge.get("mode") != "enforced" or not advisory_on_pr: + bad(f"{rel} reads {key} and does not wait for {pub} on a merge to main — declare " + f"dependsOn {pub} with mode: enforced and a modeRules advisory on github-pull-request") + mod = next((m for m in bp.get("modules") or [] if (m.get("from") or "").rstrip("/") == rel.rsplit("/", 1)[0]), None) + pub_mod = next((m["name"] for m in bp.get("modules") or [] + if (m.get("from") or "").rstrip("/") == comps[pub][0].rsplit("/", 1)[0]), None) + if mod and pub_mod and pub_mod not in (mod.get("dependsOn") or []): + bad(f"module {mod['name']} reads {key} and is not placed after {pub_mod} (module dependsOn)") +# …and the landing's await asks the platform that every one of them exists. +for p in phases: + if p["name"] not in DEPLOYS: + continue + exists = [h for h in ((p.get("hooks") or {}).get("await") or []) + if (h.get("uses") or "").startswith("orun.secrets/exists@")] + keys = {k for h in exists for k in ((h.get("with") or {}).get("keys") or [])} + envs = {e for h in exists for e in ((h.get("with") or {}).get("environments") or [])} + if set(publishes) - keys: + bad(f"phase {p['name']} does not await the wiring {sorted(set(publishes) - keys)} with orun.secrets/exists@v1") + if publishes and envs != {"stage", "prod"}: + bad(f"phase {p['name']} awaits the wiring on {sorted(envs)}, not stage and prod") + +# ── every phase's task is one the run-level list opens, in the same order ─ +def task_names(hooks): + return [(h.get("with") or {}).get("name") for h in hooks + if (h.get("uses") or "").startswith("orun.task/ensure@") + and (h.get("with") or {}).get("kind") == "task"] +opened = task_names(run_hooks) +per_phase = [n for p in phases for n in task_names(hooks_of(p))] +if opened != per_phase: + bad(f"the run-level list opens tasks {opened}; the phases ensure {per_phase} — " + f"a task is found by its title, so the two must be the same words") +milestones = [(h.get("with") or {}).get("name") for h in run_hooks + if (h.get("with") or {}).get("kind") == "milestone"] +if milestones != names: + bad(f"the run-level list opens milestones {milestones}; the phases are {names}") + +# ── every contract a hook names exists, beside the blueprint ────────────── +for h in run_hooks + [x for p in phases for x in hooks_of(p)]: + rel = (h.get("with") or {}).get("contract") + if rel and not (root / rel).exists(): + bad(f"hook {h.get('id')} names contract {rel}, which does not exist") + if rel and not rel.startswith(".baseline/tasks/"): + bad(f"hook {h.get('id')} names contract {rel} outside .baseline/tasks/ — " + f"`tasks/` is this repository's own work tree, where an unkeyed " + f"contract is an error") +for p in phases: + for h in hooks_of(p): + argv = " ".join(h.get("run") or []) + for ref in re.findall(r"\{\{ \.baseline\.dir \}\}/(\S+?)(?:\"|'|\s|$)", argv + " "): + if not (root / ref).exists(): + bad(f"phase {p['name']} hook {h.get('id')} runs {ref}, which this " + f"repository does not have") + +# ── every phase has a documentation page, and every page a phase ────────── +docs_dir = root / "docs" / "phases" +pages = {f.stem for f in docs_dir.glob("*.md")} - {"README"} +for n in names: + if n not in pages: + bad(f"phase {n} has no page at docs/phases/{n}.md") +for page in sorted(pages - set(names)): + bad(f"docs/phases/{page}.md documents a phase repo-blueprint.yaml does not declare") + +# ── narration: authored here, printed from state (Cirrus's rules) ───────── +META_AT = { + "start": {"files", "expectedMinutes"}, + "await": {"files", "expectedMinutes"}, + "failed": {"files", "expectedMinutes"}, + "done": {"files", "expectedMinutes", "elapsed", "next"}, +} +STATE_WORDS = {"done", "failed", "complete", "completed", "succeeded", "skipped"} +PHASE_KEYS = {"name", "title"} +input_keys = set((bp.get("inputs") or {}).keys()) + +ws_input = (bp.get("inputs") or {}).get("orunWorkspace") or {} +if ws_input.get("from") != "workspace": + bad("inputs.orunWorkspace must declare `from: workspace` — a console build has no other way to say it") + +def strip_expressions(line): + return re.sub(r"\{\{.*?\}\}", "", line, flags=re.S) + +def refs(line): + found = [] + for expr in re.findall(r"\{\{(.*?)\}\}", line, re.S): + found += re.findall(r"\.([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)", expr) + return found + +def check_line(where, line, slot, hook_ids): + prose = strip_expressions(line).lower() + for w in STATE_WORDS: + if re.search(rf"\b{w}\b", prose): + bad(f"{where} asserts {w!r} — `state` is the truth and narration is the " + f"caption. Describe the world, not the run.") + for ref in refs(line): + parts = ref.split(".") + head = parts[0] + if head == "phase": + if len(parts) != 2 or parts[1] not in PHASE_KEYS: + bad(f"{where} names .{ref}; a phase carries {sorted(PHASE_KEYS)}") + elif head == "inputs": + if len(parts) != 2 or parts[1] not in input_keys: + bad(f"{where} names .{ref}, which is not a declared input") + elif head == "meta": + allowed = META_AT.get(slot, META_AT["start"]) + if len(parts) != 2 or parts[1] not in allowed: + bad(f"{where} names .{ref}; the {slot} event carries {sorted(allowed)}") + elif head == "hooks": + if len(parts) < 2 or parts[1] not in hook_ids: + bad(f"{where} names .{ref}; this phase has no such hook") + else: + bad(f"{where} names .{ref}; narration may reference phase, inputs, meta and hooks") + +for p in phases: + n = p.get("narrate") or {} + ids = {h.get("id") for h in hooks_of(p)} + for slot in ("start", "await", "done", "failed"): + line = n.get(slot) + if not line: + bad(f"phase {p['name']} declares no narrate.{slot}") + continue + check_line(f"phase {p['name']} narrate.{slot}", line, slot, ids) + for h in ((p.get("hooks") or {}).get("await") or []): + line = h.get("narrate") + if not line: + bad(f"phase {p['name']} await hook {h.get('id')} declares no narrate — a " + f"wait with no words reads as a stalled build") + continue + check_line(f"phase {p['name']} hook {h.get('id')} narrate", line, "done", ids) + for slot in ("pre", "post"): + for h in ((p.get("hooks") or {}).get(slot) or []): + if h.get("narrate"): + check_line(f"phase {p['name']} hook {h.get('id')} narrate", h["narrate"], "start", ids) + +# ── what a baseline of this shape never grows back ──────────────────────── +if (root / "flows").exists(): + bad("flows/ exists — the bootstrap is the blueprint; every mechanism is a typed orun action") + +if problems: + print("FAIL: the blueprint's phases and the bootstrap disagree:", file=sys.stderr) + for p in problems: + print(f" - {p}", file=sys.stderr) + sys.exit(1) + +placed_n = sum(len(p.get("modules") or []) for p in phases) +print(f" {len(publishes)} wiring document(s), {readers} reader(s), each waiting for its publisher on main") +narrated = sum(len(p.get("narrate") or {}) for p in phases) +narrated += sum(1 for p in phases for h in hooks_of(p) if h.get("narrate")) +print(f" {len(phases)} phases, {placed_n} modules, {len(HOOK_ONLY)} hook-only — in execution order") +print(f" {narrated} authored narration lines, every reference resolving") +PY + +echo "phases.test.sh: ok" diff --git a/testing/placement.test.sh b/testing/placement.test.sh new file mode 100755 index 0000000..514bc54 --- /dev/null +++ b/testing/placement.test.sh @@ -0,0 +1,367 @@ +#!/usr/bin/env bash +# TIER 1 — the tree is placed, branded, and made to answer. +# +# A real bootstrap is `orun new --run-hooks --resume` against a workspace: it +# places each phase, runs that phase's hooks, lands a pull request and watches +# the convergence. Everything in that sentence except the platform can run +# here, offline, and this file runs it: +# +# 1. the whole blueprint placed in one go — orun runs `validate` and +# `plan --dry-run` inside the produced tree and says so; asserted, because +# a future orun that stopped running them would weaken this tier in silence; +# 2. THE OFFLINE BOOTSTRAP (testing/lib/bootstrap.sh) — both phases placed in +# order onto what the previous one landed, finished by the blueprint's OWN +# `run:` hooks (retouch, rebrand, re-tenant, work-tree strip, the +# deferrals and their restore, the lockfile, the deployment record), each +# landing a commit; +# 3. the product it ends with: branded with no residue — the page, the +# Worker (its custom entry and its one Cron Trigger kept), the KV +# namespace titles and every secret ref its own — carrying +# nothing of the factory and naming none of it, re-tenanted, its gates +# restored, its record rendered; +# 4. what the product's own CI does with the 01-product merge: `orun plan` +# for a push to main over exactly that commit — INFRA BEFORE APP: the KV +# namespace applied on stage and prod, each Worker deploy waiting on its +# own environment's apply and nothing else, stage and prod side by side, +# nothing on dev; the build rendering the environment's wiring, the +# Worker, its cron smoke and secret refs the product's own. Then the same edge on a +# pull request, where it is advisory and nothing waits; and the 02-docs +# merge, which plans nothing at all; +# 5. a `--resume` over the finished site places nothing and un-brands nothing. +# +# testing/e2e.test.sh goes on from here: it installs, builds and serves the +# product and runs its smoke against it. +# +# Needs: orun, node, pnpm, python3 (+PyYAML), git. No credential. The pnpm +# lockfile check and the deployment-record probes reach the network if they +# can, and pass without it. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" +# shellcheck source=lib/bootstrap.sh +source "$here/lib/bootstrap.sh" + +for bin in orun node pnpm python3 git; do + command -v "$bin" >/dev/null || { echo "placement.test.sh needs $bin on PATH" >&2; exit 1; } +done +# Step 4 is the PRODUCT's own plan, so it must be planned by the orun the +# product's CI runs (ci.yml's pin) or newer: v2.58.11, the bootstrap floor, +# does not apply a dependsOn edge's `modeRules`, and would plan a pull request +# with the page waiting on the KV plan. +pin="$(sed -n 's/^ *version: *v\([0-9.]*\) *$/\1/p' "$root/.github/workflows/ci.yml" | head -1)" +have="$(orun --version | sed -n 's/.*version \([0-9.]*\).*/\1/p')" +python3 -c "import sys; v=lambda s: tuple(map(int, s.split('.'))); sys.exit(0 if v(sys.argv[1]) >= v(sys.argv[2]) else 1)" "$have" "$pin" \ + || { echo "placement.test.sh plans as the product's CI does: run it with orun >= v$pin (ci.yml's pin), not v$have" >&2; exit 1; } + +scratch="$(mktemp -d)" +trap 'rm -rf "$scratch"' EXIT +fails=0 +fail() { echo " ✕ $*" >&2; fails=$((fails + 1)); } +values="$here/fixtures/acme.json" +repo="$(python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['reponame'])" "$values")" + +sets=() +while IFS=$'\t' read -r k v; do sets+=( --set "$k=$v" ); done < <( + python3 - "$values" <<'PY' +import json, sys +for k, v in json.load(open(sys.argv[1])).items(): + if not k.startswith("_"): + print(f"{k}\t{'true' if v is True else 'false' if v is False else v}") +PY +) + +# ── 1. the whole blueprint, one placement ────────────────────────────────── +echo "── placing the whole blueprint at once (offline, no credential)" +whole="$scratch/whole" +mkdir -p "$whole"/{apps,infra,packages,tests} +for d in apps infra packages tests; do touch "$whole/$d/.gitkeep"; done +if ! orun new --blueprint "$root/repo-blueprint.yaml" --out "$whole" "${sets[@]}" > "$scratch/whole.log" 2>&1; then + echo "FAIL: the placement did not run" >&2; tail -20 "$scratch/whole.log" >&2; exit 1 +fi +# The line's wording moved between orun releases (v2.58: `repo gate: validate + +# plan --dry-run passed`; v2.79: `Verified intent valid · N components …`). +grep -Eq "repo gate: validate \+ plan --dry-run passed|Verified +intent valid" "$scratch/whole.log" \ + || fail "the placement did not report the repo-scale gate (orun validate + plan --dry-run inside the tree)" +n="$(find "$whole" -type f -not -path '*/.orun/*' | wc -l | tr -d ' ')" +[ "$n" -ge 50 ] || fail "only $n files placed — that is not a product" +[ "$fails" -eq 0 ] && echo " $n files placed; the repo-scale gate ran" + +# ── 2. the offline bootstrap ─────────────────────────────────────────────── +echo "── the offline bootstrap: both phases, their own hooks, a landing each" +tree="$scratch/$repo" # named as the repository is: orun names the project after it +bootstrap_offline "$root" "$tree" "$values" "$scratch/logs" > "$scratch/bootstrap.log" 2>&1 || { + echo "FAIL: the offline bootstrap stopped" >&2; tail -40 "$scratch/bootstrap.log" >&2; exit 1; } +grep -E '^── ' "$scratch/bootstrap.log" | sed 's/^/ /' +commits="$(git -C "$tree" rev-list --count HEAD)" +[ "$commits" = 2 ] || fail "the bootstrap landed $commits commits, not one per phase (2)" + +# ── 3. the product it ends with ──────────────────────────────────────────── +echo "── the product it produced" +(cd "$tree" && node "$root/tooling/rebrand/rebrand.mjs" --verify --values .rebrand/values.json) > "$scratch/verify.log" 2>&1 \ + || { fail "rebrand --verify found the baseline's identity in the product:"; sed 's/^/ /' "$scratch/verify.log" >&2; } + +python3 - "$tree" "$values" "$root" <<'PY' || fails=$((fails + 1)) +import json, pathlib, re, subprocess, sys +import yaml +tree, values, root = pathlib.Path(sys.argv[1]), json.load(open(sys.argv[2])), pathlib.Path(sys.argv[3]) +problems = [] +def bad(m): problems.append(m) +repo, org, name, sub, ws = (values[k] for k in ("reponame", "githuborg", "productname", "subdomain", "orunWorkspace")) + +tracked = subprocess.run(["git", "ls-files"], cwd=tree, capture_output=True, text=True, check=True).stdout.split() + +# Nothing of the factory, nothing local, exactly the two context pages… +NEVER = (".baseline/", "specs/", "tasks/", "testing/", "hooks/", "docs/phases/", + "tooling/rebrand/", "tooling/bootstrap/", ".github/workflows/baseline.yml", + ".github/workflows/tag.yml", "BOOTSTRAP.md", "repo-blueprint.yaml", "blueprint.yaml") +for p in tracked: + if any(p == n or p.startswith(n) for n in NEVER): + bad(f"{p} is in the product — it is the factory") + if re.search(r"(^|/)(\.env(\.local)?|\.dev\.vars|node_modules|\.orun|\.next|\.open-next|\.terraform)(/|$)|\.tfstate$", p): + bad(f"{p} is in the product — a local or built file") +ai = {p for p in tracked if p.startswith("ai/")} +if ai != {"ai/context/deployment.md", "ai/context/operations.md"}: + bad(f"ai/ in the product is {sorted(ai)}") +# …and no file it carries NAMES the factory: those paths do not exist here. +FACTORY = re.compile(r"repo-blueprint|BOOTSTRAP\.md|(?<![\w-])(testing|specs|tasks|docs/phases|" + r"tooling/rebrand|tooling/bootstrap)/|(?<![\w/])\.baseline/") +for p in tracked: + try: + text = (tree / p).read_text() + except UnicodeDecodeError: + continue + for n, line in enumerate(text.splitlines(), 1): + if FACTORY.search(line): + bad(f"{p}:{n} names a factory path: {line.strip()[:80]}") + +# The identity, where the product carries it. +site = (tree / "apps/web/lib/site.ts").read_text() +if f"SITE_NAME = {json.dumps(name)}" not in site: + bad(f"apps/web/lib/site.ts does not name the site {name!r}") +if f'SOURCE_URL = "https://github.com/{org}/{repo}"' not in site: + bad(f"apps/web/lib/site.ts does not link github.com/{org}/{repo}") +web = yaml.safe_load((tree / "apps/web/component.yaml").read_text())["spec"] +if web["parameters"]["workerName"] != f"{repo}-web": + bad(f"workerName is {web['parameters']['workerName']}, not {repo}-web") +if web["parameters"]["workersDevSubdomain"] != sub: + bad(f"workersDevSubdomain is {web['parameters']['workersDevSubdomain']}, not {sub}") +# The Worker's config: the product's name, and the cron wiring kept — the +# custom entry that adds the scheduled handler, and the ONE trigger that calls +# it (every minute; the seven schedules are dispatched from it — one trigger +# per Worker keeps a product inside Workers Free's five per account). +crons_ts = (tree / "apps/web/lib/crons.ts").read_text() +crons = re.findall(r"cron: '([^']+)'", crons_ts) +trigger = re.search(r"export const TRIGGER = '([^']+)'", crons_ts) +if len(crons) != 7: + bad(f"apps/web/lib/crons.ts lists {len(crons)} schedules, not seven") +if not trigger or trigger.group(1) != "* * * * *": + bad("apps/web/lib/crons.ts declares no every-minute TRIGGER") +for cfg in ("wrangler.jsonc", "wrangler.template.jsonc"): + text = (tree / "apps/web" / cfg).read_text() + if f'"name": "{repo}-web"' not in text: + bad(f"apps/web/{cfg} does not name the Worker {repo}-web") + conf = json.loads(re.sub(r"^\s*//.*$", "", text, flags=re.M)) + if conf.get("main") != "worker.ts": + bad(f"apps/web/{cfg}'s main is {conf.get('main')!r} — the scheduled handler lives in worker.ts") + if (conf.get("triggers") or {}).get("crons") != ["* * * * *"]: + bad(f"apps/web/{cfg}'s triggers.crons are {(conf.get('triggers') or {}).get('crons')}, not the one every-minute trigger") +if web["parameters"].get("workerEntrypoint") != "worker.ts": + bad(f"workerEntrypoint is {web['parameters'].get('workerEntrypoint')}, not worker.ts") +if not (tree / "apps/web/worker.ts").exists() or "scheduled" not in (tree / "apps/web/worker.ts").read_text(): + bad("apps/web/worker.ts (the entry with the scheduled handler) is not in the product") +if json.loads((tree / "package.json").read_text())["name"] != repo: + bad("package.json is not named for the product") + +# The KV namespace: its titles are built on the product's repo slug, so two +# products in one account never collide (Cloudflare refuses a duplicate title). +kv = yaml.safe_load((tree / "infra/terraform/cloudflare-kv/component.yaml").read_text())["spec"] +if f'default = "{repo}"' not in (tree / "infra/terraform/cloudflare-kv/terraform/main.tf").read_text(): + bad("the KV root's terraform `repo` default is not the product's slug") +fixture = json.loads((tree / "apps/web/wiring.fixture.json").read_text()) +for env, prefix in (("dev", "dev-"), ("stage", "stg-"), ("prod", "prod-")): + want = f"{prefix}{repo}-app-kv-{env}" + if (fixture.get(f"cloudflare-kv/{env}") or {}).get("app_kv_title") != want: + bad(f"the fixture's {env} namespace title is not {want}") +# Every secret ref names the product's workspace and project. +for label, refs in (("apps/web", web.get("secretEnv") or {}), ("cloudflare-kv", kv.get("secretEnv") or {})): + for k, ref in refs.items(): + if not ref.startswith(f"secret://{ws}/{repo}/"): + bad(f"{label} secretEnv {k} is {ref} — not the product's workspace and project") + +# The intent: re-tenanted, no work tree, both gates back, the KV parameters its own. +intent_text = (tree / "intent.yaml").read_text() +intent = yaml.safe_load(intent_text) +if intent["metadata"]["name"] != repo: + bad(f"intent metadata.name is {intent['metadata']['name']}") +if intent["execution"]["state"]["workspace"] != ws: + bad(f"intent workspace is {intent['execution']['state']['workspace']}, not the product's") +if "work" in intent: + bad("intent.yaml still declares the baseline's work tree") +if "promotion" not in intent["environments"]["prod"] or "@promotion-deferred" in intent_text: + bad("prod's promotion gate was not restored by 02-docs") +if "github-push-main" not in intent["environments"]["dev"]["activation"]["triggerRefs"] or "@dev-lanes-deferred" in intent_text: + bad("dev's push activation was not restored by 02-docs") +for env in ("stage", "prod"): + want = f"https://{repo}-web-{env}.{sub}.workers.dev" + if intent["environments"][env].get("url") != want: + bad(f"environments.{env}.url is {intent['environments'][env].get('url')}, not {want}") + tf = ((intent["environments"][env].get("parameterDefaults") or {}).get("terraform") or {}) + if tf.get("repo") != repo: + bad(f"environments.{env} terraform repo is {tf.get('repo')}, not {repo}") +for page in (intent.get("repo") or {}).get("docs", {}).get("pages", []): + if not (tree / page["path"]).exists(): + bad(f"intent repo.docs names {page['path']}, which the product does not have") + +# The landings, as the phases made them: one marker per component the +# product's contract names, and the record 02-docs rendered. +for rel in ("infra/terraform/cloudflare-kv/component.yaml", "apps/web/component.yaml", "tests/web/component.yaml"): + if not re.search(r"^# orun: redeploy 01-product \S+$", (tree / rel).read_text(), re.M): + bad(f"{rel} carries no 01-product redeploy marker") +dep = (tree / "ai/context/deployment.md").read_text() +if "GENERATED by the `02-docs` phase" not in dep or f"https://{repo}-web-prod.{sub}.workers.dev" not in dep: + bad("ai/context/deployment.md was not rendered for the product") +readme = (tree / "README.md").read_text() +if not readme.startswith(f"# {repo}\n") or "This site is **live**" not in readme: + bad("README.md is not the product's, or its live-deployment section was not rendered") + +# Provenance prose, over the BRANDED files. +PROV = re.compile(r"\bfork(ed)? (of|from)\b|\bbaseline (repo|repository|commit|tag)\b|repo-blueprint|BOOTSTRAP\.md", re.I) +for rel in ("README.md", "ai/context/operations.md", "ai/context/deployment.md"): + for n, line in enumerate((tree / rel).read_text().splitlines(), 1): + if PROV.search(line): + bad(f"{rel}:{n} speaks of the factory: {line.strip()[:70]}") + +if problems: + for p in problems: + print(f" ✕ {p}", file=sys.stderr) + sys.exit(1) +print(f" {len(tracked)} tracked files; branded (page, Worker, KV titles, secret refs), the cron entry " + f"and its one trigger kept, no factory path named, re-tenanted, gates restored, record rendered") +PY + +# ── 4. the product's own CI, over the 01-product merge ───────────────────── +echo "── orun plan in the product, for the push that merged 01-product" +s01="$(git -C "$tree" rev-parse HEAD~1)"; s02="$(git -C "$tree" rev-parse HEAD)" +git -C "$tree" checkout -q "$s01" +(cd "$tree" && orun validate --intent intent.yaml) > "$scratch/validate.log" 2>&1 \ + || { fail "orun validate refused the product's intent at 01-product"; tail -10 "$scratch/validate.log" >&2; } +# The first push to main: every file is new, so the changed set is everything +# and the plan is the full one. +(cd "$tree" && orun plan --intent intent.yaml --trigger github-push-main --output "$scratch/plan.json") \ + > "$scratch/plan.log" 2>&1 || { fail "orun plan failed in the product at 01-product"; tail -15 "$scratch/plan.log" >&2; } +git -C "$tree" checkout -q main +python3 - "$scratch/plan.json" "$values" <<'PY' || fails=$((fails + 1)) +import json, sys +plan, values = json.load(open(sys.argv[1])), json.load(open(sys.argv[2])) +repo, sub, ws = values["reponame"], values["subdomain"], values["orunWorkspace"] +problems = [] +def bad(m): problems.append(m) +jobs = {(j["component"], j["environment"]): j for j in plan["jobs"]} +want = {("cloudflare-kv", "stage"), ("cloudflare-kv", "prod"), ("web", "stage"), ("web", "prod")} +if set(jobs) != want: + bad(f"the 01-product merge plans {sorted(jobs)}; it must apply cloudflare-kv and deploy web on " + f"stage and prod, and nothing else (dev's push lanes are deferred)") + +def refs(j): + return {r["asEnv"]: r["ref"] for r in j.get("secretRefs") or []} +def ours(ref): + return ref.startswith(f"secret://{ws}/") and (f"/{repo}/" in ref or f"project:{repo}" in ref) + +for env in ("stage", "prod"): + kv, web = jobs.get(("cloudflare-kv", env)), jobs.get(("web", env)) + if not kv or not web: + continue + # INFRA BEFORE APP: the Worker's deploy waits for its own environment's + # KV apply, and for nothing else — not the other environment, not stage. + if not kv["profile"].endswith(".apply"): + bad(f"cloudflare-kv@{env} plans profile {kv['profile']}, not an apply") + if kv.get("dependsOn"): + bad(f"cloudflare-kv@{env} waits on {kv['dependsOn']} — during the bootstrap stage and prod apply side by side") + if not web["profile"].endswith(".deploy"): + bad(f"web@{env} plans profile {web['profile']}, not a deploy") + if (web.get("dependsOn") or []) != [kv["id"]]: + bad(f"web@{env} waits on {web.get('dependsOn')}; it must wait on {kv['id']} alone (infra before app)") + steps = {s["id"]: s.get("run") or "" for s in web["steps"]} + for need in ("verify-app-structure", "build-app", "deploy", "smoke"): + if need not in steps: + bad(f"web@{env} has no {need} step") + if "tooling/wire/live.mjs" not in steps.get("build-app", "") or "--components cloudflare-kv" not in steps.get("build-app", ""): + bad(f"web@{env}'s build does not render the KV wiring: {steps.get('build-app','').strip()}") + if f'EFFECTIVE_WORKER_NAME="{repo}-web-{env}"' not in steps.get("deploy", ""): + bad(f"web@{env} deploys a Worker not named {repo}-web-{env}") + if "/api/data/1m" not in steps.get("smoke", "") or "fetchedAt" not in steps.get("smoke", ""): + bad(f"web@{env}'s smoke does not read the every-minute trigger's last run") + r = refs(web) + for key in ("CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID", f"WIRING_CLOUDFLARE_KV_{env.upper()}"): + if not ours(r.get(key, "")): + bad(f"web@{env} resolves {key} from {r.get(key) or 'nowhere'} — not the product's workspace and project") + r = refs(kv) + for key in ("CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID"): + if not ours(r.get(key, "")): + bad(f"cloudflare-kv@{env} resolves {key} from {r.get(key) or 'nowhere'} — not the product's") +# The lanes say the same: the applies first, each deploy one level down. +level = {l["id"]: l.get("level") for l in plan.get("lanes") or []} +lane_of = {jid: l["id"] for l in plan.get("lanes") or [] for jid in l["jobs"]} +for env in ("stage", "prod"): + k, w = lane_of.get(f"cloudflare-kv.{env}.terraform"), lane_of.get(f"web.{env}.verify-deploy") + if k and w and not (level.get(k) == 0 and level.get(w) == 1): + bad(f"{env}: the KV lane is level {level.get(k)} and the web lane level {level.get(w)} — want 0 then 1") +if problems: + for p in problems: + print(f" ✕ {p}", file=sys.stderr) + sys.exit(1) +print(" cloudflare-kv → stage + prod, apply, level 0; web → stage + prod, deploy, level 1,") +print(" each waiting on its own environment's apply alone (infra before app); Worker, wiring, cron smoke and secrets the product's own") +PY + +echo "── …the same edge on a pull request: advisory, nothing waits" +git -C "$tree" worktree add -q "$scratch/pr" "$s01" +echo "// a change" >> "$scratch/pr/apps/web/pages/index.tsx" +echo "# a change" >> "$scratch/pr/infra/terraform/cloudflare-kv/terraform/main.tf" +git -C "$scratch/pr" -c user.email=t@example.invalid -c user.name=t commit -qam "a pull request" +(cd "$scratch/pr" && orun plan --intent intent.yaml --trigger github-pull-request --changed \ + --base "$s01" --head HEAD --output "$scratch/plan-pr.json") > "$scratch/plan-pr.log" 2>&1 \ + || { fail "orun plan failed for a pull request"; tail -15 "$scratch/plan-pr.log" >&2; } +python3 - "$scratch/plan-pr.json" <<'PY' || fails=$((fails + 1)) +import json, sys +plan = json.load(open(sys.argv[1])) +jobs = {(j["component"], j["environment"]): j for j in plan["jobs"]} +problems = [] +for env in ("stage", "prod"): + web, kv = jobs.get(("web", env)), jobs.get(("cloudflare-kv", env)) + if not web or not kv: + problems.append(f"the pull request plans no web or cloudflare-kv job on {env}") + continue + if not web["profile"].endswith(".verify") or not kv["profile"].endswith(".plan-only"): + problems.append(f"{env}: a pull request plans {web['profile']} and {kv['profile']} — it must verify and plan only") + if kv["id"] in (web.get("dependsOn") or []): + problems.append(f"web@{env} waits on {kv['id']} on a pull request — the edge must be advisory there") +for p in problems: + print(f" ✕ {p}", file=sys.stderr) +sys.exit(1 if problems else 0) +PY +[ "$fails" -eq 0 ] && echo " web verifies beside the KV plan on stage and prod; neither waits" +git -C "$tree" worktree remove --force "$scratch/pr" + +echo "── …and the 02-docs merge plans nothing" +(cd "$tree" && orun plan --intent intent.yaml --trigger github-push-main --changed \ + --base "$s01" --head "$s02" --output "$scratch/plan-02.json") > "$scratch/plan-02.log" 2>&1 \ + || { fail "orun plan failed for the 02-docs merge"; tail -15 "$scratch/plan-02.log" >&2; } +jobs02="$(python3 -c "import json,sys;print(len(json.load(open(sys.argv[1]))['jobs']))" "$scratch/plan-02.json" 2>/dev/null || echo '?')" +[ "$jobs02" = 0 ] && echo " 0 jobs: restoring the gates and writing the record redeploys nothing" \ + || fail "the 02-docs merge plans $jobs02 job(s); it touches no component and must plan none" + +# ── 5. a resume over the finished site ──────────────────────────────────── +echo "── --resume over the finished product" +before="$(git -C "$tree" status --porcelain; git -C "$tree" rev-parse HEAD)" +orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" --resume "${sets[@]}" > "$scratch/resume.log" 2>&1 \ + || { fail "--resume did not run"; tail -10 "$scratch/resume.log" >&2; } +after="$(git -C "$tree" status --porcelain; git -C "$tree" rev-parse HEAD)" +[ "$before" = "$after" ] || { fail "--resume changed the finished product:"; git -C "$tree" status --short | head -10 >&2; } +name="$(python3 -c "import json,sys;print(json.dumps(json.load(open(sys.argv[1]))['productname']))" "$values")" +grep -qF "SITE_NAME = $name" "$tree/apps/web/lib/site.ts" \ + || fail "--resume reverted the product's identity" +[ "$fails" -eq 0 ] && echo " nothing placed again, nothing un-branded" + +[ "$fails" -eq 0 ] || { echo "placement.test.sh: $fails failure(s)" >&2; exit 1; } +echo "placement.test.sh: ok" diff --git a/testing/rebrand.test.sh b/testing/rebrand.test.sh new file mode 100755 index 0000000..4fc6df3 --- /dev/null +++ b/testing/rebrand.test.sh @@ -0,0 +1,177 @@ +#!/usr/bin/env bash +# THE REBRAND WRITES EACH VALUE ONCE, AND WHAT IT WROTE STAYS WRITTEN. +# +# Drives the real tooling/rebrand/rebrand.mjs over one-file trees and compares +# the file. Each case is a shape this baseline's identity actually takes in the +# tree — the source link, the site-name seam, the worker name in the component +# and the wrangler config, the KV namespace titles and the terraform `repo` +# they are built from, the placeholder domain, a secret ref — and the +# survival cases run through three passes, so a value an earlier rebrand +# wrote (a re-run phase re-runs the rebrand over everything placed) comes +# out of every later one unchanged. +# +# The identity is PINNED (fixtures/baseline-identity.cron-starter.json) +# rather than read from .baseline/identity.json: what this tests is the engine, +# and its fixtures spell the identity out literally. +# +# Needs: node, git. No network. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +rebrand="$here/../tooling/rebrand/rebrand.mjs" +identity="$here/fixtures/baseline-identity.cron-starter.json" + +fail=0 +# check NAME VALUES-JSON FILE CONTENT WANT [PASSES] +check() { + local name="$1" values="$2" file="$3" content="$4" want="$5" passes="${6:-1}" + local tmp got out i + tmp="$(mktemp -d)" + git -C "$tmp" init -q + mkdir -p "$tmp/$(dirname "$file")" "$tmp/.rebrand" + printf '%s\n' "$content" > "$tmp/$file" + printf '%s\n' "$values" > "$tmp/.rebrand/values.json" + for ((i = 1; i <= passes; i++)); do + git -C "$tmp" add -A + if ! out="$(cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --values .rebrand/values.json --allow-dirty 2>&1)"; then + echo " ✕ $name: rebrand pass $i failed:" >&2 + printf '%s\n' "$out" | sed 's/^/ /' >&2 + fail=1 + rm -rf "$tmp" + return + fi + done + got="$(cat "$tmp/$file")" + rm -rf "$tmp" + if [ "$got" = "$want" ]; then + echo " ok $name" + else + echo " ✕ $name:" >&2 + echo " got: $got" >&2 + echo " want: $want" >&2 + fail=1 + fi +} + +acme='{"reponame":"acme-crons","productname":"Acme Crons","productdomain":"acme.dev","githuborg":"acme-inc","subdomain":"acme","orunWorkspace":"ws_79BDXAZQ"}' + +echo "── rebrand: the site's own identity" +check "the source link names the product's owner and repository" \ + "$acme" apps/web/lib/site.ts \ + 'export const SOURCE_URL = "https://github.com/sourceplane/cron-starter"' \ + 'export const SOURCE_URL = "https://github.com/acme-inc/acme-crons"' +check "the site-name seam takes the product's name" \ + "$acme" apps/web/lib/site.ts 'export const SITE_NAME = "Cron Triggers on Cloudflare"' \ + 'export const SITE_NAME = "Acme Crons"' +check "…and stays a valid string for a name with an apostrophe and an ampersand" \ + '{"reponame":"sams-crons","productname":"Sam'"'"'s Crons & Schedules","productdomain":"sam.dev"}' \ + apps/web/lib/site.ts 'export const SITE_NAME = "Cron Triggers on Cloudflare"' \ + 'export const SITE_NAME = "Sam'"'"'s Crons & Schedules"' +check "the display name elsewhere is content, and is left alone" \ + "$acme" apps/web/README.md 'Cron Triggers on Cloudflare call the scheduled handler.' \ + 'Cron Triggers on Cloudflare call the scheduled handler.' +check "the worker name is re-prefixed, the environment suffix kept" \ + "$acme" apps/web/component.yaml 'workerName: cron-starter-web' \ + 'workerName: acme-crons-web' +check "the wrangler config's worker name, template and render alike" \ + "$acme" apps/web/wrangler.template.jsonc ' "name": "cron-starter-web",' \ + ' "name": "acme-crons-web",' +check "the environment URLs: worker name and subdomain" \ + "$acme" intent.yaml ' url: https://cron-starter-web-stage.your-workers-subdomain.workers.dev' \ + ' url: https://acme-crons-web-stage.acme.workers.dev' +check "the KV namespace's terraform repo — every namespace title is built on it" \ + "$acme" infra/terraform/cloudflare-kv/terraform/main.tf ' default = "cron-starter"' \ + ' default = "acme-crons"' +check "the per-environment terraform repo parameter" \ + "$acme" intent.yaml ' repo: cron-starter' \ + ' repo: acme-crons' +check "a fixture's namespace title follows the same rule" \ + "$acme" apps/web/wiring.fixture.json ' "app_kv_title": "stg-cron-starter-app-kv-stage"' \ + ' "app_kv_title": "stg-acme-crons-app-kv-stage"' +check "the placeholder domain is the product's domain, not a renamed slug" \ + "$acme" intent.yaml ' BASE_DOMAIN: cron-starter.example.com' \ + ' BASE_DOMAIN: acme.dev' +check "the repo slug" \ + "$acme" package.json ' "name": "cron-starter",' \ + ' "name": "acme-crons",' +check "a wiring secret ref names the product's workspace and project" \ + "$acme" apps/web/component.yaml \ + ' WIRING_CLOUDFLARE_KV_STAGE: "secret://cron-starter/cron-starter/stage/WIRING_CLOUDFLARE_KV"' \ + ' WIRING_CLOUDFLARE_KV_STAGE: "secret://ws_79BDXAZQ/acme-crons/stage/WIRING_CLOUDFLARE_KV"' +check "a templated provider secret ref too" \ + "$acme" infra/terraform/cloudflare-kv/component.yaml \ + ' CLOUDFLARE_API_TOKEN: "secret://cron-starter/cron-starter/{{ .environment }}/CLOUDFLARE_API_TOKEN"' \ + ' CLOUDFLARE_API_TOKEN: "secret://ws_79BDXAZQ/acme-crons/{{ .environment }}/CLOUDFLARE_API_TOKEN"' +check "org-owned identity is not renamed" \ + "$acme" intent.yaml 'apiVersion: sourceplane.io/v1 # mail ops@sourceplane.ai' \ + 'apiVersion: sourceplane.io/v1 # mail ops@sourceplane.ai' +check "without githuborg the source link keeps the baseline's owner" \ + '{"reponame":"acme-crons","productname":"Acme Crons","productdomain":"acme.dev"}' \ + apps/web/lib/site.ts 'const SOURCE_URL = "https://github.com/sourceplane/cron-starter"' \ + 'const SOURCE_URL = "https://github.com/sourceplane/acme-crons"' + +echo "── rebrand: a written value is not rewritten, in any later pass" +contains='{"reponame":"cron-starter-2","productname":"Cron Triggers on Cloudflare 2","productdomain":"cron-starter.example.com.au","githuborg":"sourceplane","subdomain":"your-workers-subdomain-2"}' +check "a repo slug containing the baseline's slug survives three passes" \ + "$contains" package.json ' "name": "cron-starter",' \ + ' "name": "cron-starter-2",' 3 +check "a worker name built on it survives three passes" \ + "$contains" apps/web/component.yaml 'workerName: cron-starter-web' \ + 'workerName: cron-starter-2-web' 3 +check "a namespace title built on it survives three passes" \ + "$contains" apps/web/wiring.fixture.json '"app_kv_title": "prod-cron-starter-app-kv-prod"' \ + '"app_kv_title": "prod-cron-starter-2-app-kv-prod"' 3 +check "a domain containing the baseline's domain survives three passes" \ + "$contains" intent.yaml 'BASE_DOMAIN: cron-starter.example.com' \ + 'BASE_DOMAIN: cron-starter.example.com.au' 3 +check "a subdomain containing the placeholder survives three passes" \ + "$contains" apps/web/component.yaml 'workersDevSubdomain: your-workers-subdomain' \ + 'workersDevSubdomain: your-workers-subdomain-2' 3 +check "a site name containing the baseline's name survives three passes" \ + "$contains" apps/web/lib/site.ts 'export const SITE_NAME = "Cron Triggers on Cloudflare"' \ + 'export const SITE_NAME = "Cron Triggers on Cloudflare 2"' 3 + +# --verify runs in every phase. Without the product's values it cannot tell +# the product's own identity from a leftover; with them it can. A real +# leftover must fail it either way. +verify() { # NAME VALUES FILE CONTENT WANT(pass|fail) [--values] + local name="$1" values="$2" file="$3" content="$4" want="$5" withvalues="${6:-}" tmp got + tmp="$(mktemp -d)" + git -C "$tmp" init -q + mkdir -p "$tmp/$(dirname "$file")" "$tmp/.rebrand" + printf '%s\n' "$content" > "$tmp/$file" + printf '%s\n' "$values" > "$tmp/.rebrand/values.json" + git -C "$tmp" add -A + if (cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --verify ${withvalues:+--values .rebrand/values.json} >/dev/null 2>&1); then got=pass; else got=fail; fi + rm -rf "$tmp" + if [ "$got" = "$want" ]; then echo " ok $name"; else echo " ✕ $name: --verify ${got}ed, want $want" >&2; fail=1; fi +} +echo "── rebrand --verify: the product's own identity is not residue" +verify "given the values, a slug containing the baseline's passes" \ + "$contains" package.json '"name": "cron-starter-2"' pass --values +verify "without them it cannot know, and fails" \ + "$contains" package.json '"name": "cron-starter-2"' fail +verify "given the values, a real leftover still fails" \ + "$acme" package.json '"name": "cron-starter"' fail --values +verify "a leftover worker name fails" \ + "$acme" apps/web/wrangler.jsonc '"name": "cron-starter-web",' fail --values +verify "a leftover namespace title fails" \ + "$acme" apps/web/wiring.fixture.json '"app_kv_title": "stg-cron-starter-app-kv-stage"' fail --values +verify "a leftover code identifier fails (no rule renames it — so nothing may spell it)" \ + "$acme" apps/web/lib/x.ts 'export class CronStarter {}' fail --values +verify "a clean product passes" \ + "$acme" package.json '"name": "acme-crons"' pass --values + +echo "── rebrand: a residue it cannot rename fails the rebrand itself" +tmp="$(mktemp -d)"; git -C "$tmp" init -q; mkdir -p "$tmp/.rebrand" "$tmp/apps/web" +printf '%s\n' "$acme" > "$tmp/.rebrand/values.json" +printf 'const x = "CRON_STARTER_TOKEN"\n' > "$tmp/apps/web/x.ts" +git -C "$tmp" add -A +if (cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --values .rebrand/values.json --allow-dirty >/dev/null 2>&1); then + echo " ✕ an unrenamable env-var prefix passed the rebrand" >&2; fail=1 +else + echo " ok an unrenamable env-var prefix fails the rebrand, naming the file" +fi +rm -rf "$tmp" + +[ "$fail" -eq 0 ] || exit 1 +echo "rebrand.test.sh: ok" diff --git a/testing/retouch.test.sh b/testing/retouch.test.sh new file mode 100755 index 0000000..1ef5d69 --- /dev/null +++ b/testing/retouch.test.sh @@ -0,0 +1,199 @@ +#!/usr/bin/env bash +# A RE-RUN PHASE HAS SOMETHING TO LAND. +# +# A phase's convergence can fail AFTER its PR merged, and the merge has already +# put every file the phase places on main. orun derives phase state from the +# files, so a retried build sees the phase placed and a forced re-run of it +# lands an EMPTY diff — and the product's CI plans `--changed`, so a component +# whose files did not change in the push does not deploy. The phase's `retouch` +# hook (tooling/bootstrap/retouch.mjs) is what breaks that: one marker line at +# the end of each affected component.yaml, +# +# # orun: redeploy <phase> <stamp> +# +# replaced rather than accumulated, so the landing has a diff and exactly the +# phase's components are in the changed set. The marker is a deploy trigger and +# nothing reads it back; phase state stays derived, never stored. +# +# This drives the real retouch.mjs over a two-component tree, then checks that +# every component the blueprint's retouch hooks name resolves in THIS tree — +# the layout a product is placed with. +# Needs: node. No network. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" +retouch="$root/tooling/bootstrap/retouch.mjs" + +command -v node >/dev/null || { echo "retouch.test.sh needs node" >&2; exit 1; } + +fail=0 +ok() { echo " ok $*"; } +bad() { echo " ✕ $*" >&2; fail=1; } + +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT + +# A product tree with two components in two of the lanes the blueprint places +# into, a test package that shares a directory name with the first (as +# tests/<worker> does with apps/<worker>) and must NOT be touched, and the +# hand-written re-trigger line the fleet carried before this tool existed. +mkdir -p "$tmp/apps/alpha" "$tmp/infra/beta" "$tmp/tests/alpha" "$tmp/node_modules/x" +cat > "$tmp/apps/alpha/component.yaml" <<'Y' +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: alpha +spec: + type: cloudflare-worker-turbo + labels: + team: platform +# ci: re-trigger deploy (batch A — runner-starvation recovery 20260622T115650Z) +Y +# No trailing newline on purpose: the tool must add one, and only one. +printf 'apiVersion: sourceplane.io/v1\nkind: Component\nmetadata:\n name: beta\nspec:\n type: terraform' > "$tmp/infra/beta/component.yaml" +printf 'kind: Component\nmetadata:\n name: alpha-tests\n' > "$tmp/tests/alpha/component.yaml" +printf 'kind: Component\nmetadata:\n name: alpha\n' > "$tmp/node_modules/x/component.yaml" +cp "$tmp/apps/alpha/component.yaml" "$tmp/alpha.orig" +cp "$tmp/infra/beta/component.yaml" "$tmp/beta.orig" + +markers() { grep -c '^# orun: redeploy ' "$1" || true; } + +echo "── retouch: one marker, last, replaced not appended" +(cd "$tmp" && ORUN_RUN_ID=run-one node "$retouch" --phase 04-workers --components alpha,beta) > "$tmp/one.log" 2>&1 \ + || { bad "first run failed:"; sed 's/^/ /' "$tmp/one.log" >&2; } +for f in apps/alpha infra/beta; do + [ "$(markers "$tmp/$f/component.yaml")" = 1 ] || bad "$f: $(markers "$tmp/$f/component.yaml") marker lines after one run, want 1" + [ "$(tail -n1 "$tmp/$f/component.yaml")" = "# orun: redeploy 04-workers run-one" ] \ + || bad "$f: last line is '$(tail -n1 "$tmp/$f/component.yaml")'" +done +[ "$(tail -c1 "$tmp/infra/beta/component.yaml" | od -An -c | tr -d ' ')" = '\n' ] \ + || bad "infra/beta: no trailing newline after retouch" +ok "both components carry the marker as their last line" + +(cd "$tmp" && ORUN_RUN_ID=run-two node "$retouch" --phase 04-workers-restore --components alpha,beta) > "$tmp/two.log" 2>&1 \ + || { bad "second run failed:"; sed 's/^/ /' "$tmp/two.log" >&2; } +for f in apps/alpha infra/beta; do + [ "$(markers "$tmp/$f/component.yaml")" = 1 ] || bad "$f: $(markers "$tmp/$f/component.yaml") marker lines after two runs — the marker accumulated" + [ "$(tail -n1 "$tmp/$f/component.yaml")" = "# orun: redeploy 04-workers-restore run-two" ] \ + || bad "$f: second run did not replace the marker: '$(tail -n1 "$tmp/$f/component.yaml")'" +done +grep -q 'replace marker' "$tmp/two.log" || bad "second run did not report a replacement" +ok "a second run replaces the marker (a different phase's too) rather than appending" + +echo "── retouch: every other byte is as it was" +if [ "$(head -n -1 "$tmp/apps/alpha/component.yaml" | cksum)" = "$(cksum < "$tmp/alpha.orig")" ]; then + ok "apps/alpha: the file above the marker is byte-for-byte the original" +else + bad "apps/alpha: bytes above the marker changed" + diff <(head -n -1 "$tmp/apps/alpha/component.yaml") "$tmp/alpha.orig" >&2 || true +fi +if [ "$(head -n -1 "$tmp/infra/beta/component.yaml" | cksum)" = "$(printf '%s\n' "$(cat "$tmp/beta.orig")" | cksum)" ]; then + ok "infra/beta: only a newline was added before the marker" +else + bad "infra/beta: bytes above the marker changed" +fi +grep -q '^# ci: re-trigger deploy' "$tmp/apps/alpha/component.yaml" \ + && ok "the hand-written re-trigger line is left alone" \ + || bad "the hand-written re-trigger line was removed" +[ "$(cat "$tmp/tests/alpha/component.yaml")" = "$(printf 'kind: Component\nmetadata:\n name: alpha-tests\n')" ] \ + && ok "tests/alpha (alpha-tests) was not touched — components resolve by metadata.name" \ + || bad "tests/alpha was touched: a component is its metadata.name, not its directory name" + +echo "── retouch: the same stamp twice is a no-op" +(cd "$tmp" && ORUN_RUN_ID=run-two node "$retouch" --phase 04-workers-restore --components alpha,beta) > "$tmp/again.log" 2>&1 \ + || bad "idempotent re-run failed" +grep -q 'nothing to do' "$tmp/again.log" && ok "re-running with the same stamp reports nothing to do" \ + || bad "re-running with the same stamp did not report a no-op: $(tail -1 "$tmp/again.log")" + +echo "── retouch: the stamp" +(cd "$tmp" && env -u ORUN_RUN_ID ORUN_SESSION_ID=sess-9 node "$retouch" --phase p --components beta) >/dev/null 2>&1 +[ "$(tail -n1 "$tmp/infra/beta/component.yaml")" = "# orun: redeploy p sess-9" ] \ + && ok "ORUN_SESSION_ID stamps when ORUN_RUN_ID is unset" \ + || bad "ORUN_SESSION_ID was not used: '$(tail -n1 "$tmp/infra/beta/component.yaml")'" +(cd "$tmp" && env -u ORUN_RUN_ID -u ORUN_SESSION_ID node "$retouch" --phase p --components beta) >/dev/null 2>&1 +tail -n1 "$tmp/infra/beta/component.yaml" | grep -Eq '^# orun: redeploy p [0-9]{8}T[0-9]{6}Z$' \ + && ok "with neither, a UTC timestamp" \ + || bad "no timestamp stamp: '$(tail -n1 "$tmp/infra/beta/component.yaml")'" + +echo "── retouch: --dry-run writes nothing, --check names what is missing" +before="$(cksum < "$tmp/apps/alpha/component.yaml")" +(cd "$tmp" && ORUN_RUN_ID=dry node "$retouch" --phase p --components alpha --dry-run) > "$tmp/dry.log" 2>&1 \ + || bad "--dry-run failed" +[ "$before" = "$(cksum < "$tmp/apps/alpha/component.yaml")" ] && grep -q 'would replace marker' "$tmp/dry.log" \ + && ok "--dry-run reports the change and leaves the file alone" \ + || bad "--dry-run wrote, or did not say what it would do" + +if (cd "$tmp" && node "$retouch" --phase p --components alpha,gamma --check) > "$tmp/check.log" 2>&1; then + bad "--check passed with gamma absent" +else + grep -q 'gamma' "$tmp/check.log" && ok "--check fails and names gamma" \ + || bad "--check failed without naming the missing component: $(cat "$tmp/check.log")" +fi +if (cd "$tmp" && ORUN_RUN_ID=x node "$retouch" --phase p --components alpha,gamma) > "$tmp/miss.log" 2>&1; then + bad "a run with a missing component succeeded" +else + [ "$(tail -n1 "$tmp/apps/alpha/component.yaml")" != "# orun: redeploy p x" ] \ + && ok "a missing component refuses the whole run before any file is written" \ + || bad "a missing component still wrote the components that exist" +fi +(cd "$tmp" && node "$retouch" --phase p --components alpha,beta --check) >/dev/null 2>&1 \ + && ok "--check passes when every component resolves" || bad "--check failed on a complete set" + +echo "── retouch: --affects reads a task contract" +cat > "$tmp/contract.yaml" <<'Y' +# A contract, as .baseline/tasks/*.TaskContract.yaml are written. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: Two components converge + affects: + - alpha + # a comment between items + - beta + doneWhen: + - convergence green + gates: [] +Y +(cd "$tmp" && ORUN_RUN_ID=via-contract node "$retouch" --phase 05-edge --affects contract.yaml) > "$tmp/aff.log" 2>&1 \ + || { bad "--affects run failed:"; sed 's/^/ /' "$tmp/aff.log" >&2; } +for f in apps/alpha infra/beta; do + [ "$(tail -n1 "$tmp/$f/component.yaml")" = "# orun: redeploy 05-edge via-contract" ] \ + || bad "$f: --affects did not touch it" +done +grep -q '2 of 2' "$tmp/aff.log" && ok "spec.affects named both, and both were touched" \ + || bad "--affects touched the wrong number: $(tail -1 "$tmp/aff.log")" +printf 'spec:\n affects: [alpha, beta]\n' > "$tmp/flow.yaml" +(cd "$tmp" && ORUN_RUN_ID=flow node "$retouch" --phase p --affects flow.yaml --check) >/dev/null 2>&1 \ + && ok 'the flow form `affects: [a, b]` reads too' || bad "the flow form of affects did not read" +printf 'spec:\n goal: nothing\n' > "$tmp/none.yaml" +(cd "$tmp" && node "$retouch" --phase p --affects none.yaml --check) >/dev/null 2>&1 \ + && bad "a contract with no affects passed --check" || ok "a contract with no affects refuses" + +# ── THE BLUEPRINT'S OWN HOOKS RESOLVE IN THIS TREE ───────────────────────── +# Every `retouch` hook in repo-blueprint.yaml names the components a phase +# redeploys, through a contract (.baseline/tasks/) or a list. A product is placed with this +# repository's layout, so each must resolve here — a contract that names a +# component nobody ships, or a component that moved, fails a real bootstrap at +# the landing, an hour in. `{{ .baseline.dir }}` is this checkout. +echo "── the blueprint's retouch hooks, against this tree" +hooks=0 +while IFS= read -r line; do + hooks=$((hooks + 1)) + argv="$(printf '%s' "$line" | sed -e 's/^[[:space:]]*run:[[:space:]]*//' \ + -e "s#{{ \.baseline\.dir }}#$root#g" -e 's#{{ \.phase\.name }}#probe#g')" + if (cd "$root" && node -e ' + const argv = JSON.parse(process.argv[1]); + const { spawnSync } = require("node:child_process"); + const r = spawnSync(argv[0], [...argv.slice(1), "--check"], { stdio: ["ignore", "pipe", "pipe"] }); + process.stdout.write(r.stdout); process.stderr.write(r.stderr); + process.exit(r.status ?? 1); + ' "$argv") > "$tmp/hook.log" 2>&1; then + ok "$(grep -c -- '->' "$tmp/hook.log") component(s): ${argv#*retouch.mjs\", }" + else + bad "a retouch hook does not resolve: $argv"; sed 's/^/ /' "$tmp/hook.log" >&2 + fi +done < <(grep -E '^\s*run: \[.*retouch\.mjs' "$root/repo-blueprint.yaml") +[ "$hooks" -ge 1 ] || bad "only $hooks retouch hook(s) in repo-blueprint.yaml — 01-product lands the deployable product and needs one" + +[ "$fail" -eq 0 ] || exit 1 +echo "retouch.test.sh: ok" diff --git a/testing/wire.test.sh b/testing/wire.test.sh new file mode 100755 index 0000000..293e139 --- /dev/null +++ b/testing/wire.test.sh @@ -0,0 +1,188 @@ +#!/usr/bin/env bash +# THE WIRING PATH — from a Terraform apply to the id in a deployed Worker's +# config — holds end to end, offline. +# +# An infra component lease-publishes a wiring document after its apply +# (`secretOutputs: "WIRING_<ROOT>=wiring"`, the root's `output "wiring"`); a +# deployable names the values it needs as tokens in `wrangler.template.jsonc` +# (`@@wiring(<root>/__ENV__:<key>)@@`), and its build renders `wrangler.jsonc` +# from the document (`tooling/wire/live.mjs`, in the component's +# buildCommand). Four things can drift apart there, and each fails a real +# deploy, late: +# +# 1. a token naming a key the root does not output, or a root that publishes +# nothing — the render fails on the deploy lane; +# 2. the fixture missing an environment the deployable builds for — its +# verify lane fails; +# 3. the committed wrangler.jsonc not being the fixture render — the deploy +# lane's `verify-app-structure` checks the config exists BEFORE the build +# (stack-tectonic's workers-assets composition), so the file is +# committed, and a stale one is what a reader finds; +# 4. the build's render command: a deployed environment must render from +# the real document and refuse to run without it, and a verify-only one +# (`dev`, where no root applies) must render from the fixture. +# +# Every templated deployable in the tree is checked, against the commands +# its own component.yaml declares. +# +# Needs: node, python3 (+PyYAML). No network, no credential. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" +fail=0 +ok() { echo " ok $1"; } +bad() { echo " ✕ $1" >&2; fail=1; } +tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT + +# Every templated deployable, and what the infra publishes — read once. +python3 - "$root" > "$tmp/facts.json" <<'PY' +import json, pathlib, re, sys +import yaml +root = pathlib.Path(sys.argv[1]) +comps = {} +for f in root.rglob("component.yaml"): + if "node_modules" in f.parts or ".orun" in f.parts: + continue + d = yaml.safe_load(f.read_text()) or {} + comps[(d.get("metadata") or {}).get("name")] = {"dir": f.parent.relative_to(root).as_posix(), "spec": d.get("spec") or {}} +publishers = {} +for name, c in comps.items(): + outs = str((c["spec"].get("parameters") or {}).get("secretOutputs") or "") + for pair in filter(None, (x.strip() for x in outs.split(","))): + key, _, output = pair.partition("=") + if not key.startswith("WIRING_"): + continue + tf = "\n".join(p.read_text() for p in (root / c["dir"]).rglob("*.tf")) + m = re.search(r'output\s+"%s"\s*\{.*?jsonencode\(\{(.*?)\}\)' % re.escape(output), tf, re.S) + keys = re.findall(r"^\s*([A-Za-z0-9_]+)\s*=", m.group(1), re.M) if m else [] + envs = [e["name"] for e in (c["spec"].get("subscribe") or {}).get("environments") or []] + publishers[name] = {"key": key, "output": output, "keys": keys, "envs": envs} +deployables = [] +for name, c in comps.items(): + tpl = root / c["dir"] / "wrangler.template.jsonc" + if not tpl.exists(): + continue + params = c["spec"].get("parameters") or {} + envs = [e["name"] for e in (c["spec"].get("subscribe") or {}).get("environments") or []] + tokens = sorted(set(re.findall(r"@@wiring\(([a-z0-9-]+)/__ENV__:([A-Za-z0-9_]+)\)@@", tpl.read_text()))) + deployables.append({"name": name, "dir": c["dir"], "envs": envs, "tokens": tokens, + "build": params.get("buildCommand") or "", "config": params.get("wranglerConfig") or "", + "secretEnv": sorted((c["spec"].get("secretEnv") or {}).keys())}) +print(json.dumps({"publishers": publishers, "deployables": deployables})) +PY +n="$(python3 -c "import json,sys;print(len(json.load(open(sys.argv[1]))['deployables']))" "$tmp/facts.json")" +[ "$n" -ge 1 ] || { echo "no wrangler.template.jsonc anywhere — this check has gone blind" >&2; exit 1; } + +for i in $(seq 0 $((n - 1))); do + eval "$(python3 - "$tmp/facts.json" "$i" <<'PY' +import json, shlex, sys +d = json.load(open(sys.argv[1]))["deployables"][int(sys.argv[2])] +for k in ("name", "dir", "build", "config"): + print(f"{k}={shlex.quote(d[k])}") +print(f"envs={shlex.quote(' '.join(d['envs']))}") +PY +)" + echo "── $name ($dir)" + + # 1 + 2: every token resolves against what its root outputs, and the + # fixture covers every environment the deployable builds for. + python3 - "$tmp/facts.json" "$i" "$root" <<'PY' && ok "every token names a key its root outputs; the fixture covers every environment, the dev rung included" || fail=1 +import json, pathlib, sys +facts = json.load(open(sys.argv[1])); d = facts["deployables"][int(sys.argv[2])]; root = pathlib.Path(sys.argv[3]) +pubs = facts["publishers"] +fixture = json.loads((root / d["dir"] / "wiring.fixture.json").read_text()) +problems = [] +if not d["tokens"]: + problems.append("wrangler.template.jsonc carries no @@wiring(<root>/__ENV__:<key>)@@ token") +for comp, key in d["tokens"]: + p = pubs.get(comp) + if not p: + problems.append(f"token {comp}:{key} — no infra component {comp} lease-publishes a WIRING_* document") + continue + if key not in p["keys"]: + problems.append(f"token {comp}:{key} — {comp}'s output \"{p['output']}\" has {p['keys']}") + for env in d["envs"]: + if not (fixture.get(f"{comp}/{env}") or {}).get(key): + problems.append(f"the fixture has no {comp}/{env}:{key} — the {env} lane renders it") + for env in p["envs"]: + want = f"{p['key']}_{env.upper()}" + if env in d["envs"] and want not in d["secretEnv"]: + problems.append(f"{env} deploys after {comp} applies there, and secretEnv does not resolve {want}") +for p in problems: + print(f" ✕ {p}", file=sys.stderr) +sys.exit(1 if problems else 0) +PY + + # 3: the committed config is the fixture render. + if [ "$config" != "wrangler.jsonc" ] || [ ! -f "$root/$dir/wrangler.jsonc" ]; then + bad "wranglerConfig is '$config' — the composition checks it exists before the build, so it must be the committed wrangler.jsonc" + else + (cd "$root/$dir" && node "$root/tooling/wire/render.mjs" --template wrangler.template.jsonc \ + --out "$tmp/rendered.jsonc" --map wiring.fixture.json --env stage) >/dev/null + cmp -s "$tmp/rendered.jsonc" "$root/$dir/wrangler.jsonc" \ + && ok "the committed wrangler.jsonc is the fixture render" \ + || { bad "the committed wrangler.jsonc is not the fixture render — run \`pnpm run wire:fixture\` and commit it"; diff "$tmp/rendered.jsonc" "$root/$dir/wrangler.jsonc" | head -10 >&2 || true; } + fi + + # 4: the build's own render command, cut from its buildCommand at the + # first `&&` (the rest is the Next.js build), run in a copy of the app. + render="${build%% && *}" + case "$render" in *tooling/wire/live.mjs*) ;; *) bad "buildCommand does not start by rendering with tooling/wire/live.mjs: $build"; continue ;; esac + rm -rf "$tmp/tree"; mkdir -p "$tmp/tree/$dir" "$tmp/tree/tooling" + cp -r "$root/tooling/wire" "$tmp/tree/tooling/wire" + cp "$root/$dir/wrangler.template.jsonc" "$root/$dir/wiring.fixture.json" "$tmp/tree/$dir/" + run_render() { # ENV [KEY=VALUE…] — the render as the lane runs it, with only the given wiring in env + local env="$1"; shift + (cd "$tmp/tree/$dir" && env -i PATH="$PATH" HOME="$HOME" ORUN_ENVIRONMENT="$env" "$@" bash -c "$render") + } + for env in $envs; do + rm -f "$tmp/tree/$dir/wrangler.jsonc" + docs=(); ids=() + for pair in $(python3 -c " +import json,sys +d=json.load(open(sys.argv[1]))['deployables'][int(sys.argv[2])]; pubs=json.load(open(sys.argv[1]))['publishers'] +for comp in sorted({c for c,_ in d['tokens']}): + if sys.argv[3] in pubs[comp]['envs']: print(pubs[comp]['key']+'_'+sys.argv[3].upper()+'|'+comp) +" "$tmp/facts.json" "$i" "$env"); do + key="${pair%%|*}"; comp="${pair#*|}" + id="e2e$(printf '%s' "$key" | md5sum | cut -c1-29)" + docs+=("$key=$(python3 -c " +import json,sys +d=json.load(open(sys.argv[1]))['deployables'][int(sys.argv[2])] +print(json.dumps({k: sys.argv[3] for c,k in d['tokens'] if c==sys.argv[4]}))" "$tmp/facts.json" "$i" "$id" "$comp")") + ids+=("$id") + done + if [ "${#docs[@]}" -gt 0 ]; then + # A deployed environment: the document wins, and without it the render refuses. + if run_render "$env" "${docs[@]}" > "$tmp/r.log" 2>&1 && grep -q "${ids[0]}" "$tmp/tree/$dir/wrangler.jsonc"; then + ok "$env renders from the published document (${#docs[@]} of them)" + else + bad "$env did not render from the published document"; sed 's/^/ /' "$tmp/r.log" >&2 + fi + rm -f "$tmp/tree/$dir/wrangler.jsonc" + if run_render "$env" > "$tmp/r.log" 2>&1; then + bad "$env rendered with no wiring document — a deploy would ship the fixture's placeholder id" + else + grep -q "${docs[0]%%=*}" "$tmp/r.log" && ok "$env without its document refuses, naming ${docs[0]%%=*}" \ + || { bad "$env refused without naming the missing document"; cat "$tmp/r.log" >&2; } + fi + else + # A verify-only environment: no root applies there, so the fixture. + if run_render "$env" > "$tmp/r.log" 2>&1; then + want="$(python3 -c " +import json,sys +d=json.load(open(sys.argv[1]))['deployables'][int(sys.argv[2])] +fx=json.load(open(sys.argv[3])) +c,k=d['tokens'][0]; print(fx[c+'/'+sys.argv[4]][k])" "$tmp/facts.json" "$i" "$root/$dir/wiring.fixture.json" "$env")" + grep -q "\"$want\"" "$tmp/tree/$dir/wrangler.jsonc" && grep -q 'verify-only' "$tmp/r.log" \ + && ok "$env (verify-only, no root applies) renders from the fixture, and says so" \ + || { bad "$env did not render the fixture's $env values"; cat "$tmp/r.log" >&2; } + else + bad "$env (verify-only) cannot render without a document no root publishes"; sed 's/^/ /' "$tmp/r.log" >&2 + fi + fi + done +done + +[ "$fail" -eq 0 ] || { echo "wire.test.sh: failure(s)" >&2; exit 1; } +echo "wire.test.sh: ok" diff --git a/tests/web/src/crons.test.ts b/tests/web/src/crons.test.ts index 49f9a84..f5354ff 100644 --- a/tests/web/src/crons.test.ts +++ b/tests/web/src/crons.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { readFileSync } from "node:fs"; import * as path from "node:path"; -import { crons, intervalFor } from "@/lib/crons"; +import { TRIGGER, crons, dueIntervals, matches } from "@/lib/crons"; // vercel.json's seven crons, verbatim: path → schedule. const vercelJson: Record<string, string> = { @@ -14,6 +14,8 @@ const vercelJson: Record<string, string> = { "/api/cron/1mo": "0 0 1 * *", }; +const at = (iso: string) => Date.parse(iso); + describe("the cron table (lib/crons.ts)", () => { it("is vercel.json's seven schedules, each with the interval its path named", () => { expect(crons.map((c) => [`/api/cron/${c.interval}`, c.cron])).toEqual( @@ -21,25 +23,54 @@ describe("the cron table (lib/crons.ts)", () => { ); }); - it("maps every expression back to its interval", () => { - for (const [route, cron] of Object.entries(vercelJson)) { - expect(intervalFor(cron)).toBe(route.replace("/api/cron/", "")); - } - }); - - it("answers undefined for an expression no trigger declares", () => { - expect(intervalFor("30 4 * * *")).toBeUndefined(); - expect(intervalFor("")).toBeUndefined(); - }); - - it("is what wrangler.template.jsonc registers as triggers.crons", () => { + it("is dispatched from ONE trigger, the only one wrangler.template.jsonc registers", () => { const template = readFileSync( path.resolve(__dirname, "../../../apps/web/wrangler.template.jsonc"), "utf8", ); const json = JSON.parse(template.replace(/^\s*\/\/.*$/gm, "")); - expect(json.triggers.crons).toEqual(crons.map((c) => c.cron)); + expect(TRIGGER).toBe("* * * * *"); + expect(json.triggers.crons).toEqual([TRIGGER]); expect(json.main).toBe("worker.ts"); expect(json.kv_namespaces[0].binding).toBe("KV"); }); }); + +describe("dueIntervals: the schedules due at a trigger's scheduled time (UTC)", () => { + const cases: Array<[string, string, string[]]> = [ + ["an ordinary minute", "2026-10-14T09:07:00Z", ["1m"]], + ["a tenth minute", "2026-10-14T09:10:00Z", ["1m", "10m"]], + ["the top of an hour", "2026-10-14T10:00:00Z", ["1m", "10m", "1h"]], + ["noon", "2026-10-14T12:00:00Z", ["1m", "10m", "1h", "12h"]], + ["midnight on a Thursday", "2026-10-15T00:00:00Z", ["1m", "10m", "1h", "12h", "1d"]], + ["midnight on a Sunday (`0 0 * * 0`)", "2026-10-18T00:00:00Z", ["1m", "10m", "1h", "12h", "1d", "1w"]], + ["midnight on a Monday is not the weekly run", "2026-10-19T00:00:00Z", ["1m", "10m", "1h", "12h", "1d"]], + ["midnight on the 1st, a Tuesday", "2026-12-01T00:00:00Z", ["1m", "10m", "1h", "12h", "1d", "1mo"]], + ["midnight on the 1st, a Sunday: all seven", "2026-11-01T00:00:00Z", ["1m", "10m", "1h", "12h", "1d", "1w", "1mo"]], + ["12:00 is due for 12h, 06:00 is not", "2026-10-14T06:00:00Z", ["1m", "10m", "1h"]], + ["the seconds of the scheduled time do not matter", "2026-10-14T09:10:59.999Z", ["1m", "10m"]], + ]; + for (const [name, iso, want] of cases) { + it(`${name} (${iso})`, () => { + expect(dueIntervals(at(iso))).toEqual(want); + }); + } + + it("reads 7 as Sunday, and lists, ranges and steps", () => { + expect(matches("0 0 * * 7", new Date(at("2026-10-18T00:00:00Z")))).toBe(true); + expect(matches("15,45 9-17/2 * * 1-5", new Date(at("2026-10-14T11:45:00Z")))).toBe(true); + expect(matches("15,45 9-17/2 * * 1-5", new Date(at("2026-10-14T10:45:00Z")))).toBe(false); + }); + + it("fires on either restricted day field, as cron(8) does", () => { + expect(matches("0 0 1 * 1", new Date(at("2026-10-19T00:00:00Z")))).toBe(true); // a Monday + expect(matches("0 0 1 * 1", new Date(at("2026-12-01T00:00:00Z")))).toBe(true); // the 1st + expect(matches("0 0 1 * 1", new Date(at("2026-10-14T00:00:00Z")))).toBe(false); + }); + + it("refuses what it cannot read rather than guess", () => { + expect(() => matches("* * * *", new Date())).toThrow(); + expect(() => matches("61 * * * *", new Date())).toThrow(); + expect(() => matches("@hourly * * * *", new Date())).toThrow(); + }); +}); diff --git a/tests/web/src/scheduled.test.ts b/tests/web/src/scheduled.test.ts index 97a1cd1..f122c1f 100644 --- a/tests/web/src/scheduled.test.ts +++ b/tests/web/src/scheduled.test.ts @@ -1,17 +1,20 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { CRON_ORIGIN, makeScheduled } from "@/lib/scheduled"; -// The scheduled handler is the bridge between a Cron Trigger (which hands the -// Worker only the expression that fired) and the template's HTTP route that -// Vercel used to call on that schedule. +// The scheduled handler is the bridge between the one Cron Trigger (which +// hands the Worker its expression and the minute it was scheduled for) and +// the template's HTTP routes that Vercel used to call on seven schedules. const env = { KV: {}, ASSETS: {} } as unknown as CloudflareEnv; const ctx = { waitUntil: vi.fn(), passThroughOnException: vi.fn(), } as unknown as ExecutionContext; -const controller = (cron: string): ScheduledController => - ({ cron, scheduledTime: Date.now(), noRetry: vi.fn() }) as unknown as ScheduledController; +const controller = (cron: string, iso: string): ScheduledController => + ({ cron, scheduledTime: Date.parse(iso), noRetry: vi.fn() }) as unknown as ScheduledController; + +const paths = (fetch: { mock: { calls: unknown[][] } }) => + fetch.mock.calls.map(([request]) => new URL((request as Request).url).pathname); describe("the scheduled handler (lib/scheduled.ts)", () => { const fetch = vi.fn(async () => new Response('"OK"', { status: 200 })); @@ -24,8 +27,8 @@ describe("the scheduled handler (lib/scheduled.ts)", () => { log.mockClear(); }); - it("turns `* * * * *` into a GET of /api/cron/1m through the fetch handler", async () => { - await makeScheduled(fetch)(controller("* * * * *"), env, ctx); + it("on an ordinary minute runs only /api/cron/1m, through the fetch handler", async () => { + await makeScheduled(fetch)(controller("* * * * *", "2026-10-14T09:07:00Z"), env, ctx); expect(fetch).toHaveBeenCalledTimes(1); const [request, passedEnv, passedCtx] = fetch.mock.calls[0] as unknown as [ Request, @@ -40,33 +43,35 @@ describe("the scheduled handler (lib/scheduled.ts)", () => { expect(log).toHaveBeenCalledWith('/api/cron/1m 200 "OK"'); }); - it("routes each of the seven expressions to its own interval", async () => { - const table: Array<[string, string]> = [ - ["*/10 * * * *", "10m"], - ["0 * * * *", "1h"], - ["0 */12 * * *", "12h"], - ["0 0 * * *", "1d"], - ["0 0 * * 0", "1w"], - ["0 0 1 * *", "1mo"], + it("runs every schedule due at the scheduled minute, in table order", async () => { + const table: Array<[string, string[]]> = [ + ["2026-10-14T09:10:00Z", ["1m", "10m"]], + ["2026-10-14T12:00:00Z", ["1m", "10m", "1h", "12h"]], + ["2026-10-18T00:00:00Z", ["1m", "10m", "1h", "12h", "1d", "1w"]], + ["2026-11-01T00:00:00Z", ["1m", "10m", "1h", "12h", "1d", "1w", "1mo"]], ]; - for (const [cron, interval] of table) { + for (const [iso, intervals] of table) { fetch.mockClear(); - await makeScheduled(fetch)(controller(cron), env, ctx); - const [request] = fetch.mock.calls[0] as unknown as [Request]; - expect(new URL(request.url).pathname).toBe(`/api/cron/${interval}`); + await makeScheduled(fetch)(controller("* * * * *", iso), env, ctx); + expect(paths(fetch)).toEqual(intervals.map((i) => `/api/cron/${i}`)); } }); - it("calls nothing for an expression the table does not know", async () => { - await makeScheduled(fetch)(controller("5 4 * * *"), env, ctx); + it("calls nothing for an expression that is not the Worker's trigger", async () => { + await makeScheduled(fetch)(controller("0 0 * * *", "2026-10-15T00:00:00Z"), env, ctx); expect(fetch).not.toHaveBeenCalled(); expect(warn).toHaveBeenCalledOnce(); }); - it("fails the invocation when the route does not answer 2xx", async () => { - const failing = vi.fn(async () => new Response("boom", { status: 500 })); + it("runs the rest when one route fails, then fails the invocation naming it", async () => { + const failing = vi.fn(async (request: Request) => + new URL(request.url).pathname === "/api/cron/1h" + ? new Response("boom", { status: 500 }) + : new Response('"OK"', { status: 200 }), + ); await expect( - makeScheduled(failing)(controller("0 0 * * *"), env, ctx), - ).rejects.toThrow("/api/cron/1d answered 500: boom"); + makeScheduled(failing)(controller("* * * * *", "2026-10-15T00:00:00Z"), env, ctx), + ).rejects.toThrow("/api/cron/1h answered 500: boom"); + expect(paths(failing)).toEqual(["1m", "10m", "1h", "12h", "1d"].map((i) => `/api/cron/${i}`)); }); }); diff --git a/tests/web/src/site.test.ts b/tests/web/src/site.test.ts new file mode 100644 index 0000000..c905a15 --- /dev/null +++ b/tests/web/src/site.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vitest"; +import { SITE_NAME, SOURCE_URL, requestOrigin } from "@/lib/site"; + +// The identity seam a product's bootstrap rewrites, and the origin the page's +// absolute links are built from. +describe("site identity (apps/web/lib/site.ts)", () => { + it("names the site and links its source repository", () => { + expect(SITE_NAME.trim()).not.toBe(""); + expect(SOURCE_URL).toMatch(/^https:\/\/github\.com\/[A-Za-z0-9-]+\/[a-z0-9-]+$/); + }); +}); + +describe("requestOrigin", () => { + const h = (entries: Record<string, string>) => new Headers(entries); + + it("is the host the visitor asked for, over https", () => { + expect(requestOrigin(h({ host: "acme-crons-web-prod.acme.workers.dev" }))?.href).toBe( + "https://acme-crons-web-prod.acme.workers.dev/", + ); + }); + + it("is plain http on a local host (wrangler dev, next dev)", () => { + expect(requestOrigin(h({ host: "127.0.0.1:8787" }))?.href).toBe("http://127.0.0.1:8787/"); + expect(requestOrigin(h({ host: "localhost:3000" }))?.href).toBe("http://localhost:3000/"); + }); + + it("prefers the forwarded host and scheme", () => { + expect( + requestOrigin(h({ host: "internal", "x-forwarded-host": "crons.acme.dev", "x-forwarded-proto": "https" })) + ?.href, + ).toBe("https://crons.acme.dev/"); + }); + + it("reads Node's header object too (getServerSideProps)", () => { + const node: Record<string, string | string[] | undefined> = { host: "crons.acme.dev" }; + expect(requestOrigin({ get: (name) => [node[name]].flat()[0] ?? null })?.origin).toBe("https://crons.acme.dev"); + }); + + it("is undefined without a host, rather than a guess", () => { + expect(requestOrigin(h({}))).toBeUndefined(); + }); +}); diff --git a/tooling/bootstrap/dev-lanes.mjs b/tooling/bootstrap/dev-lanes.mjs new file mode 100755 index 0000000..27e4f84 --- /dev/null +++ b/tooling/bootstrap/dev-lanes.mjs @@ -0,0 +1,114 @@ +#!/usr/bin/env node +// The dev verify lanes stay off main's convergences while a product is being +// bootstrapped (zero-dependency). +// +// intent.yaml activates `dev` on `github-push-main` as well as on pull +// requests: every merge to main re-verifies every component (builds, tests) +// on the dev rung beside the stage and prod deploys. That is the right rule +// for a product that is live. During a bootstrap it proves nothing — the +// content comes from a pinned baseline whose own CI already ran it, and +// every phase's pull request is checked by `plan` alone — and it costs the +// one thing a bootstrap's wall-clock is made of: runner slots. The product's +// landing is a Next.js build per deployed environment; a third, on the dev +// rung (and its tests beside it), re-proves what the baseline's own CI +// already proved and competes with stage and prod for the runner pool. +// (Measured on the Cirrus baseline, where this tool comes from: dev took +// eight of eighteen lanes and stage and prod got five each.) +// +// So 01-product defers the trigger and 02-docs, the last landing, puts it +// back, exactly as tooling/bootstrap/promotion.mjs does for prod's gate: +// +// node tooling/bootstrap/dev-lanes.mjs --defer # 01-product, before the first landing +// node tooling/bootstrap/dev-lanes.mjs --restore # 02-docs, the last landing +// node tooling/bootstrap/dev-lanes.mjs --check # prints deferred | active +// +// --defer replaces dev's `- github-push-main` trigger line with one marker +// comment that base64-encodes the exact text removed, so --restore +// reproduces intent.yaml byte-for-byte. Both are idempotent. Pull requests +// keep their dev lanes throughout: only the push-to-main activation moves. +// +// The trigger is deferred, never dropped: a bootstrap that stops before +// 02-docs leaves the marker in intent.yaml, and `--restore` (or a re-run of +// 02-docs) is the whole fix. +import * as fs from "node:fs"; + +const FILE = process.argv.includes("--file") + ? process.argv[process.argv.indexOf("--file") + 1] + : "intent.yaml"; +const MARKER = "@dev-lanes-deferred"; +const TRIGGER = "github-push-main"; + +function usage() { + console.error("usage: dev-lanes.mjs --defer | --restore | --check [--file intent.yaml]"); + process.exit(2); +} + +// The `- github-push-main` line under environments.dev.activation.triggerRefs. +function findDevPushTrigger(text) { + const lines = text.split("\n"); + let inEnvs = false; + let devIndent = -1; + let inDev = false; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (/^environments:\s*$/.test(line)) { + inEnvs = true; + continue; + } + if (!inEnvs) continue; + if (/^\S/.test(line) && line.trim() !== "") break; // left the section + const env = /^(\s+)([A-Za-z0-9_-]+):\s*$/.exec(line); + if (env && (devIndent < 0 || env[1].length <= devIndent)) { + inDev = env[2] === "dev"; + if (inDev) devIndent = env[1].length; + continue; + } + if (!inDev) continue; + if (new RegExp(`^\\s+-\\s+${TRIGGER}\\s*$`).test(line)) return { lines, index: i }; + } + return { lines, index: -1 }; +} + +function defer() { + const text = fs.readFileSync(FILE, "utf8"); + if (text.includes(`# ${MARKER}:`)) { + console.log(`dev-lanes --defer: already deferred in ${FILE}`); + return; + } + const { lines, index } = findDevPushTrigger(text); + if (index < 0) { + console.log(`dev-lanes --defer: dev is not activated on ${TRIGGER} in ${FILE} — nothing to defer`); + return; + } + const original = lines[index]; + const indent = /^(\s*)/.exec(original)[1]; + const b64 = Buffer.from(original, "utf8").toString("base64"); + const marker = `${indent}# ${MARKER}:${b64} (tooling/bootstrap/dev-lanes.mjs --restore puts it back)`; + const out = [...lines.slice(0, index), marker, ...lines.slice(index + 1)].join("\n"); + fs.writeFileSync(FILE, out); + console.log(`dev-lanes --defer: dev's verify lanes stay off main's convergences until --restore (${FILE})`); +} + +function restore() { + const text = fs.readFileSync(FILE, "utf8"); + const re = new RegExp(`^[ \\t]*# ${MARKER}:([A-Za-z0-9+/=]+) \\(tooling/bootstrap/dev-lanes\\.mjs --restore puts it back\\)$`, "m"); + const m = re.exec(text); + if (!m) { + console.log(`dev-lanes --restore: nothing deferred in ${FILE}`); + return; + } + const original = Buffer.from(m[1], "base64").toString("utf8"); + fs.writeFileSync(FILE, text.slice(0, m.index) + original + text.slice(m.index + m[0].length)); + console.log(`dev-lanes --restore: dev verifies every merge to main again (${FILE})`); +} + +function check() { + const text = fs.readFileSync(FILE, "utf8"); + console.log(text.includes(`# ${MARKER}:`) ? "deferred" : "active"); +} + +const mode = process.argv[2]; +if (mode === "--defer") defer(); +else if (mode === "--restore") restore(); +else if (mode === "--check") check(); +else usage(); diff --git a/tooling/bootstrap/promotion.mjs b/tooling/bootstrap/promotion.mjs new file mode 100644 index 0000000..ec8f4f5 --- /dev/null +++ b/tooling/bootstrap/promotion.mjs @@ -0,0 +1,123 @@ +#!/usr/bin/env node +// Stage and prod deploy side by side while a product is being bootstrapped +// (zero-dependency). +// +// intent.yaml gates prod behind stage: `environments.prod.promotion.dependsOn: +// [stage]`, which orun plans as an in-run edge from every prod job to the +// same component's stage job. That is the right rule for a product that is +// live — a change reaches prod only after it deployed to stage. During a +// bootstrap it protects nothing (both environments are empty, and every phase +// is watched to green before the next one starts) and it doubles the length +// of every convergence: each worker's prod deploy waits out its stage deploy. +// +// So 01-product defers the gate and 02-docs, the last landing, puts it back: +// +// node tooling/bootstrap/promotion.mjs --defer # 01-product, before the first landing +// node tooling/bootstrap/promotion.mjs --restore # 02-docs, the last landing +// node tooling/bootstrap/promotion.mjs --check # prints deferred | enforced +// +// --defer replaces the prod `promotion:` block with one marker comment that +// base64-encodes the exact text removed, so --restore reproduces intent.yaml +// byte-for-byte. Both are idempotent. Restoring is a change to intent.yaml's +// `environments` section only, which `orun plan --changed` (intent impact +// `watch`, the default) maps to no component: the landing that restores it +// deploys nothing. +// +// The gate is deferred, never dropped: a bootstrap that stops before 02-docs +// leaves the marker in intent.yaml, and `--restore` (or a re-run of 02-docs) +// is the whole fix. docs/phases/02-docs.md says so. + +import * as fs from "node:fs"; + +const FILE = process.argv.includes("--file") + ? process.argv[process.argv.indexOf("--file") + 1] + : "intent.yaml"; +const MARKER = "@promotion-deferred"; + +function usage() { + console.error("usage: promotion.mjs --defer | --restore | --check [--file intent.yaml]"); + process.exit(2); +} + +// The `promotion:` block of the `prod:` environment: from its `promotion:` +// line up to (not including) the next line indented at or above it. +function findProdPromotion(text) { + const lines = text.split("\n"); + let inEnvs = false; + let prodIndent = -1; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (/^environments:\s*$/.test(line)) { + inEnvs = true; + continue; + } + if (!inEnvs) continue; + if (/^\S/.test(line) && line.trim() !== "") break; // left the section + const prod = /^(\s+)prod:\s*$/.exec(line); + if (prod) { + prodIndent = prod[1].length; + continue; + } + if (prodIndent < 0) continue; + const indent = line.length - line.trimStart().length; + if (line.trim() !== "" && indent <= prodIndent) { + prodIndent = -1; // left prod without finding one + continue; + } + const m = /^(\s+)promotion:\s*$/.exec(line); + if (!m) continue; + const own = m[1].length; + let end = i + 1; + while (end < lines.length) { + const l = lines[end]; + if (l.trim() !== "" && l.length - l.trimStart().length <= own) break; + end++; + } + return { lines, start: i, end, indent: m[1] }; + } + return null; +} + +function defer() { + const text = fs.readFileSync(FILE, "utf8"); + if (text.includes(MARKER)) { + console.log(`promotion --defer: already deferred in ${FILE}`); + return; + } + const found = findProdPromotion(text); + if (!found) { + console.log(`promotion --defer: prod has no promotion block in ${FILE} — nothing to defer`); + return; + } + const { lines, start, end, indent } = found; + const removed = lines.slice(start, end).join("\n"); + const b64 = Buffer.from(removed, "utf8").toString("base64"); + const marker = `${indent}# ${MARKER}:${b64} (tooling/bootstrap/promotion.mjs --restore puts it back)`; + const out = [...lines.slice(0, start), marker, ...lines.slice(end)].join("\n"); + fs.writeFileSync(FILE, out); + console.log(`promotion --defer: prod no longer waits on stage until --restore (${FILE})`); +} + +function restore() { + const text = fs.readFileSync(FILE, "utf8"); + const re = new RegExp(`^[ \\t]*# ${MARKER}:([A-Za-z0-9+/=]+).*$`, "m"); + const m = re.exec(text); + if (!m) { + console.log(`promotion --restore: nothing deferred in ${FILE}`); + return; + } + const original = Buffer.from(m[1], "base64").toString("utf8"); + fs.writeFileSync(FILE, text.slice(0, m.index) + original + text.slice(m.index + m[0].length)); + console.log(`promotion --restore: prod waits on stage again (${FILE})`); +} + +function check() { + const text = fs.readFileSync(FILE, "utf8"); + console.log(text.includes(MARKER) ? "deferred" : "enforced"); +} + +const mode = process.argv[2]; +if (mode === "--defer") defer(); +else if (mode === "--restore") restore(); +else if (mode === "--check") check(); +else usage(); diff --git a/tooling/bootstrap/retouch.mjs b/tooling/bootstrap/retouch.mjs new file mode 100644 index 0000000..6cc76fc --- /dev/null +++ b/tooling/bootstrap/retouch.mjs @@ -0,0 +1,254 @@ +#!/usr/bin/env node +// Give a re-run phase something to land (zero-dependency). +// +// A phase lands as a pull request and is verified by the convergence run that +// follows the merge. When that convergence FAILS — a provider error, a runner +// starved out, a smoke that raced route propagation past its retries — the +// merge has already happened, so every file the phase places is on main. orun +// derives phase state from the files on disk (never from a stored record), so +// a retried build finds the phase placed, and even a forced re-run of it +// produces an EMPTY diff: `orun.pr/land@v1` has nothing to commit, and the +// product's CI (`orun plan --changed`) deploys a component only when one of +// its files changed in the push. Nothing lands, nothing redeploys, and the +// operator is told the phase is fine. +// +// This tool is what the phase's `retouch` hook runs before it stages and +// lands: for each component the phase deploys, it rewrites ONE trailing line +// in that component's `component.yaml`, +// +// # orun: redeploy <phase> <stamp> +// +// replacing the previous marker if there is one (never accumulating), so the +// landing has a diff and exactly those components are in the changed set. The +// same convention was hand-edited before this existed (`# ci: re-trigger +// deploy …` lines, duplicated by hand); this is that edit with a name, a +// stamp, and a phase to answer for it. +// +// THE MARKER IS A DEPLOY TRIGGER, NOT STATE. Nothing reads it back: orun does +// not learn from it whether a phase ran, and this repository's invariant — +// phase state is DERIVED from the tree, never stored in it — holds. Delete the +// line and nothing is lost but the next redeploy's reason to happen. +// +// node retouch.mjs --phase 01-product --affects .baseline/tasks/01-product.TaskContract.yaml +// node retouch.mjs --phase 01-product --components cloudflare-kv,web,web-tests +// +// Options: +// --phase <name> the phase the marker names (required) +// --components a,b,c the components to touch, by `metadata.name` … +// --affects <contract> … or read them from a TaskContract's `spec.affects` +// --check resolve every component and exit non-zero naming +// any without a component.yaml; write nothing +// --dry-run print what would change; write nothing +// +// The stamp is ORUN_RUN_ID if set, else ORUN_SESSION_ID, else a UTC timestamp +// (YYYYMMDDTHHMMSSZ) — whichever identifies the run that asked for the deploy. +// +// Runs in the product checkout (the phase hooks' working directory). A +// component is found by the `metadata.name` its component.yaml declares, not +// by directory: `apps/web` and `tests/web` both carry one, and only the +// first is named `web`. + +import * as fs from "node:fs"; +import * as path from "node:path"; + +const MARKER_RE = /^# orun: redeploy \S+ \S+\r?$/; +const SKIP_DIRS = new Set(["node_modules", ".git", ".orun", "dist", ".next", ".open-next", ".turbo"]); +const MAX_DEPTH = 4; + +function usage(msg) { + if (msg) console.error(`retouch: ${msg}`); + console.error( + "usage: retouch.mjs --phase <name> (--components a,b,c | --affects <TaskContract.yaml>) [--check] [--dry-run]", + ); + process.exit(2); +} + +function parseArgs(argv) { + const opts = { phase: null, components: null, affects: null, check: false, dryRun: false }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + const next = () => { + if (i + 1 >= argv.length) usage(`${a} needs a value`); + return argv[++i]; + }; + if (a === "--phase") opts.phase = next(); + else if (a === "--components") opts.components = next(); + else if (a === "--affects") opts.affects = next(); + else if (a === "--check") opts.check = true; + else if (a === "--dry-run") opts.dryRun = true; + else if (a === "-h" || a === "--help") usage(); + else usage(`unknown argument ${a}`); + } + if (!opts.phase) usage("--phase is required"); + if (/\s/.test(opts.phase)) usage("--phase must be a single token"); + if (!opts.components && !opts.affects) usage("one of --components or --affects is required"); + if (opts.components && opts.affects) usage("--components and --affects are exclusive"); + return opts; +} + +// `spec.affects` from a TaskContract, with a reader small enough to need no +// YAML dependency: the contracts are a flat mapping with one block sequence. +// Accepts the block form (`affects:` then `- name` lines indented under it) +// and the flow form (`affects: [a, b]`). +function readAffects(file) { + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch (e) { + console.error(`retouch: cannot read ${file}: ${e.message}`); + process.exit(1); + } + const lines = text.split(/\r?\n/); + const names = []; + for (let i = 0; i < lines.length; i++) { + const m = /^(\s*)affects:\s*(.*?)\s*$/.exec(lines[i]); + if (!m) continue; + const indent = m[1].length; + const inline = m[2].replace(/\s+#.*$/, ""); + if (inline.startsWith("[")) { + const body = inline.replace(/^\[/, "").replace(/\]\s*$/, ""); + for (const part of body.split(",")) { + const v = part.trim().replace(/^["']|["']$/g, ""); + if (v) names.push(v); + } + break; + } + for (let j = i + 1; j < lines.length; j++) { + const line = lines[j]; + if (/^\s*(#.*)?$/.test(line)) continue; + const lead = /^(\s*)/.exec(line)[1].length; + if (lead <= indent) break; + const item = /^\s*-\s*(.+?)\s*$/.exec(line); + if (!item) break; + names.push(item[1].replace(/\s+#.*$/, "").replace(/^["']|["']$/g, "")); + } + break; + } + if (names.length === 0) { + console.error(`retouch: ${file} declares no spec.affects — nothing to touch`); + process.exit(1); + } + return names; +} + +// `metadata.name` from a component.yaml, read the same minimal way. +function componentName(file) { + const lines = fs.readFileSync(file, "utf8").split(/\r?\n/); + for (let i = 0; i < lines.length; i++) { + const m = /^(\s*)metadata:\s*$/.exec(lines[i]); + if (!m) continue; + const indent = m[1].length; + for (let j = i + 1; j < lines.length; j++) { + const line = lines[j]; + if (/^\s*(#.*)?$/.test(line)) continue; + const lead = /^(\s*)/.exec(line)[1].length; + if (lead <= indent) break; + const nm = /^\s*name:\s*(.+?)\s*$/.exec(line); + if (nm && lead === indent + 2) return nm[1].replace(/^["']|["']$/g, ""); + } + } + return null; +} + +// Every component.yaml in the tree, by the name it declares. +function indexComponents(root) { + const byName = new Map(); + const walk = (dir, depth) => { + let entries; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const ent of entries) { + const full = path.join(dir, ent.name); + if (ent.isDirectory()) { + if (SKIP_DIRS.has(ent.name) || depth >= MAX_DEPTH) continue; + walk(full, depth + 1); + } else if (ent.name === "component.yaml") { + const name = componentName(full); + if (!name) continue; + const rel = path.relative(root, full); + if (byName.has(name)) { + console.error( + `retouch: two component.yaml files declare metadata.name ${name}: ${byName.get(name)} and ${rel}`, + ); + process.exit(1); + } + byName.set(name, rel); + } + } + }; + walk(root, 0); + return byName; +} + +function stamp() { + for (const key of ["ORUN_RUN_ID", "ORUN_SESSION_ID"]) { + const v = (process.env[key] || "").trim(); + if (v) return v.replace(/\s+/g, "-"); + } + return new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z"); +} + +// The file with exactly one marker line, last, and a trailing newline. Every +// other byte is kept as it was. +function retouched(text, marker) { + const hadTrailingNewline = text.endsWith("\n"); + const lines = text.split("\n"); + if (hadTrailingNewline) lines.pop(); + const kept = lines.filter((l) => !MARKER_RE.test(l)); + // A file that was only a marker, or empty, still ends up valid. + const body = kept.length ? kept.join("\n") + "\n" : ""; + return body + marker + "\n"; +} + +function main() { + const opts = parseArgs(process.argv.slice(2)); + const root = process.cwd(); + const wanted = opts.components + ? opts.components.split(",").map((s) => s.trim()).filter(Boolean) + : readAffects(opts.affects); + if (wanted.length === 0) usage("no components named"); + + const index = indexComponents(root); + const missing = wanted.filter((n) => !index.has(n)); + if (missing.length) { + console.error( + `retouch: no component.yaml declares metadata.name for: ${missing.join(", ")} (looked under ${root})`, + ); + process.exit(1); + } + if (opts.check) { + for (const n of wanted) console.log(`retouch --check: ${n} -> ${index.get(n)}`); + console.log(`retouch --check: ${wanted.length} component(s) resolve.`); + return; + } + + const marker = `# orun: redeploy ${opts.phase} ${stamp()}`; + const verb = opts.dryRun ? "would" : ""; + let changed = 0; + for (const n of wanted) { + const rel = index.get(n); + const file = path.join(root, rel); + const before = fs.readFileSync(file, "utf8"); + const after = retouched(before, marker); + const had = before.split("\n").some((l) => MARKER_RE.test(l)); + if (after === before) { + console.log(`retouch: ${rel}: unchanged (marker already ${marker.slice(2)})`); + continue; + } + if (!opts.dryRun) fs.writeFileSync(file, after); + changed++; + console.log(`retouch: ${rel}: ${verb ? "would " : ""}${had ? "replace" : "add"} marker`); + } + console.log( + opts.dryRun + ? `retouch --dry-run: ${changed} of ${wanted.length} file(s) would change; nothing written.` + : changed > 0 + ? `retouch: ${changed} of ${wanted.length} component.yaml file(s) marked "${marker.slice(2)}" — the landing has a diff.` + : `retouch: nothing to do (every marker already current).`, + ); +} + +main(); diff --git a/tooling/bootstrap/work-tree.mjs b/tooling/bootstrap/work-tree.mjs new file mode 100644 index 0000000..ad48ba6 --- /dev/null +++ b/tooling/bootstrap/work-tree.mjs @@ -0,0 +1,73 @@ +#!/usr/bin/env node +// A product carries no work tree of the baseline's (zero-dependency). +// +// This repository's intent.yaml declares where ITS work lives: +// +// work: +// epics: specs/epics +// tasks: tasks +// sync: on-merge +// +// and `orun plan` on main reconciles that tree into the workspace's work +// plane. A product built from this baseline has neither directory — `specs/` and +// `tasks/` are the factory's, and the leak gate keeps them out — and its +// bootstrap work is opened on the platform by the build itself. Left in, the +// block would point the product's every plan at two directories that do not +// exist. +// +// So 01-product removes it from the product's copy, before the first landing: +// +// node tooling/bootstrap/work-tree.mjs --strip # 01-product +// node tooling/bootstrap/work-tree.mjs --check # prints declared | absent +// +// The block removed is the top-level `work:` key with everything indented +// under it, and the comment lines directly above it that belong to it. It is +// not put back: a product that wants a work tree declares its own. Idempotent. +import * as fs from "node:fs"; + +const FILE = process.argv.includes("--file") + ? process.argv[process.argv.indexOf("--file") + 1] + : "intent.yaml"; + +function usage() { + console.error("usage: work-tree.mjs --strip | --check [--file intent.yaml]"); + process.exit(2); +} + +function findWork(lines) { + const start = lines.findIndex((l) => /^work:\s*(#.*)?$/.test(l)); + if (start < 0) return null; + let end = start + 1; + while (end < lines.length && (lines[end].trim() === "" || /^\s/.test(lines[end]))) end++; + // Trailing blank lines belong to the gap before the next key, not the block. + while (end > start + 1 && lines[end - 1].trim() === "") end--; + // Its own comment: the contiguous `#` lines directly above it. + let from = start; + while (from > 0 && /^#/.test(lines[from - 1])) from--; + return { from, end }; +} + +function strip() { + const text = fs.readFileSync(FILE, "utf8"); + const lines = text.split("\n"); + const found = findWork(lines); + if (!found) { + console.log(`work-tree --strip: ${FILE} declares no work tree — nothing to do`); + return; + } + let { from, end } = found; + // Drop one of the blank lines that separated it from its neighbours. + if (end < lines.length && lines[end].trim() === "" && from > 0 && lines[from - 1].trim() === "") end++; + fs.writeFileSync(FILE, [...lines.slice(0, from), ...lines.slice(end)].join("\n")); + console.log(`work-tree --strip: removed the baseline's work tree from ${FILE}`); +} + +function check() { + const lines = fs.readFileSync(FILE, "utf8").split("\n"); + console.log(findWork(lines) ? "declared" : "absent"); +} + +const mode = process.argv[2]; +if (mode === "--strip") strip(); +else if (mode === "--check") check(); +else usage(); diff --git a/tooling/rebrand/rebrand.mjs b/tooling/rebrand/rebrand.mjs new file mode 100644 index 0000000..3eea52d --- /dev/null +++ b/tooling/rebrand/rebrand.mjs @@ -0,0 +1,462 @@ +#!/usr/bin/env node +// Rebrand renamer for the cron-starter baseline (zero-dependency). +// +// This repository is a baseline: a product is instantiated from it, branded, +// and deployed as somebody's own site. This script rewrites every *instance +// identity* literal in the product tree — repo slug (which also names the KV +// namespace titles and the secret project), the site's display name, its +// source-repository link, the product domain, Cloudflare worker resource +// names (so an instance is account-safe even when it shares an account with +// another), the workers.dev subdomain placeholder — to the values in a values +// file, and leaves *org-owned* identity alone (the orun state backend, the +// `sourceplane.io` manifest apiVersion, company mailboxes). +// +// The engine is generic; the identity is not. Everything specific to this +// tree is `.baseline/identity.json` (and the defaults below, which must equal +// it) plus the SITE_NAME seam in apps/web/lib/site.ts. +// +// The engine is Cirrus's (sourceplane/cirrus-baseline tooling/rebrand): the +// FROM side declared in `.baseline/identity.json`, every written value held +// opaque until the last rule has run, and a leftover sweep that fails on any +// identity a rule did not rename. The rules are this tree's. +// +// Usage (from the product root, on a git tree with the files staged): +// node tooling/rebrand/rebrand.mjs --values .rebrand/values.json [--dry-run] [--allow-dirty] +// node tooling/rebrand/rebrand.mjs --verify [--values .rebrand/values.json] +// +// Values file (see tooling/rebrand/values.example.json): +// { +// "reponame": "acme-notes", // required — repo slug +// "productname": "Acme Notes", // required — the site's display name +// "productdomain": "acme.dev", // required — the product domain +// "githuborg": "acme-inc", // owner of the product repo (source link) +// "brandSlug": "acme", // default: reponame — worker name prefix +// "subdomain": "acme", // default: your-workers-subdomain +// "orunWorkspace": "ws_XXXXXXXX", // the segment secret refs name +// "orunWorkspaceSlug": "acme-space" // optional: wins over orunWorkspace there +// } +// +// Modes: +// (default) apply the rename map in place, then run the leftover sweep +// --dry-run report per-rule match counts; change nothing +// --verify only run the leftover sweep (non-zero exit on residue) + +import { execFileSync } from "node:child_process"; +import * as fs from "node:fs"; +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; + +// ── Inputs ───────────────────────────────────────────────────── + +function flag(name) { + return process.argv.includes(`--${name}`); +} +function arg(name) { + const i = process.argv.indexOf(`--${name}`); + return i >= 0 ? process.argv[i + 1] : undefined; +} + +const dryRun = flag("dry-run"); +const verifyOnly = flag("verify"); + +let values = {}; +// --verify takes --values too, optionally: without them it cannot tell the +// product's own identity from a leftover of the baseline's. +const valuesPath = arg("values"); +if (!verifyOnly && !valuesPath) { + console.error("usage: rebrand.mjs --values <file> [--dry-run] | --verify [--values <file>]"); + process.exit(2); +} +if (valuesPath) { + values = JSON.parse(fs.readFileSync(valuesPath, "utf8")); + for (const required of ["reponame", "productname", "productdomain"]) { + if (typeof values[required] !== "string" || values[required].length === 0) { + console.error(`rebrand: values file is missing required field "${required}"`); + process.exit(2); + } + } +} + +// ── THE BASELINE'S OWN IDENTITY — the FROM side, declared ────── +// +// Read from `.baseline/identity.json` beside THIS SCRIPT, not the working +// directory: the rebrand runs with its cwd set to the PRODUCT being branded, +// and a product does not carry `.baseline/` (no module places it). The phase +// hooks invoke this as `node {{ .baseline.dir }}/tooling/rebrand/rebrand.mjs`, +// so the script's own path is the one thing that always points at the +// baseline. `--baseline-identity <file>` overrides it (the test suite pins one). +// +// slug the repo slug: intent name, worker prefix, secret project +// pascal the code-identifier form (swept for, never expected) +// productName the display name, as the SITE_NAME seam spells it +// domain the product domain (BASE_DOMAIN) +// subdomain the workers.dev subdomain this tree carries +// githubOwner the owner in the site's source link +const BASELINE_IDENTITY_FILE = + arg("baseline-identity") ?? + path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".baseline", "identity.json"); +const BASELINE_DEFAULTS = { + slug: "cron-starter", + pascal: "CronStarter", + productName: "Cron Triggers on Cloudflare", + domain: "cron-starter.example.com", + subdomain: "your-workers-subdomain", + githubOwner: "sourceplane", +}; +const baseline = (() => { + let declared = {}; + try { + declared = JSON.parse(fs.readFileSync(BASELINE_IDENTITY_FILE, "utf8")); + } catch { + declared = {}; // absent is fine: the defaults ARE this baseline's identity + } + const id = { ...BASELINE_DEFAULTS }; + for (const k of Object.keys(BASELINE_DEFAULTS)) { + if (declared[k] !== undefined) id[k] = declared[k]; + } + for (const [k, v] of Object.entries(id)) { + if (typeof v !== "string" || v.length === 0) { + console.error(`rebrand: ${BASELINE_IDENTITY_FILE} field "${k}" must be a non-empty string`); + process.exit(2); + } + } + if (/[^a-z0-9-]/.test(id.slug)) { + console.error(`rebrand: ${BASELINE_IDENTITY_FILE} "slug" must be a lowercase slug ([a-z0-9-])`); + process.exit(2); + } + return { ...id, envPrefix: id.slug.toUpperCase().replace(/-/g, "_") }; +})(); +// Regex-escape, for the rules that build a pattern out of the identity. +const rx = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +// All fields are unused under --verify; the fallbacks keep derivation total. +const reponame = values.reponame ?? ""; +const productname = values.productname ?? ""; +const productdomain = values.productdomain ?? ""; +const githuborg = (values.githuborg ?? "").trim() || baseline.githubOwner; +const brandSlug = (values.brandSlug ?? "").trim() || reponame; +const subdomain = (values.subdomain ?? "").trim() || "your-workers-subdomain"; +// A `secret://<workspace>/<project>/<env>/<KEY>` ref names the WORKSPACE first +// and the project (repo) second. The workspace segment is the product's +// workspace — an explicit slug if one was given, else the ws_… id itself +// (the platform's resolve accepts a slug, a public id or a ws_ ref) — and the +// repo name only as the last resort when no workspace was given at all. +const orunWorkspaceSlug = (() => { + const explicit = (values.orunWorkspaceSlug ?? "").trim(); + if (explicit) return explicit; + const ws = (values.orunWorkspace ?? "").trim(); + if (ws) return ws; + return reponame; +})(); + +if (!verifyOnly && /[^a-z0-9-]/.test(`${reponame}${brandSlug}`)) { + console.error("rebrand: reponame/brandSlug must be lowercase slugs ([a-z0-9-])"); + process.exit(2); +} +if (!verifyOnly && /[^A-Za-z0-9-]/.test(githuborg)) { + console.error("rebrand: githuborg must be a GitHub owner name ([A-Za-z0-9-])"); + process.exit(2); +} + +// In-place rewrite of the whole tree: insist on a clean checkout so the +// result is reviewable as one diff (and trivially revertible). +if (!verifyOnly && !dryRun && !flag("allow-dirty")) { + const status = execFileSync("git", ["status", "--porcelain"], { encoding: "utf8" }); + if (status.trim().length > 0) { + console.error("rebrand: working tree is not clean — commit/stash first (or pass --allow-dirty)"); + process.exit(2); + } +} + +// ── File set ─────────────────────────────────────────────────── + +// Tracked text files only. Exclusions are generated/locked artifacts, this +// tool and the identity it reads, and binary content. +const EXCLUDE_RE = new RegExp( + [ + "^tooling/rebrand/", + "^\\.rebrand/", + // The baseline's declared identity. Renaming its contents would make the + // product claim to be a baseline called by the product's own name. + "^\\.baseline/", + "^pnpm-lock\\.yaml$", + "^kiox\\.lock$", + "\\.(png|jpg|jpeg|ico|gif|webp|woff2?|ttf|eot)$", + ].join("|"), +); + +function trackedFiles() { + return execFileSync("git", ["ls-files"], { encoding: "utf8" }) + .split("\n") + .filter((f) => f.length > 0 && !EXCLUDE_RE.test(f)) + .filter((f) => { + // `git ls-files` also lists gitlinks (a grounded sandbox checkout carries + // `baseline/` as one) and paths deleted from disk. Only regular files + // are sweepable. + try { + return fs.statSync(f).isFile(); + } catch { + return false; + } + }); +} + +// ── Protected literals (org-owned identity, never rewritten) ─── +// +// Masked before the rules run and restored after, so no rename can touch the +// org's shared infrastructure identity. +const PROTECTED = [ + /https:\/\/orun-api\.sourceplane\.ai/g, // orun state backend + /sourceplane\.io/g, // manifest apiVersion, owned by the orun tooling + /[A-Za-z0-9._%+-]+@sourceplane\.ai/g, // company mailboxes +]; +const MASK = (i, j) => `\u0000REBRAND_PROTECTED_${i}_${j}\u0000`; + +// ── Substituted values are opaque ────────────────────────────── +// +// The rules run in sequence over one buffer. If each wrote its VALUE into it, +// every later rule could match that value again — a product whose domain +// contains the baseline's slug would have it renamed a second time by the +// repo-slug rule, and every phase of a bootstrap re-runs this over the whole +// tree. So a rule writes a TOKEN standing for its value, and every token is +// expanded once, after the last rule. A token is NUL, `H<n>`, NUL; its outer +// characters take the word/non-word class of the value's own edges, so a +// later rule's `\b` sees the boundary the value would have given it. +const heldValues = []; +const heldIndex = new Map(); +function hold(value) { + if (value === "") return ""; + let i = heldIndex.get(value); + if (i === undefined) { + i = heldValues.push(value) - 1; + heldIndex.set(value, i); + } + const edge = (c) => (/\w/.test(c) ? "0" : "\u0001"); + return `${edge(value[0])}\u0000H${i}\u0000${edge(value[value.length - 1])}`; +} +const HELD_RE = /[0\u0001]\u0000H(\d+)\u0000[0\u0001]/g; +function release(text) { + return text.replace(HELD_RE, (_, i) => heldValues[Number(i)]); +} + +// ── Worker resource names ────────────────────────────────────── +// +// Every Cloudflare worker ships prefixed with the slug (`<slug>-<base>`, the +// base being its `apps/<base>/` directory): the component's `workerName`, the +// environment URLs, the deploy smoke. Re-prefix it so an instance's workers +// never collide with another's in a shared account. +function workerBases(files) { + const bases = new Set(); + for (const file of files) { + const m = /^apps\/([^/]+)\//.exec(file); + if (m) bases.add(m[1]); + } + return [...bases]; +} + +// ── Rename map (ordered, most specific first) ────────────────── + +function literalPairs() { + return [ + // The site's source link (apps/web/lib/site.ts SOURCE_URL, the docs). + // Before the repo-slug rule, which would otherwise rename only its tail + // and leave the link pointing at the baseline's owner. + [`github.com/${baseline.githubOwner}/${baseline.slug}`, `github.com/${githuborg}/${reponame}`, "source repository link"], + // The product domain wherever it is the product's (BASE_DOMAIN, docs). + // Before the repo-slug rule: the placeholder domain starts with the slug. + [baseline.domain, productdomain, "product domain"], + // The workers.dev subdomain (component parameters, build origin, intent + // environment URLs, docs). + [baseline.subdomain, subdomain, "workers.dev subdomain"], + ]; +} + +function regexPairs(files) { + const list = [ + // The display-name seam. JSON.stringify writes a valid TS string for any + // name the card's pattern admits (apostrophes and ampersands included). + { + re: new RegExp(`SITE_NAME = "${rx(baseline.productName)}"`, "g"), + replacement: () => `SITE_NAME = ${JSON.stringify(productname)}`, + label: "site name seam", + }, + // Secret refs: `secret://<workspace>/<project>/…`. MUST precede the + // repo-slug pass, which would otherwise rewrite only the project half. The + // workspace segment is ANY segment — a ws_… id or a slug. + { + re: new RegExp(`\\bsecret://[A-Za-z0-9_-]+/${rx(baseline.slug)}/`, "g"), + replacement: () => `secret://${orunWorkspaceSlug}/${reponame}/`, + label: "secret ref workspace/project", + }, + ]; + + const bases = workerBases(files); + if (bases.length > 0) { + // Longest-first so an alternation never matches a shorter prefix of a base. + const wb = bases.slice().sort((a, b) => b.length - a.length).map(rx).join("|"); + list.push({ + re: new RegExp(`\\b${rx(baseline.slug)}-(${wb})\\b`, "g"), + replacement: (_m, base) => `${brandSlug}-${base}`, + label: "worker CF name", + }); + } + + // Repo slug: intent metadata.name and per-env `repo:` params, the root + // package name, docs. Runs AFTER the worker pass so `<slug>-<base>` has + // already been consumed. + list.push({ + re: new RegExp(`\\b${rx(baseline.slug)}\\b`, "g"), + replacement: () => reponame, + label: "repo slug", + }); + return list; +} + +// ── Leftover sweep ───────────────────────────────────────────── +// +// After a rebrand (or under --verify) every remaining baseline-identity +// literal is residue: either org-owned (allowed, masked above) or a missed +// rename (reported, non-zero exit). The pascal form and the env-var prefix +// have no rule because nothing in this tree spells them; they are swept so +// that the first file that does fails here, naming itself, rather than +// shipping the baseline's name. +// +// The placeholder subdomain is residue only when the product changed it — a +// product that kept the placeholder has not deployed yet, and that is not a +// missed rename. Under --verify without values it is skipped for the same +// reason. +const subdomainChanged = !verifyOnly && subdomain !== baseline.subdomain; +const RESIDUE_RE = new RegExp( + (subdomainChanged ? `${rx(baseline.subdomain)}|` : "") + + [ + `\\b${rx(baseline.slug)}\\b`, + `${rx(baseline.slug)}-`, + rx(baseline.pascal), + `${rx(baseline.envPrefix)}_`, + rx(baseline.domain), + ].join("|"), + "g", +); +const ALLOWED_RESIDUE = [ + /https:\/\/orun-api\.sourceplane\.ai/, // orun state backend + /[A-Za-z0-9._%+-]+@sourceplane\.ai/, // company mailboxes +]; + +function sweep(files, allowedLiterals = []) { + const residue = []; + for (const file of files) { + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch { + continue; + } + for (const line of text.split("\n")) { + let cleaned = ALLOWED_RESIDUE.reduce((l, re) => l.replace(new RegExp(re.source, "g"), ""), line); + // The rename's own TARGET values: a product legitimately named with the + // baseline's slug inside it is not residue. + for (const lit of allowedLiterals) { + if (lit) cleaned = cleaned.split(lit).join(""); + } + if (new RegExp(RESIDUE_RE.source).test(cleaned)) { + residue.push(`${file}: ${line.trim().slice(0, 120)}`); + } + } + } + return residue; +} + +// ── Main ─────────────────────────────────────────────────────── + +const files = trackedFiles(); +const literals = literalPairs(); +const regexes = regexPairs(files); + +// Every value a rule can write. A value some rule would match again is HELD +// wherever it already stands: every phase of a bootstrap re-runs this over the +// whole tree, so what an earlier phase wrote is input to the next pass and +// must come out of it unchanged. +const produced = [ + ...literals.map(([, to]) => to), + `SITE_NAME = ${JSON.stringify(productname)}`, + `secret://${orunWorkspaceSlug}/${reponame}/`, + reponame, + ...workerBases(files).map((base) => `${brandSlug}-${base}`), +].filter((v, i, all) => v && all.indexOf(v) === i); +const rematchable = (v) => + literals.some(([from]) => v.includes(from)) || regexes.some(({ re }) => new RegExp(re.source).test(v)); +// Longest first, so a held value is never split by a shorter one inside it. +const guarded = produced.filter(rematchable).sort((a, b) => b.length - a.length); +const allowedTargets = produced.filter((to) => new RegExp(RESIDUE_RE.source).test(to)); + +if (verifyOnly) { + const residue = sweep(files, valuesPath ? allowedTargets : []); + if (residue.length > 0) { + console.error(`rebrand --verify: ${residue.length} baseline-identity leftover(s):`); + for (const r of residue) console.error(` ${r}`); + process.exit(1); + } + console.log("rebrand --verify: no baseline-identity leftovers."); + process.exit(0); +} + +const counts = new Map(); +const touched = new Set(); +const count = (label, n = 1) => counts.set(label, (counts.get(label) ?? 0) + n); + +for (const file of files) { + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch { + continue; + } + if (text.includes("\0")) continue; // binary safety net + const original = text; + + const masks = []; + PROTECTED.forEach((re, i) => { + text = text.replace(re, (m) => { + const token = MASK(i, masks.length); + masks.push([token, m]); + return token; + }); + }); + + // What a previous pass already wrote stays as written. + for (const value of guarded) text = text.split(value).join(hold(value)); + + for (const [from, to, label] of literals) { + const n = text.split(from).length - 1; + if (n === 0) continue; + text = text.split(from).join(hold(to)); + count(label, n); + } + for (const { re, replacement, label } of regexes) { + text = text.replace(re, (...m) => { + count(label); + return hold(replacement(...m)); + }); + } + + // Every rule has run; only now do the values it wrote appear. + text = release(text); + for (const [token, value] of masks) text = text.split(token).join(value); + + if (text !== original) { + touched.add(file); + if (!dryRun) fs.writeFileSync(file, text); + } +} + +console.log(`rebrand${dryRun ? " (dry-run)" : ""}: ${touched.size} file(s) affected`); +for (const [label, n] of counts) console.log(` ${String(n).padStart(5)} ${label}`); +if (dryRun) process.exit(0); + +const residue = sweep(trackedFiles(), allowedTargets); +if (residue.length > 0) { + console.error(`rebrand: ${residue.length} baseline-identity leftover(s) after rename:`); + for (const r of residue) console.error(` ${r}`); + process.exit(1); +} +console.log("rebrand: leftover sweep clean."); diff --git a/tooling/rebrand/values.example.json b/tooling/rebrand/values.example.json new file mode 100644 index 0000000..d02c419 --- /dev/null +++ b/tooling/rebrand/values.example.json @@ -0,0 +1,8 @@ +{ + "reponame": "acme-notes", + "productname": "Acme Notes", + "productdomain": "acme.dev", + "githuborg": "acme-inc", + "subdomain": "acme", + "orunWorkspace": "ws_XXXXXXXX" +} diff --git a/tooling/wire/live.mjs b/tooling/wire/live.mjs index 4bbf7ac..6045445 100644 --- a/tooling/wire/live.mjs +++ b/tooling/wire/live.mjs @@ -6,7 +6,17 @@ // render.mjs. Fails loudly on any unresolved token. // // node live.mjs --template wrangler.template.jsonc --out wrangler.jsonc \ -// --components cloudflare-kv,cloudflare-r2 --envs stage,prod +// --components cloudflare-kv,cloudflare-r2 --env stage \ +// [--fixture wiring.fixture.json --fixture-envs dev] +// +// A VERIFY-ONLY ENVIRONMENT HAS NO WIRING DOCUMENT. `dev` deploys nothing and +// no infra component applies there, so nothing ever publishes +// WIRING_<COMPONENT>_DEV; its lane still builds and dry-deploys the Worker. +// `--fixture-envs` names those environments, and for them — only them — a +// missing document renders from the committed fixture instead. Every other +// environment needs the real document: a deploy job resolves it before its +// first step (the component's secretEnv), so a missing one here is a real +// fault, never a reason to deploy a placeholder id. import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; @@ -23,19 +33,27 @@ const out = arg("out"); const components = (arg("components") ?? "").split(",").filter(Boolean); const env = arg("env"); const envs = (arg("envs") ?? env ?? "stage,prod").split(",").filter(Boolean); -if (!template || !out || components.length === 0) { +const fixture = arg("fixture"); +const fixtureEnvs = new Set((arg("fixture-envs") ?? "").split(",").filter(Boolean)); +if (!template || !out || components.length === 0 || (fixtureEnvs.size > 0 && !fixture)) { console.error( - "usage: live.mjs --template <file> --out <file> --components a,b (--env stage | --envs stage,prod)", + "usage: live.mjs --template <file> --out <file> --components a,b (--env stage | --envs stage,prod) [--fixture <file> --fixture-envs dev]", ); process.exit(2); } +const fixtureMap = fixture ? JSON.parse(fs.readFileSync(fixture, "utf8")) : {}; const dir = fs.mkdtempSync(path.join(os.tmpdir(), "wiring-")); const missing = []; +const fromFixture = []; for (const component of components) { for (const env of envs) { const key = `WIRING_${component.toUpperCase().replace(/-/g, "_")}_${env.toUpperCase()}`; - const value = process.env[key]; + let value = process.env[key]; + if (!value && fixtureEnvs.has(env) && fixtureMap[`${component}/${env}`]) { + value = JSON.stringify(fixtureMap[`${component}/${env}`]); + fromFixture.push(`${component}/${env}`); + } if (!value) { missing.push(key); continue; @@ -46,8 +64,12 @@ for (const component of components) { if (missing.length > 0) { console.error("wire: missing wiring documents in the environment:"); for (const m of missing) console.error(` ${m}`); + fs.rmSync(dir, { recursive: true, force: true }); process.exit(1); } +for (const f of fromFixture) { + console.log(`wire: ${f} is verify-only — rendered from ${path.basename(fixture)}, not a published document`); +} // A single-environment render (the workers-assets composition deploys one // environment per job, with no wrangler `--env`): `__ENV__` in the template diff --git a/tooling/wire/render.mjs b/tooling/wire/render.mjs index 72a4d42..188154c 100644 --- a/tooling/wire/render.mjs +++ b/tooling/wire/render.mjs @@ -91,8 +91,18 @@ if (/@@wiring\([a-z0-9-]+\/[a-z0-9-]+:[a-zA-Z0-9_]+\)@@/.test(rendered)) { process.exit(1); } +// The output says what it is. The template's own header comment (its leading +// `//` lines) describes the template, so it is replaced by one that names the +// source: a rendered config is never the file to edit. +const body = rendered.replace(/^(?:\/\/[^\n]*\n)+/, ""); +const banner = [ + `// GENERATED from ${path.basename(templatePath)} by tooling/wire — edit the`, + "// template, not this file. The committed copy is the fixture render", + "// (`pnpm run wire:fixture`); every Orun lane renders its own environment.", + "", +].join("\n"); fs.mkdirSync(path.dirname(path.resolve(outPath)), { recursive: true }); -fs.writeFileSync(outPath, rendered); +fs.writeFileSync(outPath, banner + body); console.log( `wire: rendered ${path.basename(outPath)} from ${path.basename(templatePath)} (${sources.size} wiring source(s))`, );