From cf91dfec510e537da19b7991741f3e0f9cc8d0b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 18 Oct 2026 14:17:38 +0000 Subject: [PATCH 1/3] =?UTF-8?q?CR5:=20the=20cirrus=20standard=20=E2=80=94?= =?UTF-8?q?=20no=20kiox,=20generated=20component=20docs,=20the=20context?= =?UTF-8?q?=20pack?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove kiox.yaml/kiox.lock and their two blueprint modules: nothing ran the kiox pin (v2.15.0); every workflow pins orun through orun-action. - Generate docs/{overview,architecture,runbook}.md for every component from what it declares (tooling/catalog/gen-component-docs.py), and fail Baseline CI when they drift (--check). - Add ai/context/{current,decisions,open-risks}.md (this repository's own; nothing places them). - Close out CR4 (shipped in #5, tagged baseline-v1) and record CR5 (CR-6). - Make the docs say what CR4 built: the epic README's summary and the status file's "Vercel Cron → Cron Triggers" describe one every-minute trigger dispatching the seven schedules (no seven triggers, no intervalFor); "Versions" no longer calls apps/web/README.md upstream's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D8AmgTwmnp4M8mgmnS9aha --- .github/workflows/baseline.yml | 6 + ai/context/current.md | 43 ++ ai/context/decisions.md | 20 + ai/context/open-risks.md | 16 + apps/web/docs/architecture.md | 31 ++ apps/web/docs/overview.md | 20 + apps/web/docs/runbook.md | 40 ++ .../cloudflare-kv/docs/architecture.md | 29 + .../terraform/cloudflare-kv/docs/overview.md | 19 + infra/terraform/cloudflare-kv/docs/runbook.md | 20 + kiox.lock | 11 - kiox.yaml | 6 - repo-blueprint.yaml | 12 +- specs/epics/README.md | 2 +- .../cron-starter/IMPLEMENTATION-STATUS.md | 66 ++- specs/epics/cron-starter/README.md | 9 +- specs/epics/cron-starter/epic.yaml | 7 + .../epics/cron-starter/implementation-plan.md | 27 +- tasks/CR-6.TaskContract.yaml | 28 + testing/phases.test.sh | 2 +- tests/web/docs/architecture.md | 11 + tests/web/docs/overview.md | 18 + tests/web/docs/runbook.md | 26 + tooling/catalog/gen-component-docs.py | 519 ++++++++++++++++++ tooling/rebrand/rebrand.mjs | 1 - 25 files changed, 942 insertions(+), 47 deletions(-) create mode 100644 ai/context/current.md create mode 100644 ai/context/decisions.md create mode 100644 ai/context/open-risks.md create mode 100644 apps/web/docs/architecture.md create mode 100644 apps/web/docs/overview.md create mode 100644 apps/web/docs/runbook.md create mode 100644 infra/terraform/cloudflare-kv/docs/architecture.md create mode 100644 infra/terraform/cloudflare-kv/docs/overview.md create mode 100644 infra/terraform/cloudflare-kv/docs/runbook.md delete mode 100644 kiox.lock delete mode 100644 kiox.yaml create mode 100644 tasks/CR-6.TaskContract.yaml create mode 100644 tests/web/docs/architecture.md create mode 100644 tests/web/docs/overview.md create mode 100644 tests/web/docs/runbook.md create mode 100644 tooling/catalog/gen-component-docs.py diff --git a/.github/workflows/baseline.yml b/.github/workflows/baseline.yml index 336b176..fa83614 100644 --- a/.github/workflows/baseline.yml +++ b/.github/workflows/baseline.yml @@ -51,6 +51,12 @@ jobs: echo "── $t" bash "testing/$t.test.sh" done + # Every component's docs/{overview,architecture,runbook}.md is generated + # from what the component declares (its manifest, Worker config, + # Terraform, migrations, package scripts). A pull request that changes + # one of those facts without regenerating the pages fails here. + - name: Component docs match their manifests + run: python3 tooling/catalog/gen-component-docs.py --check # Tier 1. THE BLUEPRINT, READ AND PLACED BY THE BINARY A BOOTSTRAP RUNS. # diff --git a/ai/context/current.md b/ai/context/current.md new file mode 100644 index 0000000..e89f8e5 --- /dev/null +++ b/ai/context/current.md @@ -0,0 +1,43 @@ +# cron-starter — where this repository stands + +The entry page for anyone (or any agent) picking this repository up. It is +this repository's own state and does not ship to a product built from it; the +two pages that do are [operations.md](operations.md) and +[deployment.md](deployment.md). + +## What it is + +Vercel's Cron Jobs example on Cloudflare Workers + Static Assets through +`@opennextjs/cloudflare`: one every-minute Cron Trigger per Worker whose +`scheduled` handler runs the template's seven schedules as the requests Vercel +used to make, the records in a Workers KV namespace. Packaged as an Orun +baseline: `orun new --blueprint repo-blueprint.yaml` builds a new product in +its own repository and takes it to live on stage and prod in one landing +(`01-product`) — the KV namespace applied before the Worker that binds it, +the deploy's smoke reading a run the trigger recorded — then records what +went live (`02-docs`). + +## Release + +| | | +|---|---| +| Latest tag | `baseline-v1` (CR4, [#5](https://github.com/sourceplane/cron-starter/pull/5)) | +| On `main` since | CR5 — the cirrus standard (no kiox, generated component docs, this context pack) | +| Proven live | No. Everything short of the platform is proven offline in Baseline CI, the trigger fired by hand at crafted times; the token minted, a real KV apply, a real deploy registering its trigger and the trigger firing on Cloudflare's clock are still to come (risk CR-K) | + +## Where to read + +| Question | Page | +|---|---| +| What shipped, and every departure from upstream | `specs/epics/cron-starter/IMPLEMENTATION-STATUS.md` | +| Why it is built this way | [decisions.md](decisions.md), then `specs/epics/cron-starter/design.md` | +| What could still go wrong | [open-risks.md](open-risks.md), then `specs/epics/cron-starter/risks-and-open-questions.md` | +| How to instantiate it | `BOOTSTRAP.md`, `docs/phases/` | +| What each component is | `apps/web/docs/`, `infra/terraform/cloudflare-kv/docs/`, `tests/web/docs/` (generated; `python3 tooling/catalog/gen-component-docs.py`) | + +## Next + +1. Bootstrap one product from the next tag against a workspace and record + its timings, including how long the first trigger took to fire (closes + CR-K). +2. Cut the next `baseline-vN` with `tag.yml` so the registry can pin CR5. diff --git a/ai/context/decisions.md b/ai/context/decisions.md new file mode 100644 index 0000000..a09bb83 --- /dev/null +++ b/ai/context/decisions.md @@ -0,0 +1,20 @@ +# cron-starter — decisions + +The choices that shape this repository, one line each, with where the full +reasoning lives. Superseded decisions stay listed, marked, so the history +reads in order. + +| # | Decision | Why | Source | +|---|---|---|---| +| 1 | OpenNext on Workers + Static Assets, the static-assets incremental cache | The template is a Next.js pages-router app; its API routes run inside the Worker unchanged | `specs/epics/cron-starter/design.md` §2 | +| 2 | One Worker: a custom entry (`worker.ts`) re-exports the generated fetch handler and adds `scheduled`, which calls the route in-process with a synthetic request | A second cron Worker would be another deployable and another render for a dozen-line handler | design.md §7 | +| 3 | `lib/kv.ts` mirrors `@vercel/kv`'s `set`/`get` over the `KV` binding | The routes change only their import | design.md §2 | +| 4 | ONE Cron Trigger per Worker (`* * * * *`); the handler runs every schedule in `lib/crons.ts` due at the trigger's `scheduledTime`. Supersedes CR1–CR3's seven triggers per Worker | Cloudflare caps Cron Triggers per account (five on Workers Free), and the platform cannot check a plan before a deploy | risks CR-B, CR-N | +| 5 | `wrangler.jsonc` is rendered per environment from the KV root's wiring document, and committed as the fixture render; `dev` renders the fixture | The deploy lane checks the file exists before it builds; no root applies to `dev` | risks CR-H, CR-I, design.md §4 | +| 6 | The deploy's smoke reads `/api/data/1m` for a run from the last ten minutes | It proves the trigger and the binding; a first deploy is covered by the landing's resumes | risk CR-J | +| 7 | One landing (`01-product`) then the record (`02-docs`); the plan applies the namespace before the Worker (`dependsOn: cloudflare-kv`, enforced on `main`, advisory on a pull request) | A landing has a fixed cost; the plan, not the phases, carries deploy order (cirrus-baseline since `baseline-v22`) | design.md §8 | +| 8 | The page's name and source link are one seam (`lib/site.ts`); the Open Graph image is absolute on the request's own origin | The rename rewrites one file; no configured site URL | IMPLEMENTATION-STATUS (CR4) | +| 9 | The cron route stays public, as upstream | Upstream sets no `CRON_SECRET`; the guard's shape is documented | risk CR-A | +| 10 | `ci.yml` plans nothing while `intent.yaml` names `ws_CHANGE_ME`; `checks.yml` runs on pull requests only | A bootstrap cannot set a repository variable (replaced the `ORUN_CI` gate); the convergence watch takes the newest run on the merge sha from any workflow | IMPLEMENTATION-STATUS (CR4) | +| 11 | stack-tectonic 0.19.0, not 0.20.0 | 0.20.0's lane-scoped install is refused by Next 16's Turbopack | IMPLEMENTATION-STATUS (CR4), `intent.yaml` | +| 12 | orun is pinned only where it runs (the `orun-action` `version:` in each workflow); no kiox. Component docs are generated from the manifests and checked in CI | `kiox.yaml` pinned a version nothing ran; a hand-written copy of the dependency graph and bindings drifts silently | IMPLEMENTATION-STATUS (CR5), `tooling/catalog/gen-component-docs.py` | diff --git a/ai/context/open-risks.md b/ai/context/open-risks.md new file mode 100644 index 0000000..ae31d36 --- /dev/null +++ b/ai/context/open-risks.md @@ -0,0 +1,16 @@ +# cron-starter — open risks + +What is not yet proven or not yet decided. The full write-up of every risk, +including the accepted and resolved ones, is +`specs/epics/cron-starter/risks-and-open-questions.md`; this page lists only +what is still live, so it should be short. + +| ID | Risk | State | What closes it | +|---|---|---|---| +| CR-K | No live bootstrap yet: the repository created and linked, the token minted, a real `terraform apply`, a real `wrangler deploy` registering its trigger, the trigger firing on Cloudflare's clock and the probes are all unproven | OPEN | One bootstrap from a tag against a workspace | + +Accepted, and worth knowing before you change them: CR-A (the cron route is +public, as upstream), CR-C (KV is eventually consistent), CR-D (Hacker News +at request time), CR-J (the first deploy's smoke waits on the trigger), CR-L +(the bootstrap floor plans every edge enforced), CR-M (a custom domain is the +owner's step), CR-N (seven schedules on one trigger). diff --git a/apps/web/docs/architecture.md b/apps/web/docs/architecture.md new file mode 100644 index 0000000..02c497d --- /dev/null +++ b/apps/web/docs/architecture.md @@ -0,0 +1,31 @@ +# web — architecture + +Built by the turbo pipeline from `apps/web` and deployed with wrangler. + +| | | +|---|---| +| Worker config | `apps/web/wrangler.template.jsonc` | +| Entry | `worker.ts` | +| Compatibility date | `2026-10-01` | +| Compatibility flags | `nodejs_compat`, `global_fetch_strictly_public` | + +## Bindings + +| Binding | Kind | Source | +|---|---|---| +| `KV` | Workers KV namespace | `app_kv_id` from `cloudflare-kv` | +| `ASSETS` | Static assets | `.open-next/assets` | + +Identifiers marked *from* a component are filled in at deploy time from +that component's published outputs for the environment being deployed. + +## Scheduled triggers + +- `* * * * *` + +## Wiring + +Resolved at deploy time from secrets the infrastructure lanes publish (names only): + +- `WIRING_CLOUDFLARE_KV_PROD` +- `WIRING_CLOUDFLARE_KV_STAGE` diff --git a/apps/web/docs/overview.md b/apps/web/docs/overview.md new file mode 100644 index 0000000..0a74e1c --- /dev/null +++ b/apps/web/docs/overview.md @@ -0,0 +1,20 @@ +# web + +The cron example (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, with Cron Triggers driving its API routes, per environment) + +A Cloudflare Worker with Static Assets (server rendering plus static files), deployed per environment by its CI lane. + +| | | +|---|---| +| Type | `cloudflare-workers-assets-turbo` | +| Source | `apps/web` | +| Package | `@app/web` | +| Environments | `dev`: `verify` · `stage`: `verify`, `deploy` on a push to `main` · `prod`: `verify`, `deploy` on a push to `main` | + +## Depends on + +- **cloudflare-kv** — Provisions the Cloudflare KV namespace the app binds (stage and prod) + +## Depended on by + +- (none) diff --git a/apps/web/docs/runbook.md b/apps/web/docs/runbook.md new file mode 100644 index 0000000..18c8c86 --- /dev/null +++ b/apps/web/docs/runbook.md @@ -0,0 +1,40 @@ +# web — runbook + +## How it runs + +Pull requests verify it; a merge to `main` deploys it to `stage`, `prod`. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Local commands + +```bash +pnpm --filter @app/web dev +pnpm --filter @app/web build +pnpm --filter @app/web typecheck +pnpm --filter @app/web lint +pnpm --filter @app/web preview +``` + +## Verify + +After a deploy the lane runs this smoke against the environment it +deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL: + +```bash +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 ] +``` + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream + has not applied for this environment yet. Within one convergence the plan + runs it first; on its own, re-run that lane. +- **The smoke fails right after a first deploy**: a new workers.dev route can + answer 4xx for a few seconds and the lane retries. A failure that persists + is a regression in the deployed code. diff --git a/infra/terraform/cloudflare-kv/docs/architecture.md b/infra/terraform/cloudflare-kv/docs/architecture.md new file mode 100644 index 0000000..4ed1148 --- /dev/null +++ b/infra/terraform/cloudflare-kv/docs/architecture.md @@ -0,0 +1,29 @@ +# cloudflare-kv — architecture + +A `terraform` root at `infra/terraform/cloudflare-kv/terraform`. + +- **State** lives in the Orun Cloud HTTP state backend — no local state and + no state bucket to manage. +- **Credentials are brokered per run** from the workspace's provider + connections and resolved by name; none is stored in this repository. +- **Adoption** (`adopt.tf`): when state is empty but the resource already + exists, plan-time import adopts it instead of failing. + +## Resources + +- `cloudflare_workers_kv_namespace.app_kv` + +## Published outputs + +Written as job-output secrets on each environment after an apply; deploy +lanes downstream resolve them by name. + +| Secret | Terraform output | +|---|---| +| `WIRING_CLOUDFLARE_KV` | `wiring` | + +## Resolved at run time (names only) + +- `CLOUDFLARE_ACCOUNT_ID` +- `CLOUDFLARE_API_TOKEN` +- `TF_VAR_cloudflare_account_id` diff --git a/infra/terraform/cloudflare-kv/docs/overview.md b/infra/terraform/cloudflare-kv/docs/overview.md new file mode 100644 index 0000000..720158a --- /dev/null +++ b/infra/terraform/cloudflare-kv/docs/overview.md @@ -0,0 +1,19 @@ +# cloudflare-kv + +Provisions the Cloudflare KV namespace the app binds (stage and prod) + +Terraform-managed infrastructure, planned and applied per environment by its CI lane. + +| | | +|---|---| +| Type | `terraform` | +| Source | `infra/terraform/cloudflare-kv` | +| Environments | `stage`: `plan-only`, `apply` on a push to `main` · `prod`: `plan-only`, `apply` on a push to `main` | + +## Depends on + +- (none) + +## Depended on by + +- **web** — The cron example (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, with Cron Triggers driving its API routes, per environment) diff --git a/infra/terraform/cloudflare-kv/docs/runbook.md b/infra/terraform/cloudflare-kv/docs/runbook.md new file mode 100644 index 0000000..b5db692 --- /dev/null +++ b/infra/terraform/cloudflare-kv/docs/runbook.md @@ -0,0 +1,20 @@ +# cloudflare-kv — runbook + +## How it runs + +Pull requests plan it; a merge to `main` applies it to `stage`, `prod`. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **Provider authentication fails**: the workspace's provider connection is + missing or revoked. Reconnect it in the console; credentials are brokered + from it per run. +- **"Already exists" on a first apply**: state is empty but the resource is + not. `adopt.tf` imports it at plan time; if it still fails, the resource was renamed outside Terraform. diff --git a/kiox.lock b/kiox.lock deleted file mode 100644 index 6e14690..0000000 --- a/kiox.lock +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: kiox.io/v1 -kind: WorkspaceLock -metadata: - name: example-platform -providers: - - alias: orun - provider: sourceplane/orun - source: ghcr.io/sourceplane/orun:v2.15.0 - version: v2.15.0 - resolved: ghcr.io/sourceplane/orun@sha256:1d28be8612dc8d8083b508f97cd71a24c090f6472c43c71f68455e3709a6a3c1 - store: e02472f57f2eb5fb5168b7d270ea547e5bffbf83824c4286abd7ba20f87cb9d1 diff --git a/kiox.yaml b/kiox.yaml deleted file mode 100644 index d654da0..0000000 --- a/kiox.yaml +++ /dev/null @@ -1,6 +0,0 @@ -apiVersion: kiox.io/v1 -kind: Workspace -metadata: - name: example-platform -providers: - orun: ghcr.io/sourceplane/orun:v2.15.0 diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml index 1217275..5e3f1bd 100644 --- a/repo-blueprint.yaml +++ b/repo-blueprint.yaml @@ -185,16 +185,6 @@ modules: 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 @@ -409,7 +399,7 @@ phases: 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] + modules: [ai-deployment, ai-operations, cloudflare-kv, discovery-roots, github-workflows, rebrand-values, root-gitignore, root-intent, root-package-json, root-pnpm-lock, root-pnpm-workspace, root-readme, root-turbo, tooling-eslint, tooling-tsconfig, tooling-wire, vscode, web, web-tests] # THE PLATFORM MUST BE ABLE TO SEE THE REPOSITORY BEFORE IT EXISTS. Every # phase lands a pull request that files under its task, and the platform # learns of a PR only through the GitHub App installation on the account diff --git a/specs/epics/README.md b/specs/epics/README.md index 155824f..a4583e1 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 — and an Orun baseline that instantiates it in one landing (CR4) | +| [`cron-starter/`](./cron-starter/) | **CR** | ✅ Shipped (`baseline-v1`); live bootstrap pending | 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 e9d0df8..8d76d17 100644 --- a/specs/epics/cron-starter/IMPLEMENTATION-STATUS.md +++ b/specs/epics/cron-starter/IMPLEMENTATION-STATUS.md @@ -9,20 +9,28 @@ 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` | +| CR4 — a baseline, in one landing | ✅ Shipped (offline-proven; no live bootstrap yet, risk CR-K) | [#5](https://github.com/sourceplane/cron-starter/pull/5) (CR-5), tagged `baseline-v1` | +| CR5 — the cirrus standard | ✅ Shipped | CR-6 — on `main` after `baseline-v1`, not yet tagged | ## Departures from the upstream template ### Vercel Cron → Cron Triggers through a custom worker entry -`vercel.json` is gone. Its seven `crons` are `triggers.crons` in -`wrangler.template.jsonc`, verbatim. `worker.ts` is wrangler's `main`: it -imports the generated `.open-next/worker.js` (with `@ts-ignore`, as the -OpenNext custom-worker howto does — the file exists only after the build), -re-exports its `fetch`, and adds `scheduled` from `lib/scheduled.ts`, which -maps the expression that fired to its interval (`lib/crons.ts`) and calls the -fetch handler with a synthetic `GET https://cron.internal/api/cron/`. -The component's `workerEntrypoint` is `worker.ts`, not `.open-next/worker.js`. +`vercel.json` is gone. Its seven `crons` are the table in `lib/crons.ts`, +verbatim, each with the interval whose route it called. The Worker registers +ONE Cron Trigger, `* * * * *` (`TRIGGER`, the only entry in `triggers.crons` +in `wrangler.template.jsonc`). `worker.ts` is wrangler's `main`: it imports +the generated `.open-next/worker.js` (with `@ts-ignore`, as the OpenNext +custom-worker howto does — the file exists only after the build), re-exports +its `fetch`, and adds `scheduled` from `lib/scheduled.ts`, which runs every +schedule whose expression matches the trigger's `scheduledTime` (UTC, +`dueIntervals`), one after another, each as a synthetic +`GET https://cron.internal/api/cron/` through the fetch handler, and +fails the invocation naming any route that failed. The component's +`workerEntrypoint` is `worker.ts`, not `.open-next/worker.js`. (Through CR3 +the seven expressions were seven `triggers.crons` entries and the handler +mapped the one that fired to its interval, `intervalFor`; CR4 replaced both — +"Departures from the port (CR4)" below, risks CR-B and CR-N.) ### `lib/kv.ts` replaces `@vercel/kv` @@ -94,8 +102,8 @@ Next `^16.0.10` → `16.3.8`; React 19; Tailwind `^3.2.7` (resolves 3.4); `@types/node` `^20` → `^22`; `swr` `^2.1.0` (resolves 2.5). Package name `@app/web`, a per-app `turbo.json`, `component.yaml`, the wrangler template 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. +`.gitignore` and `.env.example` are not carried. `apps/web/README.md` was +upstream's, verbatim, through CR3; CR4 replaced it with the app's own (below). ### The page's name and source link come from `lib/site.ts` (CR4) @@ -151,6 +159,42 @@ every product. | `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 | +## The cirrus standard (CR5) + +Nothing about the app changed. What changed is the baseline around it: + +| What | Before | After | Why | +|---|---|---|---| +| orun pin | `kiox.yaml` (v2.15.0) + `kiox.lock`, shipped to every product | gone; orun is pinned where it runs, the `orun-action` `version:` in each workflow | nothing ran the kiox pin, and it disagreed with the lanes (v2.78.4) | +| `root-kiox`, `root-kiox-lock` modules | in `01-product` | removed (`testing/phases.test.sh` and the rebrand's skip list follow) | a product is placed with 79 files (72 − 2 + 9): no kiox, plus the docs below | +| component docs | none | `apps/web/docs/`, `infra/terraform/cloudflare-kv/docs/`, `tests/web/docs/` — `overview.md`, `architecture.md`, `runbook.md` | cirrus-baseline documents every component; the workspace Docs library renders `docs/` beside each `component.yaml` | +| how the docs stay true | — | `tooling/catalog/gen-component-docs.py` derives them from the manifest, the Worker config (the one trigger included), Terraform, migrations and package scripts; Baseline CI runs it with `--check` | a hand-written copy of a manifest drifts silently | +| context pack | `operations.md`, `deployment.md` | plus `current.md`, `decisions.md`, `open-risks.md` | cirrus-baseline's shape; the three new pages are this repository's own and no module places them (the leak gate still allows exactly two) | +| status | CR4 "this PR, to be tagged"; the epic README's summary and "Vercel Cron → Cron Triggers" above still describing seven triggers and `intervalFor`; "Versions" calling `apps/web/README.md` upstream's | CR4 shipped ([#5](https://github.com/sourceplane/cron-starter/pull/5)) and tagged `baseline-v1`; one `* * * * *` trigger dispatching the seven schedules, as built; the README the app's | the documents had not caught up with the tag and with CR4 | + +## Verified (CR5) + +- `testing/{manifest,phases,coverage,rebrand,retouch,bootstrap-defer,wire}.test.sh` + green; `gen-component-docs.py --check` green (3 components, 9 pages). +- `testing/leak.test.sh` at v2.58.11 (the blueprint job's pin): 79 files + derived (72 − 2 kiox + 9 docs pages); `ai/context` still exactly the two + declared pages; 72 shipped sources name no factory path, the generated + pages included. +- `testing/placement.test.sh` at v2.78.4 (the lane pin, as `baseline.yml` + runs it — CR-L): 79 files placed, two landings, branded and re-tenanted, + the one `* * * * *` trigger kept; the product's own push-to-main plan + applies `cloudflare-kv` at level 0 and deploys `web` at level 1 on stage + and prod; on a pull request nothing waits; the 02-docs merge plans 0 jobs; + `--resume` a no-op. +- The Checks sequence: `pnpm install --frozen-lockfile`, `wire:fixture` (no + diff), typecheck, lint (no warnings), test (5 files, 34 tests), build + green. +- `testing/e2e.test.sh` at v2.78.4 green: the stage lane's four steps in the + staged job tree; under `wrangler dev --test-scheduled` the smoke refuses + the Worker before any trigger fired, the trigger at 8 crafted times runs + exactly the schedules due, all 7 records read back, and the smoke passes. +- `orun task check CR-6` complete. + ## Verified (CR4) - `orun new --status` reads the blueprint at v2.58.11 (the bootstrap floor), diff --git a/specs/epics/cron-starter/README.md b/specs/epics/cron-starter/README.md index b3f3933..eef9753 100644 --- a/specs/epics/cron-starter/README.md +++ b/specs/epics/cron-starter/README.md @@ -1,6 +1,6 @@ # Epic: cron-starter (CR) -**Vercel's Cron Jobs example is seven schedules and two API routes: a cron requests `/api/cron/`, which records the newest Hacker News story and the run time in KV; the page polls `/api/data/` and shows how long ago each interval last ran. On Cloudflare the seven schedules are Cron Triggers on the one Worker, a `scheduled` handler turns the expression that fired back into the request Vercel used to make, and the record lives in Workers KV — the namespace from Terraform through Orun, its id reaching the Worker through the Cirrus baseline's wiring documents. The routes and the page do not change; what calls the routes on schedule, and where they write, does.** +**Vercel's Cron Jobs example is seven schedules and two API routes: a cron requests `/api/cron/`, which records the newest Hacker News story and the run time in KV; the page polls `/api/data/` and shows how long ago each interval last ran. On Cloudflare one Cron Trigger fires the Worker every minute, its `scheduled` handler turns each of the seven schedules due at that minute back into the request Vercel used to make, and the record lives in Workers KV — the namespace from Terraform through Orun, its id reaching the Worker through the Cirrus baseline's wiring documents. The routes and the page do not change; what calls the routes on schedule, and where they write, does.** The port keeps the template's pages, API routes, component, styles and `@vercel/examples-ui` chrome. It adds `lib/kv.ts` (the `@vercel/kv` `set`/`get` surface over the `KV` binding, so the routes change only their import), a custom Worker entry that re-exports `@opennextjs/cloudflare`'s fetch handler and adds `scheduled`, the cron-to-interval table, the Workers build, the monorepo wrapper, a test package that exercises the table, the scheduled handler, the KV shim and the two routes against mocks, the KV Terraform root, and the deploy contract. `@vercel/analytics` becomes the Cloudflare Web Analytics beacon. @@ -8,15 +8,15 @@ The port keeps the template's pages, API routes, component, styles and `@vercel/ | Field | Value | |-------|-------| -| 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) | +| Status | ✅ Shipped — CR0–CR4 landed (#1–#5), tagged `baseline-v1`; CR5 (the cirrus standard, CR-6) on `main`, not yet tagged. KV apply, live deploy and the trigger on Cloudflare's clock proven only by a live bootstrap (risk CR-K) | +| Cluster | **CR** (CR0–CR5) | | 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 — 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 | +| Shipped as | `baseline-v1` ([#5](https://github.com/sourceplane/cron-starter/pull/5)), then CR5 on `main`; proven offline (Baseline CI), deploy gated until a workspace is linked | ## Read order @@ -34,3 +34,4 @@ The port keeps the template's pages, API routes, component, styles and `@vercel/ | 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 | +| CR5 — the cirrus standard | no kiox, generated component docs, the context pack, status that agrees with the tags | Baseline CI green with the docs check | diff --git a/specs/epics/cron-starter/epic.yaml b/specs/epics/cron-starter/epic.yaml index 5452d48..34b7a22 100644 --- a/specs/epics/cron-starter/epic.yaml +++ b/specs/epics/cron-starter/epic.yaml @@ -41,3 +41,10 @@ spec: - "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] + - name: "CR5 — the cirrus standard" + exitCriteria: + - "no file outside this milestone's own record names kiox: orun is pinned where CI runs it (the orun-action `version:` in each workflow)" + - "every component carries generated docs/{overview,architecture,runbook}.md, and Baseline CI fails a pull request whose manifests and pages disagree" + - "ai/context carries this repository's current.md, decisions.md and open-risks.md, and none of them ships to a product" + - "every milestone's status row agrees with the tags" + tasks: [CR-6] diff --git a/specs/epics/cron-starter/implementation-plan.md b/specs/epics/cron-starter/implementation-plan.md index 9aa25d5..5c9896e 100644 --- a/specs/epics/cron-starter/implementation-plan.md +++ b/specs/epics/cron-starter/implementation-plan.md @@ -65,9 +65,34 @@ schedules dispatched from its scheduled time (inside Workers Free), the - the status file records what is proven offline and what only a live bootstrap can prove +## CR5 — the cirrus standard ✅ + +Bring the baseline to cirrus-baseline's standard, with nothing about the app +itself changing. + +- **No kiox.** `kiox.yaml`/`kiox.lock` pinned an orun (v2.15.0) that nothing + ran: every workflow installs orun itself through `orun-action` with its own + `version:`. The files, their two modules and the rebrand's skip entry go. +- **Component docs.** `tooling/catalog/gen-component-docs.py` writes each + component's `docs/overview.md`, `docs/architecture.md` and `docs/runbook.md` + from what the component declares, as cirrus-baseline's do; the pages ship + with the component. Baseline CI runs it with `--check`. +- **The context pack.** `ai/context/current.md`, `decisions.md` and + `open-risks.md` beside the two pages a product ships with — this + repository's own, so no module places them. +- **Status that agrees with the tags.** CR4 is shipped and tagged; the epic + README and the status file describe the one trigger CR4 built. + +**Done when** +- `git grep -i kiox` finds nothing outside this milestone's own record + (`specs/`, `tasks/`, `ai/context/`), and the leak gate and the offline + bootstrap pass without the two modules +- the docs check is green in Baseline CI +- this file, the status file and `epic.yaml` agree + ## After CR4 (outside this repository) -1. Cut `baseline-v1` with `tag.yml` from the merged `main`. +1. Cut `baseline-v1` with `tag.yml` from the merged `main`. ✅ Done. 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 diff --git a/tasks/CR-6.TaskContract.yaml b/tasks/CR-6.TaskContract.yaml new file mode 100644 index 0000000..880f681 --- /dev/null +++ b/tasks/CR-6.TaskContract.yaml @@ -0,0 +1,28 @@ +apiVersion: orun.io/v1 +kind: TaskContract +metadata: + name: CR-6 + title: "The cirrus standard" +spec: + goal: The baseline meets cirrus-baseline's standard — no kiox pin (orun is pinned where CI runs it), every component documented by generated overview/architecture/runbook pages that CI keeps in step with the manifests, the agent context pack, and status documents that agree with the tags + affects: + - kiox.yaml + - kiox.lock + - repo-blueprint.yaml + - testing/phases.test.sh + - tooling/rebrand/** + - tooling/catalog/** + - .github/workflows/baseline.yml + - apps/web/docs/** + - infra/terraform/cloudflare-kv/docs/** + - tests/web/docs/** + - ai/context/** + - specs/** + - tasks/** + doneWhen: + - no file outside this milestone's own record names kiox, and the leak gate and the offline bootstrap place a product without it + - every component has docs/overview.md, docs/architecture.md and docs/runbook.md, and `python3 tooling/catalog/gen-component-docs.py --check` is green in Baseline CI + - ai/context carries current.md, decisions.md and open-risks.md for this repository (none of them ships) + - every milestone's status row agrees with the tags + gates: + - checks diff --git a/testing/phases.test.sh b/testing/phases.test.sh index 5307316..701589d 100755 --- a/testing/phases.test.sh +++ b/testing/phases.test.sh @@ -43,7 +43,7 @@ if not phases: 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-package-json", "root-pnpm-lock", "root-pnpm-workspace", "root-readme", "root-turbo", "tooling-eslint", "tooling-tsconfig", "tooling-wire", "vscode", "web", "web-tests"], "02-docs": [], diff --git a/tests/web/docs/architecture.md b/tests/web/docs/architecture.md new file mode 100644 index 0000000..2a0c201 --- /dev/null +++ b/tests/web/docs/architecture.md @@ -0,0 +1,11 @@ +# web-tests — architecture + +A test package at `tests/web`. Its lane runs the suite before it builds. + +## Suites (5) + +- `api.test.ts` +- `crons.test.ts` +- `kv.test.ts` +- `scheduled.test.ts` +- `site.test.ts` diff --git a/tests/web/docs/overview.md b/tests/web/docs/overview.md new file mode 100644 index 0000000..6e02b2d --- /dev/null +++ b/tests/web/docs/overview.md @@ -0,0 +1,18 @@ +# web-tests + +The test suite for **web**. It deploys nothing: its lane installs, builds and runs the tests. + +| | | +|---|---| +| Type | `turbo-package` | +| Source | `tests/web` | +| Package | `@app/web-tests` | +| Environments | `dev`: `quick-check` | + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/tests/web/docs/runbook.md b/tests/web/docs/runbook.md new file mode 100644 index 0000000..c687de2 --- /dev/null +++ b/tests/web/docs/runbook.md @@ -0,0 +1,26 @@ +# web-tests — runbook + +## How it runs + +Its lane runs on every pull request that changes it; it has no deployed surface. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Local commands + +```bash +pnpm --filter @app/web-tests build +pnpm --filter @app/web-tests test +pnpm --filter @app/web-tests typecheck +pnpm --filter @app/web-tests lint +``` + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **A dependent fails to build after a change here**: run `pnpm typecheck` + across the workspace before merging. diff --git a/tooling/catalog/gen-component-docs.py b/tooling/catalog/gen-component-docs.py new file mode 100644 index 0000000..2a6a8b8 --- /dev/null +++ b/tooling/catalog/gen-component-docs.py @@ -0,0 +1,519 @@ +#!/usr/bin/env python3 +"""Generate each component's docs (overview / architecture / runbook). + + python3 tooling/catalog/gen-component-docs.py # write + python3 tooling/catalog/gen-component-docs.py --check # fail on drift (CI) + +The Orun workspace's Docs library renders the `docs/` folder next to every +`component.yaml`. These pages are generated, not hand-written, because almost +everything in them is already declared somewhere CI validates: the component's +manifest (type, description, dependencies, environments, the secrets a lane +resolves, the smoke), its Worker config (bindings, triggers, the wiring the +deploy fills in), its Terraform (resources and outputs), its migrations and its +package scripts. A hand-written copy of those facts drifts the first time one +changes; a generated one cannot, because `--check` fails the pull request that +changes the fact without the page. + +What is NOT derivable (why a component exists, what a failure means for this +product in particular) belongs in the component's `description` and in the +product's own docs, not here. + +The pages ship with the component into every product built from this tree, so +they say nothing about where they came from: no factory paths, no generator +path, no provenance. Zero dependencies beyond PyYAML. +""" + +from __future__ import annotations + +import json +import pathlib +import re +import sys + +try: + import yaml +except ImportError: # pragma: no cover - the contract job installs it + sys.exit("gen-component-docs needs PyYAML (pip install pyyaml)") + +ROOT = pathlib.Path(__file__).resolve().parents[2] +ROOTS = ("apps", "packages", "infra", "tests") +SKIP_DIRS = {"node_modules", "dist", ".turbo", "docs", ".next", ".open-next", + ".wrangler", ".svelte-kit", ".nuxt", ".output", ".astro", "coverage"} + +# Paths a shipped page must never name: products are not placed with them. +FACTORY = re.compile( + r"repo-blueprint|BOOTSTRAP\.md|(? str: + """JSONC → JSON: drop comments outside strings, then trailing commas.""" + out, i, n, in_str = [], 0, len(text), False + while i < n: + c = text[i] + if in_str: + out.append(c) + if c == "\\" and i + 1 < n: + out.append(text[i + 1]) + i += 2 + continue + if c == '"': + in_str = False + i += 1 + continue + if c == '"': + in_str = True + out.append(c) + i += 1 + elif text.startswith("//", i): + j = text.find("\n", i) + i = n if j < 0 else j + elif text.startswith("/*", i): + j = text.find("*/", i + 2) + i = n if j < 0 else j + 2 + else: + out.append(c) + i += 1 + return re.sub(r",(\s*[}\]])", r"\1", "".join(out)) + + +def read_json(path: pathlib.Path) -> dict | None: + try: + return json.loads(strip_jsonc(path.read_text(encoding="utf-8"))) + except (OSError, ValueError): + return None + + +def rel(p: pathlib.Path) -> str: + return p.relative_to(ROOT).as_posix() + + +def discover() -> list[dict]: + found = [] + for root in ROOTS: + base = ROOT / root + if not base.is_dir(): + continue + stack = [base] + while stack: + d = stack.pop() + for entry in sorted(d.iterdir()): + if entry.is_dir(): + if entry.name in SKIP_DIRS or entry.name.startswith("."): + continue + if (entry / "main.tf").exists() and not (entry / "component.yaml").exists(): + continue + if len(entry.relative_to(base).parts) <= 3: + stack.append(entry) + elif entry.name == "component.yaml": + found.append(read_component(entry)) + comps = [c for c in found if c["name"] and c["type"]] + return sorted(comps, key=lambda c: c["name"]) + + +def read_component(file: pathlib.Path) -> dict: + doc = yaml.safe_load(file.read_text(encoding="utf-8")) or {} + meta, spec = doc.get("metadata") or {}, doc.get("spec") or {} + params = spec.get("parameters") or {} + deps = [d.get("component") for d in (spec.get("dependsOn") or []) if isinstance(d, dict)] + envs = [] + for e in ((spec.get("subscribe") or {}).get("environments") or []): + rules = [(r.get("profile"), ((r.get("when") or {}).get("triggerRef"))) + for r in (e.get("profileRules") or [])] + envs.append({"name": e.get("name"), "profile": e.get("profile"), "rules": rules}) + return { + "dir": file.parent, + "path": rel(file.parent), + "name": meta.get("name"), + "description": (meta.get("description") or "").strip(), + "type": spec.get("type"), + "deps": [d for d in deps if d], + "secret_env": sorted((spec.get("secretEnv") or {}).keys()), + "envs": envs, + "params": params, + "migrations_path": spec.get("path") if spec.get("type") == "db-migrate" else None, + } + + +def package_of(c: dict) -> dict | None: + return read_json(c["dir"] / "package.json") + + +def worker_config(c: dict) -> tuple[str | None, dict | None]: + """The config a deploy uses: the template when wiring renders one.""" + names = ["wrangler.template.jsonc", c["params"].get("wranglerConfig") or "", + "wrangler.jsonc", "wrangler.json"] + for name in names: + if name and (c["dir"] / name).is_file(): + return name, read_json(c["dir"] / name) + return None, None + + +WIRING = re.compile(r"@@wiring\(([^/)]+)/__ENV__:([^)]+)\)@@") + + +def wired(value) -> str | None: + m = WIRING.search(str(value)) if value is not None else None + return f"`{m.group(2)}` from `{m.group(1)}`" if m else None + + +def bindings(cfg: dict) -> list[tuple[str, str, str]]: + rows = [] + for kv in cfg.get("kv_namespaces") or []: + rows.append((kv.get("binding"), "Workers KV namespace", wired(kv.get("id")) or "declared in the config")) + for b in cfg.get("r2_buckets") or []: + rows.append((b.get("binding"), "R2 bucket", wired(b.get("bucket_name")) or f"`{b.get('bucket_name')}`")) + for d in cfg.get("d1_databases") or []: + rows.append((d.get("binding"), "D1 database", wired(d.get("database_id")) or "declared in the config")) + for h in cfg.get("hyperdrive") or []: + rows.append((h.get("binding"), "Hyperdrive (pooled Postgres)", wired(h.get("id")) or "declared in the config")) + if isinstance(cfg.get("ai"), dict) and cfg["ai"].get("binding"): + rows.append((cfg["ai"]["binding"], "Workers AI", "account-level; no resource to provision")) + for d in ((cfg.get("durable_objects") or {}).get("bindings") or []): + rows.append((d.get("name"), "Durable Object", f"class `{d.get('class_name')}`")) + for s in cfg.get("services") or []: + rows.append((s.get("binding"), "Service binding", f"Worker `{s.get('service')}`")) + for q in ((cfg.get("queues") or {}).get("producers") or []): + rows.append((q.get("binding"), "Queue producer", f"queue `{q.get('queue')}`")) + for r in cfg.get("ratelimits") or []: + simple = r.get("simple") or {} + rows.append((r.get("name"), "Rate limiter", + f"{simple.get('limit')} requests / {simple.get('period')}s per location")) + assets = cfg.get("assets") or {} + if assets.get("binding"): + rows.append((assets["binding"], "Static assets", f"`{assets.get('directory')}`")) + return [r for r in rows if r[0]] + + +def tf_facts(c: dict) -> dict: + tf_dir = c["dir"] / (c["params"].get("terraformDir") or "terraform") + resources, outputs, variables, backend = [], [], [], None + for f in sorted(tf_dir.glob("*.tf")) if tf_dir.is_dir() else []: + text = f.read_text(encoding="utf-8") + resources += [f"{t}.{n}" for t, n in re.findall(r'^resource\s+"([^"]+)"\s+"([^"]+)"', text, re.M)] + outputs += re.findall(r'^output\s+"([^"]+)"', text, re.M) + variables += re.findall(r'^variable\s+"([^"]+)"', text, re.M) + m = re.search(r'backend\s+"([^"]+)"', text) + backend = backend or (m.group(1) if m else None) + imports = (tf_dir / "adopt.tf").is_file() if tf_dir.is_dir() else False + return {"dir": rel(tf_dir) if tf_dir.is_dir() else None, "resources": resources, + "outputs": outputs, "variables": variables, "backend": backend, "adopt": imports} + + +def published(c: dict) -> list[tuple[str, str]]: + spec = c["params"].get("secretOutputs") or "" + pairs = [] + for part in str(spec).split(","): + if "=" in part: + k, v = part.split("=", 1) + pairs.append((k.strip(), v.strip())) + return pairs + + +def test_files(c: dict) -> list[str]: + out = [] + for p in sorted(c["dir"].rglob("*")): + if any(part in SKIP_DIRS for part in p.relative_to(c["dir"]).parts): + continue + if p.is_file() and re.search(r"\.(test|spec)\.(ts|tsx|js|mjs|cjs)$", p.name): + out.append(p.name) + return out + + +def migrations(c: dict) -> list[str]: + path = c["migrations_path"] + if not path: + return [] + d = ROOT / path + if not d.is_dir(): + return [] + return sorted(p.name for p in d.iterdir() if p.is_dir() or p.suffix == ".sql") + + +# ── phrasing ───────────────────────────────────────────────────────────── + +KIND = { + "cloudflare-worker-turbo": "A Cloudflare Worker, deployed per environment by its CI lane.", + "cloudflare-workers-assets-turbo": "A Cloudflare Worker with Static Assets (server rendering plus " + "static files), deployed per environment by its CI lane.", + "terraform": "Terraform-managed infrastructure, planned and applied per environment by its CI lane.", + "db-migrate": "Applies this repository's ordered database migrations per environment: " + "plan on pull requests, apply on merge to `main`.", + "turbo-package": "A workspace package built by the turbo pipeline. It deploys nothing itself: " + "its lane type-checks, lints, tests and builds it.", +} + +TRIGGER = {"github-push-main": "a push to `main`", "github-pull-request": "a pull request"} + + +def env_line(e: dict) -> str: + s = f"`{e['name']}`: `{e['profile']}`" + for profile, ref in e["rules"]: + s += f", `{profile}` on {TRIGGER.get(ref, f'`{ref}`')}" + return s + + +def is_tests(c: dict) -> bool: + return c["name"].endswith("-tests") or c["path"].startswith("tests/") + + +def subject_of(c: dict, by_name: dict) -> str | None: + if c["name"].endswith("-tests"): + s = c["name"][: -len("-tests")] + return s if s in by_name else None + return None + + +def bullet_list(names: list[str], by_name: dict) -> list[str]: + if not names: + return ["- (none)"] + out = [] + for n in names: + d = by_name.get(n) + out.append(f"- **{n}** — {d['description']}" if d and d["description"] else f"- **{n}**") + return out + + +# ── pages ──────────────────────────────────────────────────────────────── + +def overview(c: dict, by_name: dict, dependents: list[str]) -> str: + pkg = package_of(c) + kind = KIND.get(c["type"], f"A `{c['type']}` component.") + subject = subject_of(c, by_name) + if is_tests(c): + kind = (f"The test suite for **{subject}**. " if subject else "A test suite. ") + \ + "It deploys nothing: its lane installs, builds and runs the tests." + lines = [f"# {c['name']}", ""] + if c["description"]: + lines += [c["description"], ""] + lines += [kind, "", "| | |", "|---|---|", f"| Type | `{c['type']}` |", f"| Source | `{c['path']}` |"] + if pkg and pkg.get("name"): + lines.append(f"| Package | `{pkg['name']}` |") + if c["envs"]: + lines.append(f"| Environments | {' · '.join(env_line(e) for e in c['envs'])} |") + lines += ["", "## Depends on", "", *bullet_list(c["deps"], by_name), + "", "## Depended on by", "", *bullet_list(dependents, by_name), ""] + return "\n".join(lines) + + +def architecture(c: dict, by_name: dict) -> str: + lines = [f"# {c['name']} — architecture", ""] + t = c["type"] + + if t == "terraform": + f = tf_facts(c) + lines += [f"A `terraform` root at `{f['dir'] or c['path']}`.", ""] + if f["backend"] == "http": + lines += ["- **State** lives in the Orun Cloud HTTP state backend — no local state and", + " no state bucket to manage."] + lines += ["- **Credentials are brokered per run** from the workspace's provider", + " connections and resolved by name; none is stored in this repository."] + if f["adopt"]: + lines += ["- **Adoption** (`adopt.tf`): when state is empty but the resource already", + " exists, plan-time import adopts it instead of failing."] + lines.append("") + if f["resources"]: + lines += ["## Resources", "", *[f"- `{r}`" for r in f["resources"]], ""] + pub = published(c) + if pub: + lines += ["## Published outputs", "", + "Written as job-output secrets on each environment after an apply; deploy", + "lanes downstream resolve them by name.", "", + "| Secret | Terraform output |", "|---|---|", + *[f"| `{k}` | `{v}` |" for k, v in pub], ""] + elif f["outputs"]: + lines += ["## Outputs", "", *[f"- `{o}`" for o in f["outputs"]], ""] + if c["secret_env"]: + lines += ["## Resolved at run time (names only)", "", + *[f"- `{k}`" for k in c["secret_env"]], ""] + return "\n".join(lines) + + if t == "db-migrate": + migs = migrations(c) + lines += [f"Applies the migrations under `{c['migrations_path']}` in order, recording each one", + "it applies so a run only ever applies what is new. An already-applied migration", + "is never edited: a change is a new, later migration.", ""] + if migs: + lines += ["## Migrations", "", *[f"- `{m}`" for m in migs], ""] + if c["secret_env"]: + lines += ["## Resolved at run time (names only)", "", + *[f"- `{k}`" for k in c["secret_env"]], ""] + return "\n".join(lines) + + pkg = package_of(c) + if t.startswith("cloudflare-"): + cfg_name, cfg = worker_config(c) + lines += [f"Built by the turbo pipeline from `{c['path']}` and deployed with wrangler.", ""] + if cfg: + lines += ["| | |", "|---|---|", f"| Worker config | `{c['path']}/{cfg_name}` |"] + if cfg.get("main"): + lines.append(f"| Entry | `{cfg['main']}` |") + if cfg.get("compatibility_date"): + lines.append(f"| Compatibility date | `{cfg['compatibility_date']}` |") + if cfg.get("compatibility_flags"): + lines.append(f"| Compatibility flags | {', '.join(f'`{x}`' for x in cfg['compatibility_flags'])} |") + lines.append("") + rows = bindings(cfg) + lines += ["## Bindings", ""] + if rows: + lines += ["| Binding | Kind | Source |", "|---|---|---|", + *[f"| `{b}` | {k} | {s} |" for b, k, s in rows], ""] + if any("from `" in s for _, _, s in rows): + lines += ["Identifiers marked *from* a component are filled in at deploy time from", + "that component's published outputs for the environment being deployed.", ""] + else: + lines += ["None: the Worker binds no storage or service.", ""] + crons = (cfg.get("triggers") or {}).get("crons") or [] + if crons: + lines += ["## Scheduled triggers", "", *[f"- `{x}`" for x in crons], ""] + env_names = sorted((cfg.get("env") or {}).keys()) + var_names = sorted((cfg.get("vars") or {}).keys()) + if var_names: + lines += ["## Variables", "", ", ".join(f"`{v}`" for v in var_names) + + (f" — overridden per environment ({', '.join(f'`{e}`' for e in env_names)})." + if env_names else "."), ""] + wiring = [k for k in c["secret_env"] if k.startswith("WIRING_")] + others = [k for k in c["secret_env"] if not k.startswith("WIRING_")] + if wiring: + lines += ["## Wiring", "", + "Resolved at deploy time from secrets the infrastructure lanes publish (names only):", + "", *[f"- `{k}`" for k in wiring], ""] + if others: + lines += ["## Secrets resolved by the lane (names only)", "", *[f"- `{k}`" for k in others], ""] + return "\n".join(lines) + + # turbo-package + if is_tests(c): + files = test_files(c) + lines += [f"A test package at `{c['path']}`. Its lane runs the suite before it builds.", ""] + if files: + lines += [f"## Suites ({len(files)})", "", *[f"- `{f}`" for f in files], ""] + return "\n".join(lines) + lines += [f"A workspace package at `{c['path']}`, consumed at build time by the components", + "that depend on it. It holds no credentials and opens no connections of its own.", ""] + if pkg and pkg.get("exports"): + ex = pkg["exports"] + keys = sorted(ex.keys()) if isinstance(ex, dict) else ["."] + lines += ["## Exports", "", *[f"- `{k}`" for k in keys], ""] + return "\n".join(lines) + + +def runbook(c: dict, by_name: dict) -> str: + t = c["type"] + pkg = package_of(c) + lines = [f"# {c['name']} — runbook", "", "## How it runs", ""] + deploys = [e["name"] for e in c["envs"] + if any(ref == "github-push-main" for _, ref in e["rules"])] + if deploys and t in ("terraform", "db-migrate"): + lines += [f"Pull requests plan it; a merge to `main` applies it to " + f"{', '.join(f'`{e}`' for e in deploys)}."] + elif deploys: + lines += [f"Pull requests verify it; a merge to `main` deploys it to " + f"{', '.join(f'`{e}`' for e in deploys)}."] + else: + lines += ["Its lane runs on every pull request that changes it; it has no deployed surface."] + lines += ["CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`;", + "the plan orders a component after everything it depends on.", ""] + + if pkg and pkg.get("scripts"): + name = pkg.get("name") + wanted = [s for s in ("dev", "build", "test", "typecheck", "lint", "preview") if s in pkg["scripts"]] + if name and wanted: + lines += ["## Local commands", "", "```bash", + *[f"pnpm --filter {name} {s}" for s in wanted], "```", ""] + + smoke = c["params"].get("smokeCommand") + if smoke and "No smoke" not in str(smoke): + lines += ["## Verify", "", "After a deploy the lane runs this smoke against the environment it", + "deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL:", "", + "```bash", str(smoke).strip(), "```", ""] + + lines += ["## Rollback", "", + "Revert the commit on `main`. The next convergence applies the previous desired", + "state; nothing was changed out of band, so there is nothing else to undo.", "", + "## Common failures", ""] + if t == "terraform": + lines += ["- **Provider authentication fails**: the workspace's provider connection is", + " missing or revoked. Reconnect it in the console; credentials are brokered", + " from it per run.", + "- **\"Already exists\" on a first apply**: state is empty but the resource is", + " not." + (" `adopt.tf` imports it at plan time; if it still fails, the resource" + " was renamed outside Terraform." if tf_facts(c)["adopt"] else + " Import it, or delete the stray resource, then re-run."), ""] + elif t == "db-migrate": + lines += ["- **An applied migration's file changed**: the run stops rather than guess.", + " Restore the file and write the change as a new migration.", + "- **The database is unreachable**: the infrastructure lane it depends on has", + " not applied for this environment; that lane runs first in a convergence.", ""] + elif t.startswith("cloudflare-"): + lines += ["- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream", + " has not applied for this environment yet. Within one convergence the plan", + " runs it first; on its own, re-run that lane.", + "- **The smoke fails right after a first deploy**: a new workers.dev route can", + " answer 4xx for a few seconds and the lane retries. A failure that persists", + " is a regression in the deployed code.", ""] + else: + lines += ["- **A dependent fails to build after a change here**: run `pnpm typecheck`", + " across the workspace before merging.", ""] + return "\n".join(lines) + + +# ── main ───────────────────────────────────────────────────────────────── + +def main() -> int: + check = "--check" in sys.argv[1:] + comps = discover() + if not comps: + print("no component.yaml found", file=sys.stderr) + return 1 + by_name = {c["name"]: c for c in comps} + dependents: dict[str, list[str]] = {c["name"]: [] for c in comps} + for c in comps: + for d in c["deps"]: + dependents.setdefault(d, []).append(c["name"]) + + drifted, written, leaks = [], 0, [] + for c in comps: + pages = { + "overview.md": overview(c, by_name, sorted(dependents.get(c["name"], []))), + "architecture.md": architecture(c, by_name), + "runbook.md": runbook(c, by_name), + } + for fname, body in pages.items(): + target = c["dir"] / "docs" / fname + for n, line in enumerate(body.splitlines(), 1): + m = FACTORY.search(line) + if m: + leaks.append(f"{rel(target)}:{n} would name {m.group(0)!r}") + current = target.read_text(encoding="utf-8") if target.exists() else None + if current == body: + continue + if check: + drifted.append(rel(target)) + continue + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(body, encoding="utf-8") + written += 1 + + if leaks: + print("✗ a generated page would name a path products do not have:", file=sys.stderr) + for l in leaks: + print(f" {l}", file=sys.stderr) + return 1 + if check: + if drifted: + print(f"✗ {len(drifted)} component doc(s) differ from what the manifests say:", file=sys.stderr) + for f in drifted: + print(f" {f}", file=sys.stderr) + print("\nRun: python3 tooling/catalog/gen-component-docs.py", file=sys.stderr) + return 1 + print(f"✓ component docs match {len(comps)} component.yaml file(s)") + return 0 + print(f"✓ wrote {written} page(s) for {len(comps)} component(s)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tooling/rebrand/rebrand.mjs b/tooling/rebrand/rebrand.mjs index 3eea52d..01b8d24 100644 --- a/tooling/rebrand/rebrand.mjs +++ b/tooling/rebrand/rebrand.mjs @@ -180,7 +180,6 @@ const EXCLUDE_RE = new RegExp( // 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("|"), ); From 549e1da7941bb715ebc7ddb52e048bcaf28b7d2f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 18 Oct 2026 14:27:46 +0000 Subject: [PATCH 2/3] Regenerate component docs: prettier-padded tables, accurate wording The generator now lays tables out the way prettier does (an app whose lint is `prettier --check` accepts the pages as written), lists the WIRING_* failure only for Workers that take wiring, and no longer claims a package holds no credentials. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D8AmgTwmnp4M8mgmnS9aha --- apps/web/docs/architecture.md | 20 +++---- apps/web/docs/overview.md | 10 ++-- .../cloudflare-kv/docs/architecture.md | 6 +-- .../terraform/cloudflare-kv/docs/overview.md | 8 +-- tests/web/docs/overview.md | 10 ++-- tooling/catalog/gen-component-docs.py | 53 ++++++++++++------- 6 files changed, 61 insertions(+), 46 deletions(-) diff --git a/apps/web/docs/architecture.md b/apps/web/docs/architecture.md index 02c497d..e16229d 100644 --- a/apps/web/docs/architecture.md +++ b/apps/web/docs/architecture.md @@ -2,21 +2,21 @@ Built by the turbo pipeline from `apps/web` and deployed with wrangler. -| | | -|---|---| -| Worker config | `apps/web/wrangler.template.jsonc` | -| Entry | `worker.ts` | -| Compatibility date | `2026-10-01` | +| | | +| ------------------- | ----------------------------------------------- | +| Worker config | `apps/web/wrangler.template.jsonc` | +| Entry | `worker.ts` | +| Compatibility date | `2026-10-01` | | Compatibility flags | `nodejs_compat`, `global_fetch_strictly_public` | ## Bindings -| Binding | Kind | Source | -|---|---|---| -| `KV` | Workers KV namespace | `app_kv_id` from `cloudflare-kv` | -| `ASSETS` | Static assets | `.open-next/assets` | +| Binding | Kind | Source | +| -------- | -------------------- | -------------------------------- | +| `KV` | Workers KV namespace | `app_kv_id` from `cloudflare-kv` | +| `ASSETS` | Static assets | `.open-next/assets` | -Identifiers marked *from* a component are filled in at deploy time from +Identifiers marked _from_ a component are filled in at deploy time from that component's published outputs for the environment being deployed. ## Scheduled triggers diff --git a/apps/web/docs/overview.md b/apps/web/docs/overview.md index 0a74e1c..d9e348d 100644 --- a/apps/web/docs/overview.md +++ b/apps/web/docs/overview.md @@ -4,11 +4,11 @@ The cron example (Next.js on Cloudflare Workers + Static Assets via @opennextjs/ A Cloudflare Worker with Static Assets (server rendering plus static files), deployed per environment by its CI lane. -| | | -|---|---| -| Type | `cloudflare-workers-assets-turbo` | -| Source | `apps/web` | -| Package | `@app/web` | +| | | +| ------------ | ------------------------------------------------------------------------------------------------------------------ | +| Type | `cloudflare-workers-assets-turbo` | +| Source | `apps/web` | +| Package | `@app/web` | | Environments | `dev`: `verify` · `stage`: `verify`, `deploy` on a push to `main` · `prod`: `verify`, `deploy` on a push to `main` | ## Depends on diff --git a/infra/terraform/cloudflare-kv/docs/architecture.md b/infra/terraform/cloudflare-kv/docs/architecture.md index 4ed1148..0726cce 100644 --- a/infra/terraform/cloudflare-kv/docs/architecture.md +++ b/infra/terraform/cloudflare-kv/docs/architecture.md @@ -18,9 +18,9 @@ A `terraform` root at `infra/terraform/cloudflare-kv/terraform`. Written as job-output secrets on each environment after an apply; deploy lanes downstream resolve them by name. -| Secret | Terraform output | -|---|---| -| `WIRING_CLOUDFLARE_KV` | `wiring` | +| Secret | Terraform output | +| ---------------------- | ---------------- | +| `WIRING_CLOUDFLARE_KV` | `wiring` | ## Resolved at run time (names only) diff --git a/infra/terraform/cloudflare-kv/docs/overview.md b/infra/terraform/cloudflare-kv/docs/overview.md index 720158a..e6e6de1 100644 --- a/infra/terraform/cloudflare-kv/docs/overview.md +++ b/infra/terraform/cloudflare-kv/docs/overview.md @@ -4,10 +4,10 @@ Provisions the Cloudflare KV namespace the app binds (stage and prod) Terraform-managed infrastructure, planned and applied per environment by its CI lane. -| | | -|---|---| -| Type | `terraform` | -| Source | `infra/terraform/cloudflare-kv` | +| | | +| ------------ | ---------------------------------------------------------------------------------------------------- | +| Type | `terraform` | +| Source | `infra/terraform/cloudflare-kv` | | Environments | `stage`: `plan-only`, `apply` on a push to `main` · `prod`: `plan-only`, `apply` on a push to `main` | ## Depends on diff --git a/tests/web/docs/overview.md b/tests/web/docs/overview.md index 6e02b2d..3534e6b 100644 --- a/tests/web/docs/overview.md +++ b/tests/web/docs/overview.md @@ -2,11 +2,11 @@ The test suite for **web**. It deploys nothing: its lane installs, builds and runs the tests. -| | | -|---|---| -| Type | `turbo-package` | -| Source | `tests/web` | -| Package | `@app/web-tests` | +| | | +| ------------ | -------------------- | +| Type | `turbo-package` | +| Source | `tests/web` | +| Package | `@app/web-tests` | | Environments | `dev`: `quick-check` | ## Depends on diff --git a/tooling/catalog/gen-component-docs.py b/tooling/catalog/gen-component-docs.py index 2a6a8b8..cda768f 100644 --- a/tooling/catalog/gen-component-docs.py +++ b/tooling/catalog/gen-component-docs.py @@ -232,6 +232,18 @@ def migrations(c: dict) -> list[str]: return sorted(p.name for p in d.iterdir() if p.is_dir() or p.suffix == ".sql") +# ── markdown ───────────────────────────────────────────────────────────── + +def md_table(header: list[str], rows: list[list[str]]) -> list[str]: + """A table laid out the way prettier lays it out, so a repo whose lint is + `prettier --check` accepts the page as written.""" + cols = len(header) + width = [max(3, len(header[i]), *(len(r[i]) for r in rows)) for i in range(cols)] + def line(cells): + return "| " + " | ".join(c.ljust(width[i]) for i, c in enumerate(cells)) + " |" + return [line(header), "| " + " | ".join("-" * w for w in width) + " |", *(line(r) for r in rows)] + + # ── phrasing ───────────────────────────────────────────────────────────── KIND = { @@ -288,11 +300,12 @@ def overview(c: dict, by_name: dict, dependents: list[str]) -> str: lines = [f"# {c['name']}", ""] if c["description"]: lines += [c["description"], ""] - lines += [kind, "", "| | |", "|---|---|", f"| Type | `{c['type']}` |", f"| Source | `{c['path']}` |"] + facts = [["Type", f"`{c['type']}`"], ["Source", f"`{c['path']}`"]] if pkg and pkg.get("name"): - lines.append(f"| Package | `{pkg['name']}` |") + facts.append(["Package", f"`{pkg['name']}`"]) if c["envs"]: - lines.append(f"| Environments | {' · '.join(env_line(e) for e in c['envs'])} |") + facts.append(["Environments", " · ".join(env_line(e) for e in c["envs"])]) + lines += [kind, "", *md_table(["", ""], facts)] lines += ["", "## Depends on", "", *bullet_list(c["deps"], by_name), "", "## Depended on by", "", *bullet_list(dependents, by_name), ""] return "\n".join(lines) @@ -321,8 +334,7 @@ def architecture(c: dict, by_name: dict) -> str: lines += ["## Published outputs", "", "Written as job-output secrets on each environment after an apply; deploy", "lanes downstream resolve them by name.", "", - "| Secret | Terraform output |", "|---|---|", - *[f"| `{k}` | `{v}` |" for k, v in pub], ""] + *md_table(["Secret", "Terraform output"], [[f"`{k}`", f"`{v}`"] for k, v in pub]), ""] elif f["outputs"]: lines += ["## Outputs", "", *[f"- `{o}`" for o in f["outputs"]], ""] if c["secret_env"]: @@ -347,21 +359,20 @@ def architecture(c: dict, by_name: dict) -> str: cfg_name, cfg = worker_config(c) lines += [f"Built by the turbo pipeline from `{c['path']}` and deployed with wrangler.", ""] if cfg: - lines += ["| | |", "|---|---|", f"| Worker config | `{c['path']}/{cfg_name}` |"] + facts = [["Worker config", f"`{c['path']}/{cfg_name}`"]] if cfg.get("main"): - lines.append(f"| Entry | `{cfg['main']}` |") + facts.append(["Entry", f"`{cfg['main']}`"]) if cfg.get("compatibility_date"): - lines.append(f"| Compatibility date | `{cfg['compatibility_date']}` |") + facts.append(["Compatibility date", f"`{cfg['compatibility_date']}`"]) if cfg.get("compatibility_flags"): - lines.append(f"| Compatibility flags | {', '.join(f'`{x}`' for x in cfg['compatibility_flags'])} |") - lines.append("") + facts.append(["Compatibility flags", ", ".join(f"`{x}`" for x in cfg["compatibility_flags"])]) + lines += [*md_table(["", ""], facts), ""] rows = bindings(cfg) lines += ["## Bindings", ""] if rows: - lines += ["| Binding | Kind | Source |", "|---|---|---|", - *[f"| `{b}` | {k} | {s} |" for b, k, s in rows], ""] + lines += [*md_table(["Binding", "Kind", "Source"], [[f"`{b}`", k, s] for b, k, s in rows]), ""] if any("from `" in s for _, _, s in rows): - lines += ["Identifiers marked *from* a component are filled in at deploy time from", + lines += ["Identifiers marked _from_ a component are filled in at deploy time from", "that component's published outputs for the environment being deployed.", ""] else: lines += ["None: the Worker binds no storage or service.", ""] @@ -391,8 +402,8 @@ def architecture(c: dict, by_name: dict) -> str: if files: lines += [f"## Suites ({len(files)})", "", *[f"- `{f}`" for f in files], ""] return "\n".join(lines) - lines += [f"A workspace package at `{c['path']}`, consumed at build time by the components", - "that depend on it. It holds no credentials and opens no connections of its own.", ""] + lines += [f"A workspace package at `{c['path']}`, consumed by the components that depend", + "on it. It has no deployed surface of its own.", ""] if pkg and pkg.get("exports"): ex = pkg["exports"] keys = sorted(ex.keys()) if isinstance(ex, dict) else ["."] @@ -448,10 +459,14 @@ def runbook(c: dict, by_name: dict) -> str: "- **The database is unreachable**: the infrastructure lane it depends on has", " not applied for this environment; that lane runs first in a convergence.", ""] elif t.startswith("cloudflare-"): - lines += ["- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream", - " has not applied for this environment yet. Within one convergence the plan", - " runs it first; on its own, re-run that lane.", - "- **The smoke fails right after a first deploy**: a new workers.dev route can", + _, cfg = worker_config(c) + takes_wiring = any(k.startswith("WIRING_") for k in c["secret_env"]) or \ + bool(cfg and WIRING.search(json.dumps(cfg))) + if takes_wiring: + lines += ["- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream", + " has not applied for this environment yet. Within one convergence the plan", + " runs it first; on its own, re-run that lane."] + lines += ["- **The smoke fails right after a first deploy**: a new workers.dev route can", " answer 4xx for a few seconds and the lane retries. A failure that persists", " is a regression in the deployed code.", ""] else: From da83afe0e8eb55ae2e341249e3b30c1e4476aa36 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 18 Oct 2026 14:34:58 +0000 Subject: [PATCH 3/3] Component docs: list optional and per-environment secrets The generator now reads `optionalSecretEnv` (listed as "(optional)") and secrets declared per environment under `subscribe.environments[]`, so a page no longer leaves out a secret its component declares. Its tables are laid out as prettier lays them out, the WIRING_* failure is listed only for Workers that take wiring, and a package is no longer said to hold no credentials. Every starter now carries the identical generator. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D8AmgTwmnp4M8mgmnS9aha --- tooling/catalog/gen-component-docs.py | 37 ++++++++++++++++++--------- 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/tooling/catalog/gen-component-docs.py b/tooling/catalog/gen-component-docs.py index cda768f..9a39931 100644 --- a/tooling/catalog/gen-component-docs.py +++ b/tooling/catalog/gen-component-docs.py @@ -119,7 +119,13 @@ def read_component(file: pathlib.Path) -> dict: params = spec.get("parameters") or {} deps = [d.get("component") for d in (spec.get("dependsOn") or []) if isinstance(d, dict)] envs = [] + # Secrets may be declared for the whole component or per environment + # (`subscribe.environments[].secretEnv`); a page lists both. + req_env = set((spec.get("secretEnv") or {}).keys()) + opt_env = set((spec.get("optionalSecretEnv") or {}).keys()) for e in ((spec.get("subscribe") or {}).get("environments") or []): + req_env |= set((e.get("secretEnv") or {}).keys()) + opt_env |= set((e.get("optionalSecretEnv") or {}).keys()) rules = [(r.get("profile"), ((r.get("when") or {}).get("triggerRef"))) for r in (e.get("profileRules") or [])] envs.append({"name": e.get("name"), "profile": e.get("profile"), "rules": rules}) @@ -130,7 +136,8 @@ def read_component(file: pathlib.Path) -> dict: "description": (meta.get("description") or "").strip(), "type": spec.get("type"), "deps": [d for d in deps if d], - "secret_env": sorted((spec.get("secretEnv") or {}).keys()), + "secret_env": sorted(req_env), + "optional_env": sorted(opt_env - req_env), "envs": envs, "params": params, "migrations_path": spec.get("path") if spec.get("type") == "db-migrate" else None, @@ -278,6 +285,14 @@ def subject_of(c: dict, by_name: dict) -> str | None: return None +def names_list(c: dict, keep) -> list[str]: + """Secret names a lane resolves, required first; an optional one (from + `optionalSecretEnv`) is resolved when it exists and skipped when not.""" + req = [f"- `{k}`" for k in c["secret_env"] if keep(k)] + opt = [f"- `{k}` (optional)" for k in c["optional_env"] if keep(k)] + return req + opt + + def bullet_list(names: list[str], by_name: dict) -> list[str]: if not names: return ["- (none)"] @@ -337,9 +352,8 @@ def architecture(c: dict, by_name: dict) -> str: *md_table(["Secret", "Terraform output"], [[f"`{k}`", f"`{v}`"] for k, v in pub]), ""] elif f["outputs"]: lines += ["## Outputs", "", *[f"- `{o}`" for o in f["outputs"]], ""] - if c["secret_env"]: - lines += ["## Resolved at run time (names only)", "", - *[f"- `{k}`" for k in c["secret_env"]], ""] + if c["secret_env"] or c["optional_env"]: + lines += ["## Resolved at run time (names only)", "", *names_list(c, lambda k: True), ""] return "\n".join(lines) if t == "db-migrate": @@ -349,9 +363,8 @@ def architecture(c: dict, by_name: dict) -> str: "is never edited: a change is a new, later migration.", ""] if migs: lines += ["## Migrations", "", *[f"- `{m}`" for m in migs], ""] - if c["secret_env"]: - lines += ["## Resolved at run time (names only)", "", - *[f"- `{k}`" for k in c["secret_env"]], ""] + if c["secret_env"] or c["optional_env"]: + lines += ["## Resolved at run time (names only)", "", *names_list(c, lambda k: True), ""] return "\n".join(lines) pkg = package_of(c) @@ -385,14 +398,14 @@ def architecture(c: dict, by_name: dict) -> str: lines += ["## Variables", "", ", ".join(f"`{v}`" for v in var_names) + (f" — overridden per environment ({', '.join(f'`{e}`' for e in env_names)})." if env_names else "."), ""] - wiring = [k for k in c["secret_env"] if k.startswith("WIRING_")] - others = [k for k in c["secret_env"] if not k.startswith("WIRING_")] + wiring = names_list(c, lambda k: k.startswith("WIRING_")) + others = names_list(c, lambda k: not k.startswith("WIRING_")) if wiring: lines += ["## Wiring", "", "Resolved at deploy time from secrets the infrastructure lanes publish (names only):", - "", *[f"- `{k}`" for k in wiring], ""] + "", *wiring, ""] if others: - lines += ["## Secrets resolved by the lane (names only)", "", *[f"- `{k}`" for k in others], ""] + lines += ["## Secrets resolved by the lane (names only)", "", *others, ""] return "\n".join(lines) # turbo-package @@ -460,7 +473,7 @@ def runbook(c: dict, by_name: dict) -> str: " not applied for this environment; that lane runs first in a convergence.", ""] elif t.startswith("cloudflare-"): _, cfg = worker_config(c) - takes_wiring = any(k.startswith("WIRING_") for k in c["secret_env"]) or \ + takes_wiring = any(k.startswith("WIRING_") for k in c["secret_env"] + c["optional_env"]) or \ bool(cfg and WIRING.search(json.dumps(cfg))) if takes_wiring: lines += ["- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream",