diff --git a/.baseline/identity.json b/.baseline/identity.json new file mode 100644 index 0000000..91da2f7 --- /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 (upstream's sidebar text, \"Chatbot\"); `domain` and `subdomain` are placeholders, because this baseline has never deployed under a name of its own; `githubOwner` is the owner in this repository's source link.", + "slug": "ai-chatbot", + "pascal": "AiChatbot", + "productName": "Chatbot", + "domain": "ai-chatbot.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..c2c1336 --- /dev/null +++ b/.baseline/product/README.md @@ -0,0 +1,165 @@ +# ai-chatbot + +Vercel's [Next.js AI Chatbot](https://github.com/vercel/ai-chatbot) — AI SDK +7 streaming chat with tools and artifacts, Auth.js with a guest flow, chat +history in Postgres through Drizzle, image attachments — on **Cloudflare +Workers + Static Assets** through +[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare). Its models +run on **Workers AI** through the Worker's own binding, its Postgres is a +**Supabase** project's database reached through **Cloudflare Hyperdrive**, +and its attachments live in **R2**. Terraform provisions the data plane per +environment and Orun's `db-migrate` applies the schema, all on every merge to +`main`. + +## Live deployment + + +Not recorded yet. The bootstrap's last phase writes the live URLs, the +workspace, which model provider serves and the secrets inventory into +[ai/context/deployment.md](ai/context/deployment.md); how the product deploys +and how to operate it is in +[ai/context/operations.md](ai/context/operations.md). + + +## What is here + +| Surface | Where | +|---|---| +| The product's name | `apps/web/lib/site.ts` | +| The chat, auth, artifacts, tools, components and hooks | `apps/web/app`, `apps/web/components`, `apps/web/artifacts`, `apps/web/lib`, `apps/web/hooks` | +| The models: Workers AI by default, the AI Gateway when its key is set | `apps/web/lib/ai/models.ts`, `apps/web/lib/ai/providers.ts` | +| Postgres through Hyperdrive (`getDb()`), the schema for drizzle-kit | `apps/web/lib/db/queries.ts`, `apps/web/lib/db/schema.ts`, `apps/web/lib/db/migrations` | +| The session key (AUTH_SECRET, or the database's own) | `apps/web/lib/auth-secret.ts`, `apps/web/app/(auth)`, `apps/web/proxy.ts` | +| Attachments on R2 (upload, serve) | `apps/web/app/(chat)/api/files/upload`, `apps/web/app/(chat)/api/files/[...key]` | +| The database check the deploy smoke-tests | `apps/web/app/api/health/route.ts` | +| Workers build and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc`, `component.yaml` | +| The schema as migrations, and their runner | `packages/db` (`@saas/db`), `infra/db-migrate` | +| The Supabase project, the Hyperdrive config, the R2 bucket (stage, prod) | `infra/terraform/supabase`, `infra/terraform/cloudflare-hyperdrive`, `infra/terraform/cloudflare-r2` | +| Tests | `tests/web`, `tests/db` (vitest) | + +## Getting started + +```bash +pnpm install +pnpm run wire:fixture # re-render apps/web/wrangler.jsonc from its template (it is committed) +pnpm typecheck +pnpm lint # the template's own biome/ultracite in apps/web; eslint in the packages +pnpm test # tests/web, tests/db +pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next +``` + +The build needs no database, no Cloudflare account and no model key: +nothing pre-renders against any of them. + +## Running it locally + +1. **Postgres.** Any local Postgres works; the wrangler config points the + `HYPERDRIVE` binding's `localConnectionString` at + `postgres://postgres:postgres@localhost:5432/postgres` (edit + `wrangler.template.jsonc` and re-run `pnpm run wire:fixture` if yours + differs). Apply the schema with drizzle-kit, which reads `POSTGRES_URL` + from `apps/web/.env.local`: + + ```bash + cp apps/web/.env.example apps/web/.env.local # POSTGRES_URL; everything else is optional + pnpm --filter @app/web db:migrate # drizzle-kit migrate over apps/web/lib/db/migrations + ``` + + (In stage and prod the same SQL is applied by `infra/db-migrate` from + `packages/db`; drizzle-kit is local-only.) The migrations generate the + session key in the database, so no `AUTH_SECRET` is needed locally + either. + +2. **Models.** Workers AI has no local mode: `next dev` and `wrangler dev` + reach it through the `AI` binding remotely, on your Cloudflare account — + run `wrangler login` once. Nothing else is needed. + +3. **Run it.** + + ```bash + pnpm --filter @app/web dev # http://localhost:3000 — Next's dev server with the Worker's bindings + pnpm build + pnpm --filter @app/web preview # wrangler dev over the built Worker; optional secrets in apps/web/.dev.vars + ``` + + Opening `/` signs you in as a guest (a row in `User`); `/register` + creates an account. Attachments land in the local R2 emulation and are + served from `/api/files/`. + +## 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`. Per environment the order is +enforced — **the Supabase project, then the Hyperdrive config over its +database, then the migrations, then the Worker, with the R2 bucket applied +beside them** — because each reads what the one before it published: the +project's ref and password, the Hyperdrive id and bucket name the Worker +binds, the schema the app queries. `stage` deploys first and `prod` once +stage has converged on the same commit; `dev` only verifies. Every deploy is +smoke-tested over HTTP: `/ping`, and `/api/health`, which answers only when +the Worker reaches a migrated database. + +The pipeline holds one credential, GitHub's own `GITHUB_TOKEN`. The +Cloudflare tokens and account id and the Supabase access token and org id +are brokered per run from the workspace's connections; the Supabase +project's credentials, the Hyperdrive id and the bucket name are published +by the Terraform applies as orun secrets. Nothing provider-shaped is stored +in the repository or in GitHub. + +Each environment has its own Supabase project: two, which is what +Supabase's free plan allows per organisation. + +## Models + +The chat, the chat titles and the artifact tools run on **Workers AI** +through the Worker's `AI` binding — no key; usage is billed to the +Cloudflare account the Worker runs on, after Workers AI's free daily +allocation. The picker offers Kimi K2.6 (the default: tools, vision, +reasoning) and GLM 4.7 Flash (fast; also the title model); both are listed in +`apps/web/lib/ai/models.ts`. + +To add upstream's **Vercel AI Gateway** models (DeepSeek, Kimi K2.5, GPT OSS, +Grok), set the gateway's key per environment: + +```bash +wrangler secret put AI_GATEWAY_API_KEY --name ai-chatbot-web-stage +wrangler secret put AI_GATEWAY_API_KEY --name ai-chatbot-web-prod +``` + +Worker secrets survive every later deploy; the next request sees them, and +the picker lists the gateway's models from then on. Without the key they are +not offered, and a request naming one is answered by the default Workers AI +model. A model that fails says so in the chat (Workers AI's own message); +the writing-suggestions tool needs structured output, and a model that +cannot give it answers that the suggestions could not be made. + +## Other optional secrets + +- **`AUTH_SECRET`.** The session cookie needs no secret from you: unless you + set an `AUTH_SECRET` Worker secret, its key is one the environment's + database generated for itself when the migrations first ran. Setting + `AUTH_SECRET` (`openssl rand -base64 32`) rotates it — every existing + session ends, and guests get a new guest session. +- **`REDIS_URL`.** Turns on resumable streams and the per-IP rate limit, as + upstream. Without it both are off; the per-user hourly message limit + (`apps/web/lib/ai/entitlements.ts`) always applies. + +```bash +wrangler secret put AUTH_SECRET --name ai-chatbot-web-prod +``` + +## Custom domain + +The app answers on workers.dev from its first deploy. To serve it on your +own domain, attach the domain to the Worker in Cloudflare (Workers & Pages → +`ai-chatbot-web-prod` → Settings → Domains & Routes), then set `SITE_URL` +under that environment's `env:` in `intent.yaml` — the Open Graph images are +absolute links, built from it — and merge: the next deploy uses it. + +## CI + +| Workflow | What it runs | +|---|---| +| `checks.yml` | install, wire fixture (which must change nothing), typecheck, lint, test, build — every pull request (not pushes: on `main`, `ci.yml` must be the only run a commit has) | +| `ci.yml` | the Orun pipeline: `orun plan --changed`, then one job per lane; applies, migrates and deploys stage → prod on merge | diff --git a/.baseline/tasks/01-product.TaskContract.yaml b/.baseline/tasks/01-product.TaskContract.yaml new file mode 100644 index 0000000..ffe6bfb --- /dev/null +++ b/.baseline/tasks/01-product.TaskContract.yaml @@ -0,0 +1,33 @@ +# 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 — every one the bootstrap's convergence plans on stage and +# prod (the two test packages verify on dev, which the bootstrap keeps off +# main until 02-docs, so a marker on them would re-plan nothing): the phase's +# retouch hook reads this list to decide which component.yaml files get the +# redeploy marker, so a re-run after a failed convergence has a diff and +# re-plans exactly these — 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 provisions Supabase, Hyperdrive and R2, migrates the schema and deploys the chatbot on stage and prod + affects: + - supabase + - cloudflare-hyperdrive + - cloudflare-r2 + - db + - db-migrate + - web + doneWhen: + - repo pushed, main pinned as default, workspace linked + - SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD, SUPABASE_DB_URL, WIRING_CLOUDFLARE_HYPERDRIVE and WIRING_CLOUDFLARE_R2 published on stage and prod + - migrations applied and the app deployed and smoke-tested on stage and prod, in the order supabase → cloudflare-hyperdrive → db-migrate → web, with cloudflare-r2 before web + - /ping and /api/health answer 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..bf6e30b --- /dev/null +++ b/.baseline/tasks/02-docs.TaskContract.yaml @@ -0,0 +1,14 @@ +# 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, and the bootstrap's deferrals are put back + affects: + - ai/context/deployment.md + - ai/context/operations.md + - README.md + - intent.yaml + 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..e3ce03f --- /dev/null +++ b/.github/workflows/baseline.yml @@ -0,0 +1,145 @@ +name: Baseline CI + +# THE FACTORY'S OWN LANES — this repository tested as a BASELINE: that its +# build document parses with the orun a bootstrap actually runs, that its card +# agrees with it, that every component is placed by exactly one phase, that +# the Hyperdrive and R2 wiring reaches the Worker's config, that a placed tree +# comes up branded and carrying nothing of the factory, that the product's own +# push-to-main plan deploys infra before app, and that the product installs, +# builds, migrates, deploys (dry), serves, signs a guest in and streams a chat +# answer through its AI binding with no model key and no AUTH_SECRET. +# +# ─── WHY THIS IS NOT IN ci.yml OR checks.yml ────────────────────────────── +# +# `repo-blueprint.yaml`'s `github-workflows` module copies the WHOLE `.github` +# directory into every product built from this repository. These jobs run +# `testing/*.sh`, and `testing/` is deliberately not placed — so in a product +# 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 product'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 — supabase, then + # cloudflare-hyperdrive, then db-migrate, then web, with cloudflare-r2 + # before web, enforced — under the product's lane pin, below, and a + # --resume that changes nothing). + 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-chat \ + --set "productname=Acme Chat" \ + --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 every infra + # edge enforced: it does not apply a dependsOn edge's `modeRules`. The + # lane pin does (advisory on a PR, enforced on main), and the test + # checks the PR's advisory edges only under an orun at least that pin. + # 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: the 01-product landing under the + # checks its pull request waits on; the migrations applied by the product's + # own runner to a local Postgres (through a stand-in for the one Supabase + # Management API endpoint it calls); the stage lane's own structure check, + # build, output check and dry deploy in the job tree orun stages; and the + # built Worker served over that database and a local R2 with no model key + # and no AUTH_SECRET — its smoke, every route, a guest sign-in, a chat + # streamed through the AI binding (a deterministic stand-in: Workers AI + # cannot be called offline), the history, an attachment, a registration. + # Pinned at the product's lane version, because that is the orun its CI + # runs. The runner image carries PostgreSQL 16 (not started); the test + # starts its own on a random port. + product: + 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, migrates, deploys (dry), serves and chats + 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..a5569d0 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -1,14 +1,22 @@ 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. +# Credential-free verification: install, render the offline wrangler fixture +# (which must change nothing: the render is committed), typecheck, lint, test +# and build, on every pull request, linked or not. No database, no model and +# no Cloudflare account: nothing here connects to any of them. `ci.yml` is the +# Orun pipeline beside it (plan/run with brokered Cloudflare and Supabase +# 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 a 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 watch can read this run +# green while ci.yml's deploy lanes failed, and call the product converged. +# On main the convergence builds and tests everything anyway. on: - push: - branches: [main] pull_request: + workflow_dispatch: concurrency: group: checks-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} @@ -33,6 +41,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..4a6148d 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 product + # bootstrapped from it never carries the placeholder — the bootstrap + # writes the product's own workspace into intent.yaml — and one 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 product 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 @@ -173,8 +195,8 @@ jobs: $retry_flag 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 + # ephemeral. Every provider credential (the three Cloudflare tokens and + # the account id, the Supabase access token and the org id) 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 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 04e6e89..7b34d40 100644 --- a/.gitignore +++ b/.gitignore @@ -28,7 +28,3 @@ crash.log # orun per-job staged workspaces and object-model caches. **/.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 diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md new file mode 100644 index 0000000..6b92eed --- /dev/null +++ b/BOOTSTRAP.md @@ -0,0 +1,245 @@ +# BOOTSTRAP — a new chatbot product from this baseline, in one landing + +How to go from **nothing** to **a chatbot live on stage and prod — its own +Supabase project per environment, Hyperdrive in front of it, an R2 bucket for +attachments, the schema applied, the app deployed and chatting on Workers AI +— documented**, with two provider consents and no model key. + +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 twenty minutes** — an estimate summed from the +phases until a bootstrap measures it: one landing, then one convergence per +environment (stage and prod side by side until `02-docs` restores the +promotion gate) that creates the Supabase project (five to seven minutes), +the Hyperdrive config and the R2 bucket, applies the migrations and builds +and deploys the app, infra before app. + +## 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 wait on the PR's whole CI run, `githubOwner` on the doctor + probe, `environments` on the secrets probe, `from: workspace`). The + product's own `ci.yml` pins its lanes separately (v2.78.4), and that pin is + what reads the per-edge `mode` rules the convergence order relies on. +- A **Cloudflare** account (the free plan is enough for one Worker with + static assets, Hyperdrive, an R2 bucket and Workers AI's free daily + allocation) and its Account API token with the permission groups the + console's Connect recipe lists — Workers Scripts, Hyperdrive and R2 among + them. Workers AI needs no token: the Worker's `AI` binding runs on the + account it deploys to. +- A **Supabase** organization the platform can create projects in, connected + to the workspace (console → Integrations → Supabase), **with room for two + projects**: the build creates one for stage and one for prod, and + Supabase's free plan allows exactly two active projects per organization. + An organization that already has one or two active projects needs to pause + them, or a paid plan. +- 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. +- **No AI vendor key.** No platform brokers one: the chat runs on Workers AI, + and the Vercel AI Gateway's models are an optional key the owner adds + afterwards (§3). +- **A known platform risk (R2).** The R2 bucket is applied with its own + `r2-data` key, but the Worker's `BLOB` binding is attached by the deploy, + which runs with the `workers-deploy` token (Workers Scripts and KV). + Whether that token may bind R2 is unproven live; if the first deploy fails + on it, the fix is the platform's `workers-deploy` template. + +## 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/ai-chatbot +cd ai-chatbot + +orun new --blueprint repo-blueprint.yaml \ + --out ~/products/acme-chat --run-hooks --resume \ + --set reponame=acme-chat --set productname="Acme Chat" \ + --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 six brokered credentials; then the whole product in one PR — intent, CI, tooling, identity, the Supabase, Hyperdrive and R2 Terraform roots, the migrations, the app and its tests | the convergence green (supabase → cloudflare-hyperdrive → db-migrate → web, and cloudflare-r2 → web, per environment), the five published secrets on stage and prod, `/ping` and `/api/health` answering on both workers.dev URLs | +| `02-docs` | `ai/context/deployment.md` from probed facts (which model provider serves included); prod's promotion gate and dev's push lanes restored | the final probe | + +```bash +orun new --blueprint repo-blueprint.yaml --out ~/products/acme-chat --run-hooks \ + --phase 01-product --values ~/acme-chat.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, the Terraform roots, the +migrations and their runner, the 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 shipped file +names any of it. That promise is a test: `testing/leak.test.sh` derives what +every phase would place and gates the set and every file's text, and +`testing/placement.test.sh` gates the same rules over a placed, branded tree. + +## 2. Headless / container mode + +The blueprint's source is this repository (`sources: [{kind: dir, path: .}]`), +so the container contract is a shallow clone at a pinned tag plus two +tokens: + +```bash +export ORUN_TOKEN=… # orun auth, headless +export GITHUB_TOKEN=… # fine-grained PAT (below) + +git clone --depth 1 --branch https://github.com/sourceplane/ai-chatbot +cd ai-chatbot +orun new --blueprint repo-blueprint.yaml \ + --out /work/acme-chat --run-hooks --resume --progress json \ + --values /work/acme-chat.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 | + +## 3. After the product is live + +- **The models** need nothing: the chat, the titles and the artifact tools + run on Workers AI through the Worker's `AI` binding, billed to the + Cloudflare account. To add the Vercel AI Gateway's models (upstream's + list), set its key per environment: + + ```bash + wrangler secret put AI_GATEWAY_API_KEY --name -web- + ``` + + Without it the picker offers only the Workers AI models. The product's + README, "Models", is the owner's copy of this. +- **The session key** needs nothing: the database generated one per + environment when the migrations first ran. `AUTH_SECRET` as a Worker secret + overrides it (and ends every session). +- **Redis** is optional: `REDIS_URL` as a Worker secret turns on resumable + streams and the IP rate limit. Without it the per-user hourly limit still + applies. +- **Custom domain**: attach it to the Worker in Cloudflare, then set + `SITE_URL` under the environment's `env:` in the product's `intent.yaml` + (its README, "Custom domain"). There is no domain phase: attaching a domain needs zone + permissions the brokered `workers-deploy` token does not carry. +- **Refresh the record**: re-run `--phase 02-docs`; it is idempotent, and it + records which model provider serves. + +## 4. Testing this baseline + +`.github/workflows/baseline.yml` runs three tiers on every pull request, and +each runs locally the same way: + +```bash +for t in manifest phases coverage rebrand retouch bootstrap-defer wire; do bash testing/$t.test.sh; done +bash testing/leak.test.sh # needs orun +bash testing/placement.test.sh # needs orun, node, pnpm: the offline bootstrap and the product's own plans +bash testing/e2e.test.sh # + network for pnpm, psql and a PostgreSQL server install +``` + +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, reconcile, land, watch, secrets, +probe) and the `link` step are stood in for, a landing becoming a commit. + +What no test here can do is the clouds' half: create a Supabase project, +apply the Hyperdrive config and the bucket, mint a token, deploy for real — +or call Workers AI. The Terraform roots are held to `init -backend=false` and +`validate` (a real `plan` reads Supabase's and Cloudflare's APIs and the +platform's state backend); the convergence ORDER is proven on the product's +own `orun plan`; the migrations are applied by the product's own runner to a +local Postgres through a stand-in for the one Supabase Management API +endpoint it calls (`testing/lib/fake-supabase-api.py`); and the built Worker +then serves a guest over that database and wrangler's local R2, its `AI` +binding pointed at a deterministic stand-in (`testing/lib/fake-ai/`) that +streams a canned answer the way Workers AI's binding does. That a real +Workers AI model answers, calls tools and honours structured output is +verified only by a live deployment. + +## 5. 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 add (or 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` parks on the `providers` probe for cloudflare or supabase | that connection is missing. Connect it (console → Integrations); 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 | +| supabase apply: `does not support oauth access` | a supabase provider ≥ 1.6 reads billing endpoints the brokered OAuth token cannot; the root pins `~> 1.5.1` — keep it | +| supabase apply: project limit reached | the Supabase org already has active projects; the free plan allows two, and stage + prod need both. Pause or delete one, or upgrade, then re-run `01-product` | +| hyperdrive apply: Authentication error (10000) | the Hyperdrive token lacks the permission; reconnect Cloudflare with the recipe's permission groups and re-run the phase — the reconcile re-mints only what is missing | +| r2 apply: Authentication error (10000) | the R2 token (`r2-data`) lacks the permission; reconnect Cloudflare with R2 in the recipe and re-run the phase | +| web deploy fails naming R2 or the bucket | the open risk in §0: the `workers-deploy` token could not attach the `BLOB` binding. A platform fix (the template's scopes), not a change to the product | +| the chat answers "Workers AI could not answer with …" | Workers AI refused the request: a model it no longer serves (pick another in `apps/web/lib/ai/models.ts`), or the account's Workers AI allocation spent | +| hyperdrive or db-migrate: `secret resolution failed … SUPABASE_*` | the supabase apply for that environment did not publish; its lane's log says why. Both wait on it, enforced | +| db-migrate: `row-level security would lock the app out of …` | migration 030 refused: `postgres` (Hyperdrive's role) neither owns the tables in `public` nor bypasses RLS. Nothing was enabled; give `postgres` the tables or BYPASSRLS and re-run `01-product` | +| web smoke: `/api/health` 503 | `database: unreachable` — the Hyperdrive config is wrong or the project is paused; `schema: missing` — db-migrate did not run for that environment | +| `build-app` fails: `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) | +| `verify-app-structure` fails: `test -f "wrangler.jsonc"` | the product's `apps/web/wrangler.jsonc` is not committed. It must be — the check runs before the build in a fresh checkout (`pnpm run wire:fixture` renders it) | +| 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 components re-plan; the project and the config are adopted, not recreated | +| 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` runs on pull requests only | +| 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 | diff --git a/README.md b/README.md index 4cff54a..3582419 100644 --- a/README.md +++ b/README.md @@ -5,79 +5,114 @@ SDK 7 streaming chat with tools and artifacts, Auth.js with a guest flow, Drizzle over Postgres, image attachments — running on **Cloudflare Workers + Static Assets** through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with its -Postgres a **Supabase** project reached through **Hyperdrive**, its -attachments in an **R2** bucket, and the project, the Hyperdrive config, the -bucket and the schema all provisioned by Terraform and Orun's db-migrate -through [Orun](https://github.com/sourceplane/orun), the way the -[Lumen baseline](https://github.com/sourceplane/lumen) does it. - -The template's code is the code. What the port changes is where the -Postgres client comes from (the `HYPERDRIVE` binding, one client per call), -where attachments go (the `BLOB` R2 binding, served back at -`/api/files/`), and the Vercel-only modules — Blob, BotID, -`@vercel/functions`, `@vercel/otel`, `@vercel/analytics` — each replaced by -its Cloudflare counterpart or a no-op. The AI Gateway stays. See +models on **Workers AI** through the Worker's own binding, its Postgres a +**Supabase** project reached through **Hyperdrive**, its attachments in an +**R2** bucket, and the project, the Hyperdrive config, the bucket and the +schema all provisioned by Terraform and Orun's `db-migrate` through +[Orun](https://github.com/sourceplane/orun), the way the +[Lumen baseline](https://github.com/sourceplane/lumen) does it — and packaged +as an **Orun baseline**: one command takes a new chatbot from nothing to live +on stage and prod, in its own repository, under its own name, in ONE +landing. + +The template's code is the code. What the port changes is what the Workers +runtime and a fresh, unattended deployment force: the Postgres client comes +from the `HYPERDRIVE` binding, one per call; attachments go to the `BLOB` R2 +binding and are served back at `/api/files/`; the Vercel-only modules — +Blob, BotID, `@vercel/functions`, `@vercel/otel`, `@vercel/analytics` — are +each replaced by their Cloudflare counterpart or a no-op; the models default +to Workers AI (so a fresh product chats with no model key, and the AI +Gateway's models appear only once its key is set); and the session key +defaults to one the database generates for itself (so no secret has to be +set by hand). 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) builds a +product, in one landing. See [`specs/epics/ai-chatbot`](specs/epics/ai-chatbot/README.md) for the design, -the milestones and the as-built status with every departure. +the milestones and the as-built status, including every departure. -## What is here +## Instantiating a product + +```bash +git clone --depth 1 --branch https://github.com/sourceplane/ai-chatbot +cd ai-chatbot +orun new --blueprint repo-blueprint.yaml --out ~/products/acme-chat --run-hooks --resume \ + --set reponame=acme-chat --set productname="Acme Chat" --set productdomain=acme.dev \ + --set githuborg=acme-inc --set subdomain= +``` + +Or, once the platform's registry lists it, from the Orun console (Baselines → +`ai-chatbot` → Build). Two phases: **`01-product`** creates the repository, +mints the six brokered credentials (Cloudflare and Supabase) and lands the +whole product as one pull request, whose convergence on `main` provisions and +deploys it per environment in a fixed order — + +``` +supabase ──▶ cloudflare-hyperdrive ──▶ db-migrate ──▶ web + cloudflare-r2 ──▶ web +``` + +— each edge `mode: enforced` on a push to main and advisory on a pull +request; then **`02-docs`** records the live deployment from probed facts. +**[BOOTSTRAP.md](BOOTSTRAP.md)** is the operator guide; +[docs/phases/](docs/phases/README.md) has a page per phase. + +The new repository receives the **product only** — the app, the Terraform +roots, the migrations, the tests, its CI, its tooling, a README of its own +and its operating contract — renamed throughout to the product's name, +repository, Worker, Supabase project, Hyperdrive config and bucket. None of +this repository's machinery ships. **No AI vendor key is asked for**: the +platform brokers none, and the chat runs on Workers AI; the AI Gateway's key +is the owner's to add afterwards (the product's README, "Models"). The +Supabase organisation the build uses needs room for **two projects**, stage +and prod — the free plan's limit. + +| 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, the product's README and the bootstrap's task contracts | `.baseline/` | +| The rename engine (product-name seam: `apps/web/lib/site.ts`) | `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 context pack | `ai/context/` | +| The baseline's tests: contract, wiring, leak, offline bootstrap and plans, 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 product's name | `apps/web/lib/site.ts` | | The chat, auth, artifacts, tools, components and hooks | `apps/web/app`, `apps/web/components`, `apps/web/artifacts`, `apps/web/lib`, `apps/web/hooks` | +| The models (Workers AI by default; the AI Gateway when its key is set) | `apps/web/lib/ai/models.ts`, `apps/web/lib/ai/providers.ts` | | Postgres through Hyperdrive (`getDb()`), the schema for drizzle-kit | `apps/web/lib/db/queries.ts`, `apps/web/lib/db/schema.ts`, `apps/web/lib/db/migrations` | +| The session key: AUTH_SECRET, or the one the database generated | `apps/web/lib/auth-secret.ts` | | Attachments on R2 (upload, serve) | `apps/web/app/(chat)/api/files/upload`, `apps/web/app/(chat)/api/files/[...key]` | +| The database check the deploy smoke-tests | `apps/web/app/api/health/route.ts` | | The Vercel-only stand-ins | `apps/web/lib/geo.ts`, `apps/web/lib/bot.ts`, `apps/web/instrumentation.ts`, `apps/web/components/cloudflare-web-analytics.tsx` | -| Workers build and deploy contract | `apps/web/next.config.ts`, `apps/web/open-next.config.ts`, `apps/web/wrangler.template.jsonc`, `apps/web/component.yaml` | +| Workers build and deploy contract | `apps/web/next.config.ts`, `apps/web/open-next.config.ts`, `apps/web/wrangler.template.jsonc` → `wrangler.jsonc` (committed), `apps/web/component.yaml` | | The schema as migrations, and their runner | `packages/db` (`@saas/db`), `infra/db-migrate` | | The Supabase project, the Hyperdrive config, the R2 bucket (stage, prod) | `infra/terraform/supabase`, `infra/terraform/cloudflare-hyperdrive`, `infra/terraform/cloudflare-r2` | -| Tests | `tests/web` (vitest: helpers, the shims, the attachment routes), `tests/db` (vitest: the manifest, the offline plan); upstream's Playwright suite stays in `apps/web/tests` behind `test:e2e` and is not run in CI | +| Tests | `tests/web`, `tests/db` (vitest); upstream's Playwright suite stays in `apps/web/tests` behind `test:e2e` and is not run in CI | ## Getting started ```bash pnpm install -pnpm run wire:fixture # render apps/web/wrangler.jsonc from the offline fixture +pnpm run wire:fixture # re-render apps/web/wrangler.jsonc from its template (committed; this changes nothing) pnpm typecheck pnpm lint # the template's own biome/ultracite in apps/web; eslint in the packages pnpm test # tests/web, tests/db pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next ``` -## Local development - -The app needs a Postgres, a model key and an auth secret. - -1. **Postgres.** Any local Postgres works; the wrangler config points the - `HYPERDRIVE` binding's `localConnectionString` at - `postgres://postgres:postgres@localhost:5432/postgres` (edit it if - yours differs). Apply the schema with drizzle-kit, which reads - `POSTGRES_URL` from `apps/web/.env.local`: - - ```bash - cp apps/web/.env.example apps/web/.env.local # set POSTGRES_URL, AUTH_SECRET, AI_GATEWAY_API_KEY - pnpm --filter @app/web db:migrate # drizzle-kit migrate over apps/web/lib/db/migrations - ``` - - (In stage and prod the same SQL is applied by `infra/db-migrate` from - `packages/db`; drizzle-kit is local-only.) - -2. **Model key.** `AI_GATEWAY_API_KEY` from - [Vercel AI Gateway](https://vercel.com/ai-gateway) — the template's - provider, model list and capability lookups all speak the gateway's API. - To route through Cloudflare AI Gateway instead, point the `ai` gateway - provider's `baseURL` at it (`apps/web/lib/ai/providers.ts`). - -3. **Run it.** - - ```bash - pnpm --filter @app/web dev # http://localhost:3000 — Next's dev server with the Worker's bindings (HYPERDRIVE → your Postgres, BLOB → a local R2) - pnpm --filter @app/web preview # wrangler dev over the built Worker; secrets from apps/web/.dev.vars (see .dev.vars.example) - ``` - - Opening `/` signs you in as a guest (a row in `User`); `/register` - creates an account. Attachments land in the local R2 emulation and are - served from `/api/files/`. +The build needs no database, no Cloudflare account and no model key. +Running it locally — a Postgres, `pnpm --filter @app/web db:migrate`, +`next dev` or `wrangler dev` (Workers AI is reached remotely, so +`wrangler login` first) — is in the product's README +(`.baseline/product/README.md`), which is what a product built from here +carries. ## How it maps to Vercel @@ -91,31 +126,17 @@ The app needs a Postgres, a model key and an auth secret. | BotID | Removed; `lib/bot.ts` never flags a request — use Cloudflare Bot Management or Turnstile at the edge | | `@vercel/otel` + `@ai-sdk/otel` | Workers observability (`observability.enabled` in wrangler); `instrumentation.ts` registers nothing | | `@vercel/analytics` | Cloudflare Web Analytics beacon (`NEXT_PUBLIC_CF_BEACON_TOKEN` at build time; unset renders nothing) | -| Vercel AI Gateway (OIDC on Vercel) | The same gateway with `AI_GATEWAY_API_KEY` as a Worker secret | -| Redis resumable streams + IP rate limit (`REDIS_URL`) | Off, as upstream is without `REDIS_URL`; per-user entitlements still apply | -| Project env vars in the dashboard | `AUTH_SECRET`, `AI_GATEWAY_API_KEY` as Worker secrets per environment; the Hyperdrive id and bucket name as bindings rendered from the infra roots' wiring documents | -| Deploy on push | Orun deploys `ai-chatbot-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`), after the three roots and db-migrate | - -## 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 Cloudflare **and Supabase** to that workspace, -and set the `ORUN_CI` repository variable to `true`. A merge to `main` -then applies the Supabase project, the Hyperdrive config and the R2 bucket, -applies the schema with db-migrate, builds the app with that environment's -Hyperdrive id and bucket name rendered into `wrangler.jsonc`, and deploys -the Worker to `stage`, then `prod`. - -Two Worker secrets are yours to set once per environment, before the first -deploy takes traffic: - -```bash -wrangler secret put AUTH_SECRET --name ai-chatbot-web-stage # openssl rand -base64 32 -wrangler secret put AI_GATEWAY_API_KEY --name ai-chatbot-web-stage -``` - -(and again for `ai-chatbot-web-prod`). Without `AUTH_SECRET` every -signed-in request fails at the proxy; without the gateway key the chat -route answers with the gateway's error. +| Vercel AI Gateway (OIDC on Vercel) for every model call | Workers AI through the `AI` binding by default (`workers-ai-provider`); the gateway's models only with `AI_GATEWAY_API_KEY` as a Worker secret | +| `AUTH_SECRET` set by the owner | Optional: unset, the session key is the one the environment's database generated (`app_private.secrets`) | +| Redis resumable streams + IP rate limit (`REDIS_URL`) | Off without `REDIS_URL`, as upstream; per-user entitlements still apply | +| A database created by hand | `infra/terraform/supabase` + `infra/terraform/cloudflare-hyperdrive` + `infra/terraform/cloudflare-r2`, ids and credentials as orun secrets | +| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, provisioned, deployed | + +## CI + +| Workflow | What it runs | Ships to a product | +|---|---|---| +| `checks.yml` | install, wire fixture (which must change nothing), 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, migrates and deploys stage → prod on merge. 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 blueprint read by the pinned orun, the leak gate, the offline bootstrap and the product's own plans; the product built, migrated into a local Postgres, dry-deployed, served, and chatted with through a stand-in AI binding | 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..1465e3d --- /dev/null +++ b/ai/context/deployment.md @@ -0,0 +1,7 @@ +# ai-chatbot — 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, which model provider serves the chat, and the secrets +> inventory by name. Until then, nothing here claims the product 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..268c1c3 --- /dev/null +++ b/ai/context/operations.md @@ -0,0 +1,189 @@ +# ai-chatbot — operating contract (for humans and agents) + +This is the standing guide to how this product is deployed and operated. +Instance facts (live URLs, workspace, which model provider serves, the +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 product +without any other source. + +## What this system is + +Vercel's Next.js AI Chatbot — streaming chat with tools and artifacts on the +AI SDK, Auth.js with guest and registered users, chat history, votes and +documents in Postgres, image attachments — on Cloudflare Workers. Its models +run on Workers AI through the Worker's `AI` binding, its Postgres is a +Supabase project reached through Cloudflare Hyperdrive, and its attachments +live in an R2 bucket, all expressed as an Orun component-native +desired-state repo. Eight components: + +- **`infra/terraform/supabase`** (`supabase`) — one Supabase project per + environment. Its apply publishes `SUPABASE_PROJECT_REF`, + `SUPABASE_DB_PASSWORD` and `SUPABASE_DB_URL` onto the environment's secret + rung. +- **`infra/terraform/cloudflare-hyperdrive`** (`cloudflare-hyperdrive`) — one + Hyperdrive config per environment over that database. Its apply publishes + `WIRING_CLOUDFLARE_HYPERDRIVE` (the config's id and name). +- **`infra/terraform/cloudflare-r2`** (`cloudflare-r2`) — one R2 bucket per + environment for attachments. Its apply publishes `WIRING_CLOUDFLARE_R2` + (the bucket's name). +- **`infra/db-migrate`** (`db-migrate`) — applies `packages/db`'s migrations + to the environment's database through Supabase's Management API. Each + migration is recorded with its checksum in `_migrations.applied`; only the + missing ones apply. +- **`packages/db`** (`db`) — the migrations and their runner. +- **`apps/web`** (`web`) — the app: Next.js built by `@opennextjs/cloudflare` + into one Worker plus Static Assets. It reaches Postgres through its + `HYPERDRIVE` binding, one client per call (`lib/db/queries.ts`), stores + attachments through its `BLOB` binding and runs models through its `AI` + binding (`lib/ai/providers.ts`). +- **`tests/web`**, **`tests/db`** — vitest suites, verified on the `dev` rung. + +Environments: **`stage`** and **`prod`** are deployed, each with its own +Supabase project — two projects, which is what Supabase's free plan allows +per organisation. **`dev` is verify-only by design** — lanes build and test, +nothing deploys. + +## Identity and tenancy + +Every remote operation runs against ONE Orun workspace, declared in +`intent.yaml` under `execution.state.workspace` — committed, enforced, and +what CI uses. Do not remove it; headless credentials depend on it. If it +reads `ws_SET_ME`, the bootstrap had no workspace to write: set the real one +before anything else. + +## How deployment works + +1. Merge (or push) to `main`. +2. CI (`.github/workflows/ci.yml`) runs `orun plan --changed` — only + components whose files changed are planned — then runs each planned lane + with `orun run --remote-state`, authenticated by GitHub OIDC (the + exchange resolves this repository's linked workspace server-side). +3. Per environment, in this order — each edge `mode: enforced` on a push to + main, advisory on a pull request (which deploys nothing): + **`supabase` → `cloudflare-hyperdrive` → `db-migrate` → `web`**, and + **`cloudflare-r2` → `web`**. A job resolves its secrets when it starts, so + each one reads what the apply before it published. The app's deploy + re-renders `apps/web/wrangler.jsonc` from `WIRING_CLOUDFLARE_HYPERDRIVE` + and `WIRING_CLOUDFLARE_R2` before it builds, deploys + `ai-chatbot-web-`, and smoke-tests it: `/ping`, and `/api/health`, + which answers 200 only when the database is reachable through Hyperdrive + and migrated. +4. `prod` deploys after `stage` has converged on the same commit + (`environments.prod.promotion` in intent.yaml). +5. **The convergence run is the deployment.** A green run means every + planned lane applied. Failed lanes are retried with + `gh run rerun --failed`, which resumes the same execution. + +Caveats that matter: + +- A push that touches no component files plans zero lanes — that run is + green and deployed nothing. Never treat "latest run green" as "product + converged"; probe the URLs instead. +- Every page sends a visitor without a session to `/api/auth/guest`, which + creates a guest user and signs it in. Probe `/ping` and `/api/health`, + which answer without a session; `/` answers with a redirect. +- `apps/web/wrangler.jsonc` is committed as the render of + `wrangler.template.jsonc` from `wiring.fixture.json` (a placeholder + Hyperdrive id and bucket name): edit the template and run + `pnpm run wire:fixture`. The deploy lanes render the real one in their own + job tree; never commit a real id. +- The R2 bucket is applied with the `r2-data` token, but the Worker's + `BLOB` binding is attached by the deploy, which runs with the + `workers-deploy` token (Workers Scripts and KV). Whether that token may + attach an R2 binding is not yet proven live; a deploy that fails on it is + a platform fix, not a change to this repository. +- Every table in `public` has row-level security and no policy. Supabase's + Data API serves `public` to the anon key, so this is what keeps the users + (password hashes included), chats and messages out of it; the app is + unaffected because it connects as `postgres`, the tables' owner. Give a new + table `.enableRLS()`; never `FORCE` it, and never add a policy for `anon` + without meaning to publish that table. +- A migration is immutable once applied: its checksum is in + `packages/db/src/manifest.ts` and in the database's ledger. Change the + schema with a NEW migration (in `packages/db/src/migrations`, and its + drizzle-kit twin in `apps/web/lib/db/migrations` for local databases). + +## Models + +- **Workers AI is the default** for the chat, the titles and the artifact + tools: `@cf/moonshotai/kimi-k2.6` (tools, vision, reasoning) and + `@cf/zai-org/glm-4.7-flash` (fast; also the title model), in + `apps/web/lib/ai/models.ts`. They run on the Cloudflare account the Worker + deploys to, through its `AI` binding — no key, billed to that account + (Workers AI's free daily allocation first). +- **The Vercel AI Gateway is optional.** With `AI_GATEWAY_API_KEY` set as a + Worker secret, the picker also offers upstream's gateway models (DeepSeek, + Kimi K2.5, GPT OSS, Grok). Without it they are not offered, and a request + naming one is answered by the default Workers AI model instead. +- A model's failure is shown in the chat as Workers AI's own message, never + as a 500. A tool a model cannot serve (the writing-suggestions tool needs + structured output) answers the model with what went wrong, and the chat + goes on. +- Redis is optional too: without `REDIS_URL` there are no resumable streams + and no IP rate limit; the per-user hourly message limit + (`lib/ai/entitlements.ts`) always applies. + +## Secrets model + +- **Brokered provider secrets**, minted per run from the workspace's + connections — no long-lived values at rest, nothing to rotate by hand: + `CLOUDFLARE_API_TOKEN` (Workers deploy), `CLOUDFLARE_HYPERDRIVE_TOKEN` + (Hyperdrive) and `CLOUDFLARE_R2_TOKEN` (R2) — the deploy token + deliberately cannot touch either — `CLOUDFLARE_ACCOUNT_ID`, + `SUPABASE_ACCESS_TOKEN` (project create and migrations) and + `SUPABASE_ORG_ID`. +- **Published by the applies** onto the stage and prod rungs: + `SUPABASE_PROJECT_REF`, `SUPABASE_DB_PASSWORD`, `SUPABASE_DB_URL`, + `WIRING_CLOUDFLARE_HYPERDRIVE`, `WIRING_CLOUDFLARE_R2`. +- **Optional Worker secrets the owner adds**, because no platform brokers + them: `AI_GATEWAY_API_KEY` (the gateway's models), `REDIS_URL` (resumable + streams, the IP rate limit). +- **The session key.** `AUTH_SECRET`, when set as a Worker secret, signs and + encrypts the session cookie. Unset, the key is the one the environment's + database generated for itself (`app_private.secrets`, migration + `020_app_secrets`; `apps/web/lib/auth-secret.ts`) — so a fresh deployment + signs guests and new users in without any secret set by hand. The proxy + reads the same key over the same Hyperdrive binding. Setting `AUTH_SECRET` + rotates it: every existing session ends. +- 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. + +## Verifying the system + +```bash +# the Worker and its database path on each environment (also recorded, probed, in deployment.md) +curl -s https://ai-chatbot-web-stage.your-workers-subdomain.workers.dev/ping +curl -s https://ai-chatbot-web-prod.your-workers-subdomain.workers.dev/api/health + +# workspace readiness (integrations + repository link) +orun integrations list --org --json && orun cloud check --org +``` + +## Common operations + +| task | how | +|---|---| +| deploy a change | merge to `main`; watch the run; failed lanes → `gh run rerun --failed` | +| change the schema | add the table to `apps/web/lib/db/schema.ts` with `.enableRLS()`, `pnpm --filter @app/web db:generate`, copy the SQL into a new `packages/db/src/migrations/_/up.sql` and the manifest (`pnpm --filter @saas/db run manifest:fix` for its checksum), merge — db-migrate applies it before the app deploys. `pnpm test` fails on a table in `public` without row-level security | +| add or change a model | `apps/web/lib/ai/models.ts`: a Workers AI model in `workersAiModels` with its capabilities, a gateway model in `gatewayModels` | +| turn the AI Gateway on | `wrangler secret put AI_GATEWAY_API_KEY --name ai-chatbot-web-` | +| redeploy without a change | edit the last line of the component's `component.yaml` (`# orun: redeploy `) and merge — it is a deploy trigger, nothing reads it | +| rotate the session key | `wrangler secret put AUTH_SECRET --name ai-chatbot-web-` (32+ random bytes); every session ends | +| serve a custom domain | attach it to the Worker in Cloudflare (Workers & Pages → the Worker → Settings → Domains & Routes), then set `SITE_URL` under the environment's `env:` in `intent.yaml` (the Open Graph images' origin) and merge | +| headless credentials | `ORUN_TOKEN` (workspace-scoped) + `GITHUB_TOKEN` | + +The deployment record is the bootstrap's `02-docs` phase. Re-running it (the +Orun console's Retry on that phase, or `orun new … --phase 02-docs`) +re-probes the URLs and re-renders [deployment.md](deployment.md); it is +idempotent. + +## Evolution + +Structural changes (a second Worker, a queue, another data store) follow the +same contract that deployed the product: add a component under `apps/`, +`infra/` or `packages/` with a `component.yaml` — declaring `dependsOn` on +any infrastructure whose published secrets it reads, enforced on main — land +it as a pull request, and the convergence run applies it. diff --git a/apps/web/.dev.vars.example b/apps/web/.dev.vars.example index ec25c2e..d860cf6 100644 --- a/apps/web/.dev.vars.example +++ b/apps/web/.dev.vars.example @@ -1,12 +1,23 @@ # Local Worker secrets for `wrangler dev` / `opennextjs-cloudflare preview`. -# Copy to .dev.vars (git-ignored); never commit a value. +# Copy to .dev.vars (git-ignored); never commit a value. EVERY KEY IS +# OPTIONAL: the Worker runs with this file absent. # -# In stage/prod these are Worker secrets, not wrangler vars: set once per -# environment with `wrangler secret put --name ai-chatbot-web-` -# (README → Deploying); the deploy lane does not set them. The database is -# not here: the Worker reaches it through the HYPERDRIVE binding -# (wrangler.jsonc), and attachments go to the BLOB bucket binding. -AUTH_SECRET=change-me-openssl-rand-base64-32 -AI_GATEWAY_API_KEY= +# In stage/prod these are Worker secrets, not wrangler vars: set one with +# `wrangler secret put --name ai-chatbot-web-` (README); the +# deploy lane does not set them. The database is not here: the Worker reaches +# it through the HYPERDRIVE binding (wrangler.jsonc); attachments go to the +# BLOB bucket binding, and the models to the AI binding (Workers AI — remote +# even under `wrangler dev`, so `wrangler login` first). + +# The session key. Unset, it is the one the database generated +# (migration 020_app_secrets; lib/auth-secret.ts). +# AUTH_SECRET= + +# The Vercel AI Gateway: adds upstream's gateway models to the picker. +# AI_GATEWAY_API_KEY= + +# Redis: resumable streams and the per-IP rate limit. +# REDIS_URL= + # Optional. Cloudflare Web Analytics token; build-time (NEXT_PUBLIC_) so it # belongs in .env.local for `next build`, not here. diff --git a/apps/web/.env.example b/apps/web/.env.example index fc1f4da..66530a5 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -1,13 +1,5 @@ -# Local development with Next's dev server (`pnpm --filter @app/web dev`). -# Copy to .env.local (git-ignored); never commit a value. - -# generate a random secret: `openssl rand -base64 32` -AUTH_SECRET=**** - -# Vercel AI Gateway key (https://vercel.com/ai-gateway). The template's model -# calls go through the gateway from the Worker exactly as they did from a -# Vercel function; on Workers there is no OIDC, so the key is required. -AI_GATEWAY_API_KEY=**** +# Local development with Next's dev server (`pnpm --filter @app/web dev`) and +# drizzle-kit. Copy to .env.local (git-ignored); never commit a value. # Postgres for drizzle-kit (`pnpm --filter @app/web db:migrate`, db:studio, # db:push) and for `next dev` only when no Cloudflare context is available. @@ -15,10 +7,20 @@ AI_GATEWAY_API_KEY=**** # from wrangler.jsonc instead (its localConnectionString, same database). POSTGRES_URL=postgres://postgres:postgres@localhost:5432/postgres +# Optional. The session key; unset, the one the migrations generated in the +# database (`openssl rand -base64 32` to set your own). +AUTH_SECRET= + +# Optional. The models are Workers AI through the AI binding (remote under +# `next dev`: `wrangler login` first). A Vercel AI Gateway key +# (https://vercel.com/ai-gateway) adds upstream's gateway models. +AI_GATEWAY_API_KEY= + # Optional. Cloudflare Web Analytics beacon token (stands in for Vercel # Analytics). Unset → no script is rendered. NEXT_PUBLIC_CF_BEACON_TOKEN= -# Not used on Workers: attachments go to the BLOB R2 binding -# (BLOB_READ_WRITE_TOKEN is gone) and resumable streams / the Redis IP rate -# limit stay off without REDIS_URL, as upstream intends. +# Optional. Redis for resumable streams and the per-IP rate limit; unset, +# both stay off, as upstream intends. Attachments go to the BLOB R2 binding +# (BLOB_READ_WRITE_TOKEN is gone). +REDIS_URL= diff --git a/apps/web/.gitignore b/apps/web/.gitignore index 27c8c53..2cc593c 100644 --- a/apps/web/.gitignore +++ b/apps/web/.gitignore @@ -26,6 +26,6 @@ yarn-error.log* next-env.d.ts tsconfig.tsbuildinfo -# Workers build output and local wrangler state (the rendered wrangler.jsonc and .dev.vars are ignored from the repo root) +# Workers build output and local wrangler state (.dev.vars is ignored from the repo root; wrangler.jsonc is committed) .open-next/ .wrangler/ diff --git a/apps/web/README.md b/apps/web/README.md index b407018..80b0166 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -1,71 +1,36 @@ - - Chatbot -

Chatbot

-
- -

- Chatbot (formerly AI Chatbot) is a free, open-source template built with Next.js and the AI SDK that helps you quickly build powerful chatbot applications. -

- -

- Read Docs · - Features · - Model Providers · - Deploy Your Own · - Running locally -

-
- -## Features - -- [Next.js](https://nextjs.org) App Router - - Advanced routing for seamless navigation and performance - - React Server Components (RSCs) and Server Actions for server-side rendering and increased performance -- [AI SDK](https://ai-sdk.dev/docs/introduction) - - Unified API for generating text, structured objects, and tool calls with LLMs - - Hooks for building dynamic chat and generative user interfaces - - Supports OpenAI, Anthropic, Google, xAI, and other model providers via AI Gateway -- [shadcn/ui](https://ui.shadcn.com) - - Styling with [Tailwind CSS](https://tailwindcss.com) - - Component primitives from [Radix UI](https://radix-ui.com) for accessibility and flexibility -- Data Persistence - - [Neon Serverless Postgres](https://vercel.com/marketplace/neon) for saving chat history and user data - - [Vercel Blob](https://vercel.com/storage/blob) for efficient file storage -- [Auth.js](https://authjs.dev) - - Simple and secure authentication - -## Model Providers - -This template uses the [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) to access multiple AI models through a unified interface. Models are configured in `lib/ai/models.ts` with per-model provider routing. Included models: Mistral, Moonshot, DeepSeek, OpenAI, and xAI. - -### AI Gateway Authentication - -**For Vercel deployments**: Authentication is handled automatically via OIDC tokens. - -**For non-Vercel deployments**: You need to provide an AI Gateway API key by setting the `AI_GATEWAY_API_KEY` environment variable in your `.env.local` file. - -With the [AI SDK](https://ai-sdk.dev/docs/introduction), you can also switch to direct LLM providers like [OpenAI](https://openai.com), [Anthropic](https://anthropic.com), [Cohere](https://cohere.com/), and [many more](https://ai-sdk.dev/providers/ai-sdk-providers) with just a few lines of code. - -## Deploy Your Own - -You can deploy your own version of Chatbot to Vercel with one click: - -[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/templates/next.js/chatbot) - -## Running locally - -You will need to use the environment variables [defined in `.env.example`](.env.example) to run Chatbot. It's recommended you use [Vercel Environment Variables](https://vercel.com/docs/projects/environment-variables) for this, but a `.env` file is all that is necessary. - -> Note: You should not commit your `.env` file or it will expose secrets that will allow others to control access to your various AI and authentication provider accounts. - -1. Install Vercel CLI: `npm i -g vercel` -2. Link local instance with Vercel and GitHub accounts (creates `.vercel` directory): `vercel link` -3. Download your environment variables: `vercel env pull` +# apps/web — the app + +A chatbot from Vercel's [Next.js AI Chatbot](https://github.com/vercel/ai-chatbot) +(Apache-2.0, see `LICENSE`), running on Cloudflare Workers + Static Assets: + +- Streaming chat on the [AI SDK](https://ai-sdk.dev) (`app/(chat)/api/chat`), + with the template's tools — the weather, and artifacts (text, code, + spreadsheets) the model creates, edits and suggests changes to +- Models on Workers AI through the Worker's `AI` binding by default + (`lib/ai/models.ts`, `lib/ai/providers.ts`); the Vercel AI Gateway's models + are offered only when `AI_GATEWAY_API_KEY` is set +- Auth.js (next-auth v5) with credentials and a guest flow: every page signs a + visitor without a session in as a guest (`proxy.ts`, `app/(auth)`) +- Chat history, votes, documents and suggestions in Postgres through Drizzle +- Image attachments in the `BLOB` R2 bucket, served back at + `/api/files/` +- `/ping`, answered by the proxy, and `/api/health`, which answers 200 only + when the database is reachable through Hyperdrive and migrated + +The product's name is `lib/site.ts`. The database client is built per call +over the `HYPERDRIVE` binding (`lib/db/queries.ts`); the session key is +`AUTH_SECRET` or the one the database generated (`lib/auth-secret.ts`). +Redis (`REDIS_URL`) is optional: without it there are no resumable streams +and no IP rate limit. ```bash -pnpm install -pnpm db:migrate # Setup database or apply latest database changes -pnpm dev +pnpm dev # next dev on http://localhost:3000 (Workers AI is remote: `wrangler login` first) +pnpm build # next build + opennextjs-cloudflare build → .open-next/ +pnpm preview # wrangler dev over the built Worker +pnpm db:migrate # drizzle-kit, against POSTGRES_URL ``` -Your app template should now be running on [localhost:3000](http://localhost:3000). +How it runs locally, how it deploys — per environment, after the Supabase +project, the Hyperdrive config, the R2 bucket and the migrations, on merge to +`main` — and how to add the AI Gateway's models are the repository's README +and `component.yaml` beside this file. diff --git a/apps/web/app/(auth)/api/auth/guest/route.ts b/apps/web/app/(auth)/api/auth/guest/route.ts index 97ce3d2..ea82ac1 100644 --- a/apps/web/app/(auth)/api/auth/guest/route.ts +++ b/apps/web/app/(auth)/api/auth/guest/route.ts @@ -1,7 +1,8 @@ import { NextResponse } from "next/server"; import { getToken } from "next-auth/jwt"; import { signIn } from "@/app/(auth)/auth"; -import { isDevelopmentEnvironment } from "@/lib/constants"; +import { usesSecureCookies } from "@/lib/auth-cookie"; +import { authSecret } from "@/lib/auth-secret"; export async function GET(request: Request) { const { searchParams } = new URL(request.url); @@ -13,8 +14,8 @@ export async function GET(request: Request) { const token = await getToken({ req: request, - secret: process.env.AUTH_SECRET, - secureCookie: !isDevelopmentEnvironment, + secret: await authSecret(), + secureCookie: usesSecureCookies(request), }); if (token) { diff --git a/apps/web/app/(auth)/auth.ts b/apps/web/app/(auth)/auth.ts index fd3b705..de61d3d 100644 --- a/apps/web/app/(auth)/auth.ts +++ b/apps/web/app/(auth)/auth.ts @@ -2,6 +2,7 @@ import { compare } from "bcrypt-ts"; import NextAuth, { type DefaultSession } from "next-auth"; import type { DefaultJWT } from "next-auth/jwt"; import Credentials from "next-auth/providers/credentials"; +import { authSecret } from "@/lib/auth-secret"; import { DUMMY_PASSWORD } from "@/lib/constants"; import { createGuestUser, getUser } from "@/lib/db/queries"; import { authConfig } from "./auth.config"; @@ -30,12 +31,16 @@ declare module "next-auth/jwt" { } } +// Initialised lazily — Auth.js resolves this config per request — because the +// secret may be one the database holds (lib/auth-secret.ts): AUTH_SECRET when +// it is set, otherwise the key migration 020_app_secrets generated, so a +// fresh deployment signs guests in with no owner-supplied secret. export const { handlers: { GET, POST }, auth, signIn, signOut, -} = NextAuth({ +} = NextAuth(async () => ({ ...authConfig, callbacks: { jwt({ token, user }) { @@ -96,4 +101,5 @@ export const { id: "guest", }), ], -}); + secret: await authSecret(), +})); diff --git a/apps/web/app/(auth)/layout.tsx b/apps/web/app/(auth)/layout.tsx index d14e92c..f9e4099 100644 --- a/apps/web/app/(auth)/layout.tsx +++ b/apps/web/app/(auth)/layout.tsx @@ -1,6 +1,6 @@ import { ArrowLeftIcon } from "lucide-react"; import Link from "next/link"; -import { SparklesIcon, VercelIcon } from "@/components/chat/icons"; +import { SparklesIcon } from "@/components/chat/icons"; import { Preview } from "@/components/chat/preview"; export default function AuthLayout({ @@ -31,8 +31,7 @@ export default function AuthLayout({
Powered by - - AI Gateway + Workers AI
diff --git a/apps/web/app/(chat)/actions.ts b/apps/web/app/(chat)/actions.ts index a461c91..83d39a6 100644 --- a/apps/web/app/(chat)/actions.ts +++ b/apps/web/app/(chat)/actions.ts @@ -4,7 +4,6 @@ import { generateText, type UIMessage } from "ai"; import { cookies } from "next/headers"; import { auth } from "@/app/(auth)/auth"; import type { VisibilityType } from "@/components/chat/visibility-selector"; -import { titleModel } from "@/lib/ai/models"; import { titlePrompt } from "@/lib/ai/prompts"; import { getTitleModel } from "@/lib/ai/providers"; import { @@ -29,8 +28,9 @@ export async function generateTitleFromUserMessage({ instructions: titlePrompt, model: getTitleModel(), prompt: getTextFromMessage(message), + // A title needs no thinking: the Workers AI title model's reasoning off. providerOptions: { - gateway: { order: titleModel.gatewayOrder }, + "workers-ai": { chat_template_kwargs: { enable_thinking: false } }, }, }); return text diff --git a/apps/web/app/(chat)/api/chat/route.ts b/apps/web/app/(chat)/api/chat/route.ts index a05c994..b1a078c 100644 --- a/apps/web/app/(chat)/api/chat/route.ts +++ b/apps/web/app/(chat)/api/chat/route.ts @@ -12,14 +12,13 @@ import { createResumableStreamContext } from "resumable-stream"; import { auth, type UserType } from "@/app/(auth)/auth"; import { entitlementsByUserType } from "@/lib/ai/entitlements"; import { - allowedModelIds, chatModels, - DEFAULT_CHAT_MODEL, getCapabilities, getModelAvailability, + isWorkersAiModel, } from "@/lib/ai/models"; import { type RequestHints, systemPrompt } from "@/lib/ai/prompts"; -import { getLanguageModel } from "@/lib/ai/providers"; +import { getLanguageModel, resolveModelId } from "@/lib/ai/providers"; import { createDocument } from "@/lib/ai/tools/create-document"; import { editDocument } from "@/lib/ai/tools/edit-document"; import { getWeather } from "@/lib/ai/tools/get-weather"; @@ -94,9 +93,9 @@ export async function POST(request: Request) { return new ChatbotError("unauthorized:chat").toResponse(); } - const chatModel = allowedModelIds.has(selectedChatModel) - ? selectedChatModel - : DEFAULT_CHAT_MODEL; + // Only a model this deployment can run: a gateway model without the + // gateway's key falls back to the default Workers AI model. + const chatModel = resolveModelId(selectedChatModel); await checkIpRateLimit(ipAddress(request)); @@ -397,6 +396,12 @@ export async function POST(request: Request) { ) { return "AI Gateway requires a valid credit card on file to service requests. Please visit https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%3Fmodal%3Dadd-credit-card to add a card and unlock your free credits."; } + // Workers AI's own error (a model it no longer serves, a quota, a + // binding that is not there) is shown as it is, in the chat, rather + // than as a bare "Oops". + if (isWorkersAiModel(chatModel) && error instanceof Error) { + return `Workers AI could not answer with ${modelConfig?.name ?? chatModel}: ${error.message.slice(0, 200)}`; + } return "Oops, an error occurred!"; }, originalMessages: isToolApprovalFlow ? uiMessages : undefined, diff --git a/apps/web/app/(chat)/api/models/route.ts b/apps/web/app/(chat)/api/models/route.ts index de1d12a..db7078d 100644 --- a/apps/web/app/(chat)/api/models/route.ts +++ b/apps/web/app/(chat)/api/models/route.ts @@ -1,20 +1,43 @@ -import { getAllGatewayModels, getCapabilities, isDemo } from "@/lib/ai/models"; +import { + getAllGatewayModels, + getAvailableModels, + getCapabilities, + isDemo, + isGatewayConfigured, +} from "@/lib/ai/models"; +// What the model picker shows: `available` is exactly what this deployment +// can run — the Workers AI models always, the AI Gateway's only when its key +// is set — and `capabilities` says what each supports. In the demo mode +// upstream ships (IS_DEMO=1, with a gateway key), `models` adds the +// gateway's whole catalogue, shown locked. export async function GET() { const headers = { - "Cache-Control": "public, max-age=86400, s-maxage=86400", + // Per deployment, and it changes when a key is set: short-lived. + "Cache-Control": "public, max-age=300, s-maxage=300", }; + const available = getAvailableModels(); const curatedCapabilities = await getCapabilities(); - if (isDemo) { + if (isDemo && isGatewayConfigured()) { const models = await getAllGatewayModels(); const capabilities = Object.fromEntries( models.map((m) => [m.id, curatedCapabilities[m.id] ?? m.capabilities]) ); - return Response.json({ capabilities, models }, { headers }); + return Response.json( + { + available, + capabilities: { ...capabilities, ...curatedCapabilities }, + models, + }, + { headers } + ); } - return Response.json(curatedCapabilities, { headers }); + return Response.json( + { available, capabilities: curatedCapabilities }, + { headers } + ); } diff --git a/apps/web/app/api/health/route.ts b/apps/web/app/api/health/route.ts new file mode 100644 index 0000000..e696c48 --- /dev/null +++ b/apps/web/app/api/health/route.ts @@ -0,0 +1,47 @@ +import { sql } from "drizzle-orm"; +import { connection } from "next/server"; +import { DEFAULT_CHAT_MODEL, isGatewayConfigured } from "@/lib/ai/models"; +import { getDb } from "@/lib/db/queries"; + +// Not upstream's: the deploy's smoke check and the bootstrap's probes read +// this. `/ping` proves the Worker deployed; this proves what /ping never +// touches — the HYPERDRIVE binding names a real config, Hyperdrive reaches the +// Supabase database, and db-migrate applied the schema (the template's tables +// and the key the app signs sessions with when no AUTH_SECRET is set). It +// answers without a session (proxy.ts lets it through) and reads no row. +// It also says which model provider serves — the deployment record reads it — +// as names and a yes/no, never a key. +export async function GET() { + // Never prerendered: the answer is the database's, at request time. + await connection(); + try { + const db = await getDb(); + const [row] = await db.execute<{ + users: string | null; + secrets: string | null; + }>( + sql`select to_regclass('public."User"')::text as users, + to_regclass('app_private.secrets')::text as secrets` + ); + const ok = Boolean(row?.users && row?.secrets); + return Response.json( + { + database: "reachable", + models: { + default: DEFAULT_CHAT_MODEL, + gateway: isGatewayConfigured() ? "connected" : "not connected", + provider: "workers-ai", + }, + ok, + schema: ok ? "migrated" : "missing", + }, + { headers: { "cache-control": "no-store" }, status: ok ? 200 : 503 } + ); + } catch (error) { + console.error("health: database check failed", error); + return Response.json( + { database: "unreachable", ok: false }, + { headers: { "cache-control": "no-store" }, status: 503 } + ); + } +} diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index f8d21be..2fa17f7 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -3,14 +3,22 @@ import { Geist, Geist_Mono } from "next/font/google"; import { CloudflareWebAnalytics } from "@/components/cloudflare-web-analytics"; import { ThemeProvider } from "@/components/theme-provider"; import { TooltipProvider } from "@/components/ui/tooltip"; +import { SITE_NAME } from "@/lib/site"; import "./globals.css"; import { SessionProvider } from "next-auth/react"; +// The Open Graph and Twitter images are absolute URLs, which Next resolves +// against `metadataBase`. Upstream's was its own demo (chat.vercel.ai); here +// it is the product's public origin, baked in at build: the environment's +// SITE_URL when one is set (a custom domain), else its workers.dev URL +// (component.yaml's buildCommand). A local build has neither. export const metadata: Metadata = { description: "Next.js chatbot template using the AI SDK.", - metadataBase: new URL("https://chat.vercel.ai"), - title: "Next.js Chatbot Template", + metadataBase: new URL( + process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000" + ), + title: SITE_NAME, }; export const viewport = { diff --git a/apps/web/cloudflare-env.d.ts b/apps/web/cloudflare-env.d.ts index d101e8b..a2f70b5 100644 --- a/apps/web/cloudflare-env.d.ts +++ b/apps/web/cloudflare-env.d.ts @@ -1,7 +1,8 @@ // The bindings wrangler.template.jsonc gives the Worker, as seen through // `getCloudflareContext().env` from @opennextjs/cloudflare (which types `env` // as the global `CloudflareEnv` interface for the app to augment). Typed by -// hand as the slice of the Hyperdrive and R2 APIs this app touches, rather +// hand as the slice of the Hyperdrive, R2 and Workers AI APIs this app +// touches, rather // than through @cloudflare/workers-types: its own `Headers`/`ReadableStream` // declarations clash with the DOM lib a Next app compiles against. // (`wrangler types --env-interface CloudflareEnv` generates the full @@ -36,8 +37,20 @@ type R2BucketBinding = { ) => Promise; }; +// The Workers AI binding as workers-ai-provider calls it +// (lib/ai/providers.ts): `run(model, inputs, options)`, a JSON answer or, +// with `stream: true` in the inputs, a server-sent-event stream. +type AiBinding = { + run: ( + model: string, + inputs: Record, + options?: Record + ) => Promise; +}; + declare global { interface CloudflareEnv { + AI: AiBinding; ASSETS: { fetch: ( input: RequestInfo | URL, diff --git a/apps/web/component.yaml b/apps/web/component.yaml index 6c7d3f3..5ef4aaf 100644 --- a/apps/web/component.yaml +++ b/apps/web/component.yaml @@ -12,18 +12,41 @@ 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 Hyperdrive config and the R2 bucket must exist before this deploys - # (their ids are rendered into the Worker's HYPERDRIVE and BLOB bindings), - # and the schema must be applied before the Worker takes traffic - # (db-migrate, which itself waits on the Supabase project). + # INFRA BEFORE APP, ENFORCED ON MAIN. A merge to main converges the whole + # product in one run: the Supabase project, then the Hyperdrive config over + # its database, then the migrations, then this Worker — with the R2 bucket + # applied beside them. Its deploy reads the Hyperdrive id and the bucket + # name (WIRING_CLOUDFLARE_HYPERDRIVE_, WIRING_CLOUDFLARE_R2_, + # rendered into the HYPERDRIVE and BLOB bindings) and needs the schema + # applied, and a job resolves its secrets when it STARTS — so it waits on + # all three, `mode: enforced`, and what the applies lease-published is + # there. A pull request deploys nothing, so nothing on one waits: every + # edge is advisory there. dependsOn: - component: cloudflare-hyperdrive + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request - component: cloudflare-r2 + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request - component: db-migrate + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + # The wiring documents the cloudflare-hyperdrive and cloudflare-r2 roots + # lease-publish, one per deployed environment; tooling/wire/live.mjs picks + # this job's. No model key and no session secret: the model is the AI + # binding, and the session key is one the database generated unless an + # owner sets AUTH_SECRET as a Worker secret (README). secretEnv: - # The wiring documents the wrangler template is rendered from per - # environment. AUTH_SECRET and AI_GATEWAY_API_KEY are Worker secrets set - # once per environment (README → Deploying); the lane does not set them. WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://ai-chatbot/ai-chatbot/stage/WIRING_CLOUDFLARE_HYPERDRIVE" WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://ai-chatbot/ai-chatbot/prod/WIRING_CLOUDFLARE_HYPERDRIVE" WIRING_CLOUDFLARE_R2_STAGE: "secret://ai-chatbot/ai-chatbot/stage/WIRING_CLOUDFLARE_R2" @@ -68,15 +91,27 @@ spec: workersDevSubdomain: your-workers-subdomain installCommand: pnpm install --frozen-lockfile - # Render this environment's wrangler config from the wiring documents, - # then build (the verify lane already rendered from the fixture through - # `wire:fixture`; a deploy lane re-renders with the real values). - buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-hyperdrive,cloudflare-r2 --env "${ORUN_ENVIRONMENT}" && pnpm exec turbo run build --filter=@app/web + # wrangler.jsonc is COMMITTED — the fixture render, so the composition's + # structure check (`test -f wrangler.jsonc`, before the build, in a fresh + # checkout) passes. Every lane re-renders it here, in its own job tree: + # stage and prod from this environment's wiring documents (and refuse to + # build without them), so the Worker binds the real Hyperdrive config and + # bucket; dev, which no root applies to, from the fixture. + # + # The product's public origin (the Open Graph images are absolute links, + # app/layout.tsx's metadataBase): the environment's SITE_URL when + # intent.yaml sets one (a custom domain), else its workers.dev URL. The + # subdomain is written out rather than read from ${WORKERS_DEV_SUBDOMAIN}: + # the composition exports that to the smoke step only, so the build would + # see it empty. ${ORUN_ENVIRONMENT} the runner sets for every step. + buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-hyperdrive,cloudflare-r2 --env "${ORUN_ENVIRONMENT}" --fixture wiring.fixture.json --fixture-envs dev && NEXT_PUBLIC_SITE_URL="${SITE_URL:-https://ai-chatbot-web-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" pnpm exec turbo run build --filter=@app/web - # Smoke: the proxy's health route answers before auth or the database are - # involved (`/ping` → "pong", proxy.ts), so a booted Worker passes and a - # broken one fails regardless of the model key. - smokeCommand: "curl -sf \"${DEPLOYED_URL}/ping\" | grep -q pong" + # Smoke: the proxy answers `/ping` before auth or the database are + # involved — the Worker booted — and /api/health answers ok: the database + # behind the HYPERDRIVE binding reachable and migrated, the session key + # among it. Each response is buffered before grep so an early match + # cannot SIGPIPE curl. + smokeCommand: "pong=$(curl -sf \"${DEPLOYED_URL}/ping\") && echo \"${pong}\" | grep -qx pong && health=$(curl -sf \"${DEPLOYED_URL}/api/health\") && echo \"${health}\" | grep -q '\"ok\":true'" labels: team: platform layer: delivery diff --git a/apps/web/components/chat/app-sidebar.tsx b/apps/web/components/chat/app-sidebar.tsx index d3cd842..bc1cf90 100644 --- a/apps/web/components/chat/app-sidebar.tsx +++ b/apps/web/components/chat/app-sidebar.tsx @@ -32,6 +32,7 @@ import { SidebarTrigger, useSidebar, } from "@/components/ui/sidebar"; +import { SITE_NAME } from "@/lib/site"; import { AlertDialog, AlertDialogAction, @@ -91,7 +92,7 @@ export function AppSidebar({ user }: { user: User | undefined }) { diff --git a/apps/web/components/chat/chat-header.tsx b/apps/web/components/chat/chat-header.tsx index 398cecb..3e59a0e 100644 --- a/apps/web/components/chat/chat-header.tsx +++ b/apps/web/components/chat/chat-header.tsx @@ -1,11 +1,9 @@ "use client"; import { PanelLeftIcon } from "lucide-react"; -import Link from "next/link"; import { memo } from "react"; import { Button } from "@/components/ui/button"; import { useSidebar } from "@/components/ui/sidebar"; -import { VercelIcon } from "./icons"; import { VisibilitySelector, type VisibilityType } from "./visibility-selector"; function PureChatHeader({ @@ -34,15 +32,6 @@ function PureChatHeader({ - - - - {!isReadonly && ( )} - + {/* Upstream's "Deploy with Vercel" call to action (and its mobile icon + link) is gone: this product deploys to Cloudflare, and its header + is its owner's, not the template's advertisement. */} ); } diff --git a/apps/web/components/chat/multimodal-input.tsx b/apps/web/components/chat/multimodal-input.tsx index 987aefa..07dd28d 100644 --- a/apps/web/components/chat/multimodal-input.tsx +++ b/apps/web/components/chat/multimodal-input.tsx @@ -39,9 +39,9 @@ import { } from "@/components/ai-elements/model-selector"; import { type ChatModel, - chatModels, DEFAULT_CHAT_MODEL, type ModelCapabilities, + workersAiModels, } from "@/lib/ai/models"; import type { Attachment, ChatMessage } from "@/lib/types"; import { cn } from "@/lib/utils"; @@ -696,7 +696,8 @@ function ModelSelectorOption({ selectedModelId: string; setOpen: Dispatch>; }) { - const [logoProvider] = model.id.split("/"); + // A Workers AI id is `@cf//`; the logo is the vendor's. + const logoProvider = model.provider; const maybeWithTooltip = (icon: ReactNode, label: string) => { if (!curated) { return icon; @@ -799,14 +800,18 @@ function PureModelSelectorCompact({ const capabilities: Record | undefined = modelsData?.capabilities ?? modelsData; + // What this deployment can run (app/(chat)/api/models): Workers AI's models + // always, the AI Gateway's only when its key is set. Until the answer + // arrives, the Workers AI models, which every deployment has. + const availableModels: ChatModel[] = modelsData?.available ?? workersAiModels; const dynamicModels: ChatModel[] | undefined = modelsData?.models; - const activeModels = dynamicModels ?? chatModels; + const activeModels = availableModels; const selectedModel = activeModels.find((m: ChatModel) => m.id === selectedModelId) ?? activeModels.find((m: ChatModel) => m.id === DEFAULT_CHAT_MODEL) ?? activeModels[0]; - const [provider] = selectedModel.id.split("/"); + const { provider } = selectedModel; return ( @@ -824,13 +829,13 @@ function PureModelSelectorCompact({ {(() => { - const curatedIds = new Set(chatModels.map((m) => m.id)); + const curatedIds = new Set(availableModels.map((m) => m.id)); const allModels = dynamicModels ? [ - ...chatModels, + ...availableModels, ...dynamicModels.filter((m) => !curatedIds.has(m.id)), ] - : chatModels; + : availableModels; const grouped: Record< string, diff --git a/apps/web/components/chat/preview.tsx b/apps/web/components/chat/preview.tsx index d349821..bb0d70d 100644 --- a/apps/web/components/chat/preview.tsx +++ b/apps/web/components/chat/preview.tsx @@ -3,6 +3,7 @@ import { useRouter } from "next/navigation"; import { useCallback } from "react"; import { suggestions } from "@/lib/constants"; +import { SITE_NAME } from "@/lib/site"; import { SparklesIcon } from "./icons"; function PreviewSuggestionButton({ @@ -48,7 +49,7 @@ export function Preview() {
- Chatbot + {SITE_NAME}
diff --git a/apps/web/lib/ai/models.ts b/apps/web/lib/ai/models.ts index 469608d..65e529c 100644 --- a/apps/web/lib/ai/models.ts +++ b/apps/web/lib/ai/models.ts @@ -1,12 +1,11 @@ -export const DEFAULT_CHAT_MODEL = "moonshotai/kimi-k2.5"; - -export const titleModel = { - description: "Fast model for title generation", - gatewayOrder: ["fireworks", "bedrock"], - id: "moonshotai/kimi-k2.5", - name: "Kimi K2.5", - provider: "moonshotai", -}; +// WHERE THE MODELS COME FROM. Upstream sends every model call through the +// Vercel AI Gateway, which needs a key nobody brokers. Here the default is +// Workers AI, through the Worker's own `AI` binding (wrangler.jsonc): it needs +// no key, so a fresh deployment chats with nothing configured. The gateway's +// models — upstream's list, unchanged — are offered only when +// AI_GATEWAY_API_KEY is set (a Worker secret), and the picker shows exactly +// what is available (`getAvailableModels`), never a model that would fail. +export const DEFAULT_CHAT_MODEL = "@cf/moonshotai/kimi-k2.6"; export type ModelCapabilities = { tools: boolean; @@ -19,17 +18,56 @@ export type ChatModel = { name: string; provider: string; description: string; + // `workers-ai`: the AI binding; `gateway`: the AI Gateway (needs its key). + via?: "workers-ai" | "gateway"; + // Workers AI models' capabilities are known here; the gateway's are looked + // up from the gateway (getCapabilities). + capabilities?: ModelCapabilities; gatewayOrder?: string[]; reasoningEffort?: "none" | "minimal" | "low" | "medium" | "high"; }; -export const chatModels: ChatModel[] = [ +// Current Workers AI text models with tool calling (OpenAI-compatible chat +// completions on the binding), run through `workers-ai-provider`. +export const workersAiModels: ChatModel[] = [ + { + capabilities: { reasoning: true, tools: true, vision: true }, + description: "Moonshot AI's Kimi on Workers AI — tools, vision, reasoning", + id: "@cf/moonshotai/kimi-k2.6", + name: "Kimi K2.6", + provider: "moonshotai", + via: "workers-ai", + }, + { + capabilities: { reasoning: true, tools: true, vision: false }, + description: "Fast GLM on Workers AI — tools, reasoning", + id: "@cf/zai-org/glm-4.7-flash", + name: "GLM 4.7 Flash", + provider: "zai", + via: "workers-ai", + }, +]; + +// Titles: the fast Workers AI model, its thinking turned off +// (app/(chat)/actions.ts). +export const titleModel: ChatModel = { + description: "Fast model for title generation", + id: "@cf/zai-org/glm-4.7-flash", + name: "GLM 4.7 Flash", + provider: "zai", + via: "workers-ai", +}; + +// Upstream's curated gateway models, as upstream lists them. Offered only +// with AI_GATEWAY_API_KEY set. +export const gatewayModels: ChatModel[] = [ { description: "Fast and capable model with tool use", gatewayOrder: ["bedrock", "deepinfra"], id: "deepseek/deepseek-v3.2", name: "DeepSeek V3.2", provider: "deepseek", + via: "gateway", }, { description: "Moonshot AI flagship model", @@ -37,6 +75,7 @@ export const chatModels: ChatModel[] = [ id: "moonshotai/kimi-k2.5", name: "Kimi K2.5", provider: "moonshotai", + via: "gateway", }, { description: "Compact reasoning model", @@ -45,6 +84,7 @@ export const chatModels: ChatModel[] = [ name: "GPT OSS 20B", provider: "openai", reasoningEffort: "low", + via: "gateway", }, { description: "Open-source 120B parameter model", @@ -53,6 +93,7 @@ export const chatModels: ChatModel[] = [ name: "GPT OSS 120B", provider: "openai", reasoningEffort: "low", + via: "gateway", }, { description: "Fast non-reasoning model with tool use", @@ -60,14 +101,42 @@ export const chatModels: ChatModel[] = [ id: "xai/grok-4.1-fast-non-reasoning", name: "Grok 4.1 Fast", provider: "xai", + via: "gateway", }, ]; +// Every model this app knows, in picker order. +export const chatModels: ChatModel[] = [...workersAiModels, ...gatewayModels]; + +// Whether the AI Gateway is configured. OpenNext copies the Worker's +// secrets and vars into process.env per request, so this is read at call +// time, never at module load. +export function isGatewayConfigured(): boolean { + return Boolean(process.env.AI_GATEWAY_API_KEY); +} + +// What a request may use: Workers AI always (the binding is in the committed +// wrangler config), the gateway's models only with its key. +export function getAvailableModels(): ChatModel[] { + return isGatewayConfigured() ? chatModels : workersAiModels; +} + +export function isAvailableModel(modelId: string): boolean { + return getAvailableModels().some((m) => m.id === modelId); +} + +export function isWorkersAiModel(modelId: string): boolean { + return workersAiModels.some((m) => m.id === modelId); +} + export async function getCapabilities(): Promise< Record > { const results = await Promise.all( - chatModels.map(async (model) => { + getAvailableModels().map(async (model) => { + if (model.capabilities) { + return [model.id, model.capabilities]; + } try { const res = await fetch( `https://ai-gateway.vercel.sh/v1/models/${model.id}/endpoints`, @@ -150,11 +219,9 @@ export async function getAllGatewayModels(): Promise< } export function getActiveModels(): ChatModel[] { - return chatModels; + return getAvailableModels(); } -export const allowedModelIds = new Set(chatModels.map((m) => m.id)); - export const modelsByProvider = chatModels.reduce( (acc, model) => { if (!acc[model.provider]) { @@ -202,7 +269,8 @@ export async function getModelAvailability( ): Promise { const model = chatModels.find((item) => item.id === modelId); - if (!model) { + // Workers AI reports no per-model health the way the gateway does. + if (!model || model.via === "workers-ai") { return "unknown"; } diff --git a/apps/web/lib/ai/providers.ts b/apps/web/lib/ai/providers.ts index 9cf5258..627d069 100644 --- a/apps/web/lib/ai/providers.ts +++ b/apps/web/lib/ai/providers.ts @@ -1,6 +1,13 @@ -import { customProvider, gateway } from "ai"; +import { getCloudflareContext } from "@opennextjs/cloudflare"; +import { customProvider, gateway, type LanguageModel } from "ai"; +import { createWorkersAI } from "workers-ai-provider"; import { isTestEnvironment } from "../constants"; -import { titleModel } from "./models"; +import { + DEFAULT_CHAT_MODEL, + isAvailableModel, + isWorkersAiModel, + titleModel, +} from "./models"; export const myProvider = isTestEnvironment ? (() => { @@ -17,17 +24,41 @@ export const myProvider = isTestEnvironment })() : null; -export function getLanguageModel(modelId: string) { +// Workers AI through the Worker's own `AI` binding (wrangler.jsonc). No key: +// the binding is the credential. Read per call — the binding lives on the +// request's Cloudflare context, not at module scope. +function workersAi() { + const { env } = getCloudflareContext(); + if (!env.AI) { + throw new Error( + 'The AI binding is missing: wrangler.jsonc must declare `"ai": { "binding": "AI" }`' + ); + } + return createWorkersAI({ binding: env.AI }); +} + +// A model id the request may not use — a gateway model with no gateway key, +// or one nobody lists — falls back to the default Workers AI model rather +// than failing the chat (lib/ai/models.ts, getAvailableModels). +export function resolveModelId(modelId: string): string { + return isAvailableModel(modelId) ? modelId : DEFAULT_CHAT_MODEL; +} + +export function getLanguageModel(modelId: string): LanguageModel { if (isTestEnvironment && myProvider) { return myProvider.languageModel(modelId); } - return gateway.languageModel(modelId); + const id = resolveModelId(modelId); + if (isWorkersAiModel(id)) { + return workersAi()(id); + } + return gateway.languageModel(id); } -export function getTitleModel() { +export function getTitleModel(): LanguageModel { if (isTestEnvironment && myProvider) { return myProvider.languageModel("title-model"); } - return gateway.languageModel(titleModel.id); + return workersAi()(titleModel.id); } diff --git a/apps/web/lib/ai/tools/request-suggestions.ts b/apps/web/lib/ai/tools/request-suggestions.ts index c2f1df8..9936463 100644 --- a/apps/web/lib/ai/tools/request-suggestions.ts +++ b/apps/web/lib/ai/tools/request-suggestions.ts @@ -39,56 +39,70 @@ export const requestSuggestions = ({ "userId" | "createdAt" | "documentCreatedAt" >[] = []; - const { partialOutputStream } = streamText({ - instructions: - "You are a writing assistant. Given a piece of writing, offer up to 5 suggestions to improve it. Each suggestion must contain full sentences, not just individual words. Describe what changed and why.", - model: getLanguageModel(modelId), - output: Output.array({ - element: z.object({ - description: z - .string() - .describe("The description of the suggestion"), - originalSentence: z.string().describe("The original sentence"), - suggestedSentence: z.string().describe("The suggested sentence"), + // Structured output (a JSON schema the model must follow) is the one + // thing this tool asks of a model beyond text and tool calls, and not + // every model honours it. A model that cannot is told so — the chat + // goes on and says so — rather than failing the whole response. + try { + const { partialOutputStream } = streamText({ + instructions: + "You are a writing assistant. Given a piece of writing, offer up to 5 suggestions to improve it. Each suggestion must contain full sentences, not just individual words. Describe what changed and why.", + model: getLanguageModel(modelId), + output: Output.array({ + element: z.object({ + description: z + .string() + .describe("The description of the suggestion"), + originalSentence: z.string().describe("The original sentence"), + suggestedSentence: z.string().describe("The suggested sentence"), + }), }), - }), - prompt: document.content, - }); - - let processedCount = 0; - for await (const partialOutput of partialOutputStream) { - if (!partialOutput) { - continue; - } + prompt: document.content, + }); - for (let i = processedCount; i < partialOutput.length; i += 1) { - const element = partialOutput[i]; - if ( - !element?.originalSentence || - !element?.suggestedSentence || - !element?.description - ) { + let processedCount = 0; + for await (const partialOutput of partialOutputStream) { + if (!partialOutput) { continue; } - const suggestion = { - description: element.description, - documentId, - id: generateUUID(), - isResolved: false, - originalText: element.originalSentence, - suggestedText: element.suggestedSentence, - }; + for (let i = processedCount; i < partialOutput.length; i += 1) { + const element = partialOutput[i]; + if ( + !element?.originalSentence || + !element?.suggestedSentence || + !element?.description + ) { + continue; + } + + const suggestion = { + description: element.description, + documentId, + id: generateUUID(), + isResolved: false, + originalText: element.originalSentence, + suggestedText: element.suggestedSentence, + }; - dataStream.write({ - data: suggestion as Suggestion, - transient: true, - type: "data-suggestion", - }); + dataStream.write({ + data: suggestion as Suggestion, + transient: true, + type: "data-suggestion", + }); - suggestions.push(suggestion); - processedCount += 1; + suggestions.push(suggestion); + processedCount += 1; + } } + } catch (error) { + return { + error: `Could not generate suggestions with this model: ${ + error instanceof Error + ? error.message.slice(0, 200) + : "unknown error" + }. Try again, or pick another model.`, + }; } if (session.user?.id) { diff --git a/apps/web/lib/auth-cookie.ts b/apps/web/lib/auth-cookie.ts new file mode 100644 index 0000000..7038a80 --- /dev/null +++ b/apps/web/lib/auth-cookie.ts @@ -0,0 +1,22 @@ +// Whether Auth.js's session cookie carries the `__Secure-` prefix for this +// request — which proxy.ts and the guest route must know to decode it. +// +// Auth.js decides it from the URL it serves: https gets the prefix, http does +// not (AUTH_URL when set, otherwise the request's forwarded protocol). Upstream +// decoded with `secureCookie: !isDevelopmentEnvironment` instead, which agrees +// on a deployment (https) and under `next dev` (http) but not for the BUILT +// Worker served over http — `pnpm preview`, `wrangler dev` — where the guest +// sign-in set `authjs.session-token`, the proxy looked for +// `__Secure-authjs.session-token`, and every page sent the visitor back to the +// guest sign-in. Decided the way Auth.js decides it, the two always agree. +export function usesSecureCookies(request: Request): boolean { + const configured = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL; + if (configured) { + return new URL(configured).protocol === "https:"; + } + const forwarded = request.headers.get("x-forwarded-proto"); + if (forwarded) { + return forwarded.split(",")[0]?.trim() === "https"; + } + return new URL(request.url).protocol === "https:"; +} diff --git a/apps/web/lib/auth-secret.ts b/apps/web/lib/auth-secret.ts new file mode 100644 index 0000000..333ee81 --- /dev/null +++ b/apps/web/lib/auth-secret.ts @@ -0,0 +1,50 @@ +import { sql } from "drizzle-orm"; + +// The secret Auth.js signs and encrypts its session cookie with +// (app/(auth)/auth.ts) and that proxy.ts and the guest route decode it with. +// +// Upstream reads AUTH_SECRET, which its owner generates and sets. A deployed +// Worker built from nothing has no owner-set secret yet, and without one every +// request fails at the proxy. So the secret is the first of these that exists: +// +// 1. AUTH_SECRET — a Worker secret in a deployment, .dev.vars or .env.local +// locally. Setting it is how an owner rotates the key: every session +// signed under the previous one ends (guests get a new guest session). +// 2. the secret this environment's database generated for itself. Migration +// 020_app_secrets writes 64 random hex characters into +// app_private.secrets the first time it runs, so it is never in a +// repository, a CI log or a deploy artifact, and stage and prod each have +// their own. `app_private` is not a schema Supabase's Data API exposes. +// +// The stored secret is read once per isolate and kept as a plain string: it +// does not change under a running Worker, and a string (unlike a pending +// query or a socket) is safe to share between requests. The proxy runs in the +// same Worker as the routes (OpenNext bundles it there), so it reaches the +// database through the same HYPERDRIVE binding — the one extra round trip is +// the first request an isolate serves. +let stored: string | undefined; + +export async function authSecret(): Promise { + const configured = process.env.AUTH_SECRET; + if (configured) { + return configured; + } + if (stored) { + return stored; + } + // Imported here rather than at the top so that a process with AUTH_SECRET + // set (the tests, local scripts) never loads the database client. + const { getDb } = await import("@/lib/db/queries"); + const db = await getDb(); + const rows = await db.execute<{ value: string }>( + sql`select value from app_private.secrets where name = 'auth_secret'` + ); + const value = rows[0]?.value; + if (!value) { + throw new Error( + "No AUTH_SECRET is set and the database holds no auth_secret: apply the migrations (020_app_secrets) or set AUTH_SECRET" + ); + } + stored = value; + return value; +} diff --git a/apps/web/lib/db/migrations/0001_app_secrets.sql b/apps/web/lib/db/migrations/0001_app_secrets.sql new file mode 100644 index 0000000..a02c25f --- /dev/null +++ b/apps/web/lib/db/migrations/0001_app_secrets.sql @@ -0,0 +1,14 @@ +-- The same SQL as packages/db/src/migrations/020_app_secrets/up.sql, which is +-- what db-migrate applies to stage and prod; this copy is for drizzle-kit +-- (`pnpm db:migrate`) against a local database. lib/auth-secret.ts reads it. +CREATE SCHEMA IF NOT EXISTS app_private; +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS app_private.secrets ( + name TEXT PRIMARY KEY, + value TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +--> statement-breakpoint +INSERT INTO app_private.secrets (name, value) +VALUES ('auth_secret', replace(gen_random_uuid()::text || gen_random_uuid()::text, '-', '')) +ON CONFLICT (name) DO NOTHING; diff --git a/apps/web/lib/db/migrations/0002_row_level_security.sql b/apps/web/lib/db/migrations/0002_row_level_security.sql new file mode 100644 index 0000000..89e8f55 --- /dev/null +++ b/apps/web/lib/db/migrations/0002_row_level_security.sql @@ -0,0 +1,32 @@ +-- The same SQL as packages/db/src/migrations/030_row_level_security/up.sql +-- (which says why), for drizzle-kit (`pnpm db:migrate`) against a local +-- database: the guard, then RLS on every table schema.ts marks `.enableRLS()`. +DO $$ +DECLARE + app_bypasses boolean; + not_owned text; +BEGIN + SELECT rolsuper OR rolbypassrls INTO app_bypasses FROM pg_roles WHERE rolname = 'postgres'; + SELECT string_agg(c.relname, ', ' ORDER BY c.relname) INTO not_owned + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') + AND pg_get_userbyid(c.relowner) <> 'postgres'; + IF NOT coalesce(app_bypasses, false) AND not_owned IS NOT NULL THEN + RAISE EXCEPTION 'row-level security would lock the app out of %: postgres (the role Hyperdrive connects as) neither owns them nor has SUPERUSER or BYPASSRLS', not_owned; + END IF; +END +$$; +--> statement-breakpoint +ALTER TABLE "Chat" ENABLE ROW LEVEL SECURITY; +--> statement-breakpoint +ALTER TABLE "Document" ENABLE ROW LEVEL SECURITY; +--> statement-breakpoint +ALTER TABLE "Message_v2" ENABLE ROW LEVEL SECURITY; +--> statement-breakpoint +ALTER TABLE "Stream" ENABLE ROW LEVEL SECURITY; +--> statement-breakpoint +ALTER TABLE "Suggestion" ENABLE ROW LEVEL SECURITY; +--> statement-breakpoint +ALTER TABLE "User" ENABLE ROW LEVEL SECURITY; +--> statement-breakpoint +ALTER TABLE "Vote_v2" ENABLE ROW LEVEL SECURITY; diff --git a/apps/web/lib/db/migrations/meta/_journal.json b/apps/web/lib/db/migrations/meta/_journal.json index a39cb79..b44fbd5 100644 --- a/apps/web/lib/db/migrations/meta/_journal.json +++ b/apps/web/lib/db/migrations/meta/_journal.json @@ -8,6 +8,20 @@ "when": 1710000000000, "tag": "0000_initial", "breakpoints": true + }, + { + "idx": 1, + "version": "7", + "when": 1791100000000, + "tag": "0001_app_secrets", + "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1791100000001, + "tag": "0002_row_level_security", + "breakpoints": true } ] } diff --git a/apps/web/lib/db/schema.ts b/apps/web/lib/db/schema.ts index 82d0ca0..708a119 100644 --- a/apps/web/lib/db/schema.ts +++ b/apps/web/lib/db/schema.ts @@ -11,6 +11,10 @@ import { varchar, } from "drizzle-orm/pg-core"; +// Every table is created with row-level security on and no policy +// (`.enableRLS()`; migration 030_row_level_security): Supabase's Data API +// serves `public` to anyone with the project's anon key, and gets nothing +// here. The app connects as the tables' owner, which RLS does not apply to. export const user = pgTable("User", { createdAt: timestamp("createdAt").notNull().defaultNow(), email: varchar("email", { length: 64 }).notNull(), @@ -21,7 +25,7 @@ export const user = pgTable("User", { name: text("name"), password: varchar("password", { length: 64 }), updatedAt: timestamp("updatedAt").notNull().defaultNow(), -}); +}).enableRLS(); export type User = InferSelectModel; @@ -35,7 +39,7 @@ export const chat = pgTable("Chat", { visibility: varchar("visibility", { enum: ["public", "private"] }) .notNull() .default("private"), -}); +}).enableRLS(); export type Chat = InferSelectModel; @@ -48,7 +52,7 @@ export const message = pgTable("Message_v2", { id: uuid("id").primaryKey().notNull().defaultRandom(), parts: json("parts").notNull(), role: varchar("role").notNull(), -}); +}).enableRLS(); export type DBMessage = InferSelectModel; @@ -66,7 +70,7 @@ export const vote = pgTable( (table) => ({ pk: primaryKey({ columns: [table.chatId, table.messageId] }), }) -); +).enableRLS(); export type Vote = InferSelectModel; @@ -87,7 +91,7 @@ export const document = pgTable( (table) => ({ pk: primaryKey({ columns: [table.id, table.createdAt] }), }) -); +).enableRLS(); export type Document = InferSelectModel; @@ -113,7 +117,7 @@ export const suggestion = pgTable( }), pk: primaryKey({ columns: [table.id] }), }) -); +).enableRLS(); export type Suggestion = InferSelectModel; @@ -131,6 +135,6 @@ export const stream = pgTable( }), pk: primaryKey({ columns: [table.id] }), }) -); +).enableRLS(); export type Stream = InferSelectModel; diff --git a/apps/web/lib/site.ts b/apps/web/lib/site.ts new file mode 100644 index 0000000..d345aca --- /dev/null +++ b/apps/web/lib/site.ts @@ -0,0 +1,5 @@ +// The product's name, written once: every page's , the sidebar's logo +// tooltip and the preview's label read it. A product built from this +// repository gets it rewritten to its own name at instantiation, so keep it +// literal and on one line. +export const SITE_NAME = "Chatbot"; diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index efba60a..db870d8 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -1,6 +1,7 @@ import path from "node:path"; import { initOpenNextCloudflareForDev } from "@opennextjs/cloudflare"; import type { NextConfig } from "next"; +import { PHASE_DEVELOPMENT_SERVER } from "next/constants"; const basePath = process.env.IS_DEMO === "1" ? "/demo" : ""; @@ -59,9 +60,16 @@ const nextConfig: NextConfig = { }; // `next dev` gets the Worker's bindings — HYPERDRIVE (pointed at the local -// Postgres by wrangler.jsonc's localConnectionString) and the BLOB bucket (a -// local R2 emulation) — through getCloudflareContext(); a no-op at build time. -initOpenNextCloudflareForDev(); - -// Upstream wrapped this in `withBotId` (Vercel BotID); see lib/bot.ts. -export default nextConfig; +// Postgres by wrangler.jsonc's localConnectionString), the BLOB bucket (a +// local R2 emulation) and AI (Workers AI, which has no local mode, so wrangler +// reaches it remotely: `wrangler login` first) — through +// getCloudflareContext(). In the dev server ONLY: the AI binding makes +// wrangler open a remote session, and a build must need no Cloudflare +// credential (Checks has none; a deploy lane's token is for the deploy). +// Upstream wrapped the config in `withBotId` (Vercel BotID); see lib/bot.ts. +export default function config(phase: string): NextConfig { + if (phase === PHASE_DEVELOPMENT_SERVER) { + initOpenNextCloudflareForDev(); + } + return nextConfig; +} diff --git a/apps/web/open-next.config.ts b/apps/web/open-next.config.ts index b17be64..d3a4c86 100644 --- a/apps/web/open-next.config.ts +++ b/apps/web/open-next.config.ts @@ -11,7 +11,7 @@ // write is a no-op on a read-only cache, so those lookups go to the gateway // each time. A port that wants them cached swaps this for // `r2IncrementalCache` on the BLOB bucket (plus the WORKER_SELF_REFERENCE -// service binding); see specs/epics/ai-chatbot/design.md. +// service binding). import { defineCloudflareConfig } from "@opennextjs/cloudflare/config"; import staticAssetsIncrementalCache from "@opennextjs/cloudflare/overrides/incremental-cache/static-assets-incremental-cache"; diff --git a/apps/web/package.json b/apps/web/package.json index 9d1773a..de18ed1 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -3,7 +3,7 @@ "version": "3.1.0", "private": true, "scripts": { - "build": "next build && opennextjs-cloudflare build --skipBuild --skipWranglerConfigCheck && opennextjs-cloudflare populateCache local", + "build": "next build && opennextjs-cloudflare build --skipBuild --skipWranglerConfigCheck && node scripts/populate-static-assets-cache.mjs", "check": "ultracite check", "db:check": "drizzle-kit check", "db:generate": "drizzle-kit generate", @@ -80,6 +80,7 @@ "tailwindcss-animate": "^1.0.7", "use-stick-to-bottom": "^1.1.6", "usehooks-ts": "^3.1.1", + "workers-ai-provider": "4.0.0", "zod": "^4.4.3" }, "devDependencies": { diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts index e1a75be..2c5892d 100644 --- a/apps/web/proxy.ts +++ b/apps/web/proxy.ts @@ -1,6 +1,8 @@ import { type NextRequest, NextResponse } from "next/server"; import { getToken } from "next-auth/jwt"; -import { guestRegex, isDevelopmentEnvironment } from "./lib/constants"; +import { usesSecureCookies } from "./lib/auth-cookie"; +import { authSecret } from "./lib/auth-secret"; +import { guestRegex } from "./lib/constants"; export async function proxy(request: NextRequest) { const { pathname } = request.nextUrl; @@ -9,6 +11,12 @@ export async function proxy(request: NextRequest) { return new Response("pong", { status: 200 }); } + // The deploy's smoke check and the bootstrap's probes read the database + // check without a session (app/api/health/route.ts). + if (pathname === "/api/health") { + return NextResponse.next(); + } + if (pathname.startsWith("/api/auth")) { return NextResponse.next(); } @@ -20,10 +28,12 @@ export async function proxy(request: NextRequest) { return NextResponse.next(); } + // AUTH_SECRET, or the key the database generated (lib/auth-secret.ts), + // under the cookie name Auth.js gave it (lib/auth-cookie.ts). const token = await getToken({ req: request, - secret: process.env.AUTH_SECRET, - secureCookie: !isDevelopmentEnvironment, + secret: await authSecret(), + secureCookie: usesSecureCookies(request), }); const base = process.env.NEXT_PUBLIC_BASE_PATH ?? ""; diff --git a/apps/web/scripts/populate-static-assets-cache.mjs b/apps/web/scripts/populate-static-assets-cache.mjs new file mode 100644 index 0000000..479561f --- /dev/null +++ b/apps/web/scripts/populate-static-assets-cache.mjs @@ -0,0 +1,27 @@ +// The build's last step: what `opennextjs-cloudflare populateCache local` +// does for the static-assets incremental cache (open-next.config.ts) — copy +// the pre-rendered pages OpenNext wrote to .open-next/cache into the Worker's +// static assets, under the directory that cache reads (OpenNext's own +// CACHE_DIR, imported so the two cannot drift). +// +// Not that command itself: before it copies anything it opens wrangler's +// platform proxy over wrangler.jsonc, only to read string vars, and the AI +// binding — Workers AI has no local simulator — makes the proxy open a +// session to a Cloudflare account. A build must need no credential (Checks +// has none, and a deploy lane's token is for the deploy). If +// open-next.config.ts moves to another incremental cache (R2, KV), go back to +// `opennextjs-cloudflare populateCache`: those are populated through the +// platform, not by a copy. +import { cpSync, existsSync } from "node:fs"; +import { CACHE_DIR } from "@opennextjs/cloudflare/overrides/incremental-cache/static-assets-incremental-cache"; + +const from = ".open-next/cache"; +const to = `.open-next/assets/${CACHE_DIR}`; +if (!existsSync(from)) { + console.error( + `populate: no ${from} — run \`opennextjs-cloudflare build\` first` + ); + process.exit(1); +} +cpSync(from, to, { recursive: true }); +console.log(`populate: the static-assets incremental cache, ${from} → ${to}`); diff --git a/apps/web/wiring.fixture.json b/apps/web/wiring.fixture.json index b082d1e..a7ff29c 100644 --- a/apps/web/wiring.fixture.json +++ b/apps/web/wiring.fixture.json @@ -1,12 +1,19 @@ { + "cloudflare-hyperdrive/dev": { + "hyperdrive_id": "00000000000000000000000000000002", + "hyperdrive_name": "dev-ai-chatbot-dev" + }, "cloudflare-hyperdrive/stage": { "hyperdrive_id": "00000000000000000000000000000001", "hyperdrive_name": "stg-ai-chatbot-stage" }, "cloudflare-hyperdrive/prod": { - "hyperdrive_id": "00000000000000000000000000000001", + "hyperdrive_id": "00000000000000000000000000000003", "hyperdrive_name": "prod-ai-chatbot-prod" }, + "cloudflare-r2/dev": { + "r2_bucket_name": "dev-ai-chatbot-dev" + }, "cloudflare-r2/stage": { "r2_bucket_name": "stg-ai-chatbot-stage" }, diff --git a/apps/web/wrangler.jsonc b/apps/web/wrangler.jsonc new file mode 100644 index 0000000..c6038b1 --- /dev/null +++ b/apps/web/wrangler.jsonc @@ -0,0 +1,51 @@ +// GENERATED from wrangler.template.jsonc 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. +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "ai-chatbot-web", + "main": ".open-next/worker.js", + "compatibility_date": "2026-10-01", + "compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"], + "assets": { + "directory": ".open-next/assets", + "binding": "ASSETS" + }, + "observability": { "enabled": true }, + // The Supabase project's Postgres, fronted by Hyperdrive. lib/db/queries.ts + // builds its `postgres` client per call from env.HYPERDRIVE.connectionString + // (upstream read POSTGRES_URL at module scope). Locally — `wrangler dev`, + // `next dev` — the binding points at a Postgres on localhost (README → + // Running it locally); `pnpm --filter @app/web db:migrate` applies the + // schema to it. + "hyperdrive": [ + { + "binding": "HYPERDRIVE", + "id": "00000000000000000000000000000001", + "localConnectionString": "postgres://postgres:postgres@localhost:5432/postgres" + } + ], + // Chat attachments. Vercel Blob's `put()` becomes a put into this bucket + // (app/(chat)/api/files/upload/route.ts) and the Worker serves the objects + // back at /api/files/<key> (app/(chat)/api/files/[...key]/route.ts). + "r2_buckets": [ + { + "binding": "BLOB", + "bucket_name": "stg-ai-chatbot-stage" + } + ], + // The model provider. Workers AI through this binding is the default for + // the chat, the titles and the artifact tools (lib/ai/providers.ts): it + // needs no key — the Worker's own account runs the models. Workers AI has + // no local mode, so `wrangler dev` and `next dev` reach it remotely + // (`wrangler login` first). + "ai": { + "binding": "AI" + } + // AUTH_SECRET and AI_GATEWAY_API_KEY are optional Worker secrets, never + // vars (`wrangler secret put`, README). Without AUTH_SECRET the session key + // is the one the database generated (lib/auth-secret.ts); without the + // gateway key only the Workers AI models are offered. REDIS_URL is absent + // too: without it the chat skips resumable streams and the Redis IP rate + // limit, as upstream does, and the per-user hourly limit still applies. +} diff --git a/apps/web/wrangler.template.jsonc b/apps/web/wrangler.template.jsonc index e13aee4..6dcabb8 100644 --- a/apps/web/wrangler.template.jsonc +++ b/apps/web/wrangler.template.jsonc @@ -1,10 +1,13 @@ -// Rendered to wrangler.jsonc (git-ignored) by tooling/wire: the verify lane -// renders from wiring.fixture.json, the deploy lane from the wiring documents -// the `cloudflare-hyperdrive` and `cloudflare-r2` Terraform roots -// lease-publish (WIRING_CLOUDFLARE_HYPERDRIVE_<ENV>, WIRING_CLOUDFLARE_R2_<ENV>). -// The workers-assets composition deploys one environment per job with no -// wrangler `--env`, so `__ENV__` names the environment this config 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, because the deploy lane checks the config exists before it +// builds), and on every Orun lane from the wiring documents the +// `cloudflare-hyperdrive` and `cloudflare-r2` Terraform roots lease-publish +// (WIRING_CLOUDFLARE_HYPERDRIVE_<ENV>, WIRING_CLOUDFLARE_R2_<ENV>) — 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": "ai-chatbot-web", @@ -20,7 +23,7 @@ // builds its `postgres` client per call from env.HYPERDRIVE.connectionString // (upstream read POSTGRES_URL at module scope). Locally — `wrangler dev`, // `next dev` — the binding points at a Postgres on localhost (README → - // Local development); `pnpm --filter @app/web db:migrate` applies the + // Running it locally); `pnpm --filter @app/web db:migrate` applies the // schema to it. "hyperdrive": [ { @@ -37,9 +40,19 @@ "binding": "BLOB", "bucket_name": "@@wiring(cloudflare-r2/__ENV__:r2_bucket_name)@@" } - ] - // AUTH_SECRET and AI_GATEWAY_API_KEY are Worker secrets, never vars: - // .dev.vars locally, `wrangler secret put` per environment (README → - // Deploying). REDIS_URL is deliberately absent: without it the template - // skips resumable streams and the Redis IP rate limit, as upstream does. + ], + // The model provider. Workers AI through this binding is the default for + // the chat, the titles and the artifact tools (lib/ai/providers.ts): it + // needs no key — the Worker's own account runs the models. Workers AI has + // no local mode, so `wrangler dev` and `next dev` reach it remotely + // (`wrangler login` first). + "ai": { + "binding": "AI" + } + // AUTH_SECRET and AI_GATEWAY_API_KEY are optional Worker secrets, never + // vars (`wrangler secret put`, README). Without AUTH_SECRET the session key + // is the one the database generated (lib/auth-secret.ts); without the + // gateway key only the Workers AI models are offered. REDIS_URL is absent + // too: without it the chat skips resumable streams and the Redis IP rate + // limit, as upstream does, and the per-user hourly limit still applies. } diff --git a/blueprint.yaml b/blueprint.yaml new file mode 100644 index 0000000..5b74cb0 --- /dev/null +++ b/blueprint.yaml @@ -0,0 +1,166 @@ +# The ai-chatbot 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: ai-chatbot + displayName: AI Chatbot — Next.js chat on Cloudflare Workers AI and Supabase + description: > + Vercel's Next.js AI Chatbot as a product of its own: streaming chat with + tools and artifacts, guest and registered sign-in, saved chat history and + image attachments, built by OpenNext into one Cloudflare Worker. Its + models run on Workers AI through the Worker's own binding — no model key + to bring — its Postgres is a Supabase project reached through Hyperdrive, + and its attachments live in R2. Terraform creates the data plane per + environment, db-migrate applies the schema, and CI deploys it all to stage + and prod on merge, infra before app. Needs a Supabase organisation with + room for two projects (stage and prod — the free plan's limit). Live in + about twenty minutes. + tags: [ai, chatbot, workers-ai, supabase, cloudflare, nextjs] +spec: + source: + repo: sourceplane/ai-chatbot + # No `tag`. The registry pins it; this file is fetched at it. + + # ── What the operator reads first ──────────────────────────────────────── + overview: + lede: > + An AI chatbot with history, tools, artifacts and attachments — Workers + AI for the models, Supabase for Postgres, R2 for files, Terraform + holding the data plane, and no model key to bring. + architecture: + - layer: Edge + items: [web, Workers AI] + - layer: Data + items: [Supabase Postgres, Hyperdrive, R2, db-migrate] + - layer: Delivery + items: [Terraform, GitHub Actions, OpenNext] + outcome: + - Live on stage and prod, guests chatting on Workers AI + - A Supabase project and an R2 bucket per environment, migrated on merge + - Other models through the AI Gateway when you add its key + + requires: + # GitHub arrives as the App installation plus the repo link; Cloudflare + # and Supabase are the two provider connections the build mints from. + # No AI vendor is here: the models are Workers AI, reached through the + # Worker's own binding on the Cloudflare account, and the AI Gateway's + # key is optional — its owner adds it afterwards (the product's README, + # "Models"). + # + # TWO SUPABASE PROJECTS. The build creates one per environment (stage and + # prod); Supabase's free plan allows two active projects per + # organisation, so the connected organisation needs room for both. + integrations: [github, cloudflare, supabase] + 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: Product name + pattern: "^[A-Za-z0-9][A-Za-z0-9 .,'&-]{1,48}$" + help: The name people see — in every page title and the sidebar. + example: Acme Chat + - key: productdomain + label: Product domain + pattern: "^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$" + help: The domain the product will answer on. It does not need to exist — the app 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 product'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 app 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. Six keys, six scopes, + # on purpose — the deploy token deliberately cannot touch Hyperdrive or R2. + # No model key is here: Workers AI needs none. + secrets: + - key: CLOUDFLARE_API_TOKEN + provider: cloudflare + template: workers-deploy + why: Deploys the app's Worker and its static assets + - key: CLOUDFLARE_HYPERDRIVE_TOKEN + provider: cloudflare + template: hyperdrive-edit + why: Hyperdrive — the deploy token deliberately cannot touch it + - key: CLOUDFLARE_R2_TOKEN + provider: cloudflare + template: r2-data + why: Applies the attachments' R2 bucket — the deploy token deliberately cannot touch R2 + - key: CLOUDFLARE_ACCOUNT_ID + provider: cloudflare + template: account-id + why: Connection fact, not a secret + fact: true + - key: SUPABASE_ACCESS_TOKEN + provider: supabase + template: management-access + why: Project create and migrations + - key: SUPABASE_ORG_ID + provider: supabase + template: org-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: chatbot-baselining # = repo-blueprint.yaml's `epicSlug` default + epicName: "Chatbot baselining — {productname}" + milestones: + - 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: a Supabase project takes five to seven minutes to come up, + # and the app's deploy waits on it, on Hyperdrive, on the bucket and on + # the migrations. + expectedMinutes: 20 + tokenChannel: ORUN_TOKEN_FILE # how a runner hands over its refreshed token + verify: + urls: + - "https://{reponame}-web-{env}.{subdomain}.workers.dev/ping" + - "https://{reponame}-web-{env}.{subdomain}.workers.dev/api/health" + envs: [stage, prod] diff --git a/docs/phases/01-product.md b/docs/phases/01-product.md new file mode 100644 index 0000000..3d5a5b9 --- /dev/null +++ b/docs/phases/01-product.md @@ -0,0 +1,140 @@ +# 01-product — the product, in one landing + +The whole product lands as ONE pull request, and ONE convergence on main +provisions and deploys it on stage and prod: the Supabase project, the +Hyperdrive config over its database, the migrations, the R2 bucket and the +chatbot — infra before app, per environment. + +**Places** every module `repo-blueprint.yaml` declares: the root manifests, +CI, tooling and identity; `infra/terraform/supabase`, +`infra/terraform/cloudflare-hyperdrive`, `infra/terraform/cloudflare-r2` and +`infra/db-migrate`; `packages/db` (the migrations and their runner); +`apps/web`; and `tests/web`, `tests/db`. `testing/phases.test.sh` holds the +set. + +**Requires** three live connections, probed and waited for (up to ten +minutes, so a consent can be clicked while it waits): the GitHub App on the +account that OWNS the repository — the platform sees a PR only through that +installation — and Cloudflare and Supabase, which every credential below is +minted from. The Supabase organisation needs room for two projects (stage +and prod; the free plan's limit). + +## How one convergence keeps the order + +| what has to come first | how the plan holds it | +|---|---| +| the Supabase project before Hyperdrive | `cloudflare-hyperdrive` reads `SUPABASE_PROJECT_REF` and `SUPABASE_DB_PASSWORD`, which the `supabase` apply lease-publishes, and declares `dependsOn: supabase`, `mode: enforced` on main. A job resolves its secrets when it STARTS, so the values are there | +| the migrations after the project — and after Hyperdrive | `db-migrate` reads the project's three credentials and declares `dependsOn` on `supabase` and `cloudflare-hyperdrive`, enforced on main. Nothing in it needs Hyperdrive: a migration is the one step a re-run cannot take back, so it runs only once everything else the app needs exists, right before the app | +| the bucket before the app | `web` binds the bucket by name (`WIRING_CLOUDFLARE_R2_<ENV>`, rendered into `wrangler.jsonc`) and declares `dependsOn: cloudflare-r2`, enforced on main. The bucket depends on nothing, so it applies beside the Supabase chain | +| the app last | `web` binds the Hyperdrive id (`WIRING_CLOUDFLARE_HYPERDRIVE_<ENV>`) and queries the migrated schema, so it declares `dependsOn` on `cloudflare-hyperdrive` and `db-migrate` too, enforced on main | +| stage before prod | deferred during the bootstrap (below), so both environments run their chains side by side | + +Every one of these edges is **advisory on a pull request**, which applies and +deploys nothing. `testing/placement.test.sh` plans the placed product's own +push to main and reads the order off it: +`supabase → cloudflare-hyperdrive → db-migrate → web`, and +`cloudflare-r2 → web`. + +## What runs + +| hook | what it does | +|---|---| +| `task` (pre) | finds the phase's task and yields its key | +| `retouch` | one trailing `# orun: redeploy 01-product <stamp>` line in each component `.baseline/tasks/01-product.TaskContract.yaml` names (supabase, cloudflare-hyperdrive, cloudflare-r2, db, db-migrate, web), so a RE-RUN has a diff to land | +| `git-init`, `stage` | the tree becomes a git repository with a populated index (the rebrand enumerates `git ls-files`) | +| `rebrand` | renames the baseline's identity to the product's: the slug (intent, worker, secret project, the `repo` the Supabase project, Hyperdrive config and bucket are named after), the name seam, the domain, the workers.dev subdomain. The upstream template's repository link and every migration are left alone | +| `orun-workspace` | writes the product's workspace into `intent.yaml` | +| `work-tree` | strips this repository's `work:` block from the product's intent | +| `promotion`, `dev-lanes` | defer prod's wait on stage and dev's push lanes until `02-docs` | +| `restage`, `rebrand-verify` | the sweep: no baseline identity left | +| `pnpm-lockfile` | confirms the complete lockfile `root-pnpm-lock` placed | +| `repo` | `orun.repo/ensure@v1`: creates (or finds) `<githuborg>/<reponame>` | +| `link` | the repository becomes the workspace's (`orun cloud link`, best effort; `orun cloud check` is the gate). Every convergence lane authenticates over GitHub OIDC through that link | +| `secret-*` | six `orun.integrations/reconcile@v1` hooks, one key and one scope each: `CLOUDFLARE_API_TOKEN` (workers-deploy), `CLOUDFLARE_HYPERDRIVE_TOKEN` (hyperdrive-edit), `CLOUDFLARE_R2_TOKEN` (r2-data), `CLOUDFLARE_ACCOUNT_ID` (account-id), `SUPABASE_ACCESS_TOKEN` (management-access), `SUPABASE_ORG_ID` (org-id). Keys that exist are kept | +| `land` | one PR, checked (Checks, and `plan` alone on a bootstrap branch), then merged | +| `converge` (await) | `orun.run/watch@v1` on the merge commit's run; resumes it up to three times | +| `wiring` (await) | `orun.secrets/exists@v1`: `SUPABASE_PROJECT_REF`, `SUPABASE_DB_PASSWORD`, `SUPABASE_DB_URL`, `WIRING_CLOUDFLARE_HYPERDRIVE` and `WIRING_CLOUDFLARE_R2` on stage and prod | +| `verify` (await) | `orun.http/probe@v1`: `/ping` and `/api/health` on both workers.dev URLs. Not `/`: every page sends a visitor with no session to the guest sign-in (a redirect), and the probe wants a 200 | + +## What the convergence does, per environment + +1. **supabase** — `terraform apply`: one project, `<reponame>-<env>`, in the + org `SUPABASE_ORG_ID` names, with a generated database password. Its + outputs are lease-published as `SUPABASE_PROJECT_REF`, + `SUPABASE_DB_PASSWORD` and `SUPABASE_DB_URL`. A new project takes five to + seven minutes to come up. +2. **cloudflare-hyperdrive** — `terraform apply` with the Hyperdrive token: a + config over the project's Postgres, published as + `WIRING_CLOUDFLARE_HYPERDRIVE` (its id and name). +3. **cloudflare-r2** — `terraform apply` with the R2 token (`r2-data`): one + bucket, published as `WIRING_CLOUDFLARE_R2` (its name). Beside steps 1–2; + it waits on nothing. +4. **db-migrate** — builds `@saas/db` and applies every migration the + database's `_migrations.applied` ledger does not have, through Supabase's + Management API: the template's schema, `app_private.secrets` with the + session key the environment generates for itself, and row-level security + on every table in `public` — closed to Supabase's Data API, open to the + app, which owns them. +5. **web** — installs, re-renders `wrangler.jsonc` from this environment's + two wiring documents, builds with OpenNext, deploys `<reponame>-web-<env>` + with its `HYPERDRIVE`, `BLOB` (R2) and `AI` bindings, and smoke-tests it: + `/ping`, and `/api/health`, which answers only when the database behind + the binding is reachable and migrated. + +No model key is in it: the models are Workers AI through the Worker's `AI` +binding. The AI Gateway's models turn on when the owner adds its key (the +product's README, "Models"). + +**An open platform risk.** The deploy step binds the bucket with the +`workers-deploy` token, which is scoped to Workers Scripts and KV. Whether +Cloudflare lets that token attach an R2 binding to a Worker is unverified +live; if it does not, the `web` deploy fails with an authentication error +naming R2, and the fix belongs to the platform's `workers-deploy` template, +not to this tree. + +## Verify / done means + +- The convergence for the merge commit is green on stage and prod. +- The five published secrets exist on stage and prod. +- `/ping` and `/api/health` answer on both workers.dev URLs. + +## Failure modes + +| symptom | meaning → fix | +|---|---| +| parks on the `providers` probe | a connection is missing — GitHub on the repository's owner, Cloudflare, or Supabase. Connect it (console → Integrations); the probe is a wait, not a failure | +| supabase apply: project limit reached | the organisation already has two active projects (the free plan's limit). Pause or delete one, or upgrade, then re-run the phase | +| supabase apply: `does not support oauth access` | the provider is above 1.5.x, which reads billing endpoints an OAuth token cannot — `~> 1.5.1` is pinned for this reason | +| supabase apply: project name already exists | `adopt.tf` looks the project up by name and imports it — if you removed that file, restore it | +| hyperdrive or db-migrate lane: secret resolution failed (`SUPABASE_*`) | the supabase apply for that environment did not publish — read its log; both wait on it, so they show as not run | +| hyperdrive apply: Authentication error (10000) | the token in play is workers-deploy, which deliberately cannot touch Hyperdrive — the component binds `CLOUDFLARE_HYPERDRIVE_TOKEN` | +| r2 apply: Authentication error (10000) | the component binds `CLOUDFLARE_R2_TOKEN` (r2-data); check the `secret-r2-data` hook minted it | +| web deploy: an authentication error naming R2 or a bucket | the open risk above: the `workers-deploy` token could not attach the `BLOB` binding | +| db-migrate: checksum mismatch | an applied migration's file changed. Never edit one; add a new migration | +| db-migrate: `row-level security would lock the app out of …` | migration 030's guard: the tables in `public` are not owned by `postgres` (the role Hyperdrive connects as), and `postgres` has neither SUPERUSER nor BYPASSRLS. Nothing was enabled and the app did not deploy. Give `postgres` the tables (`ALTER TABLE … OWNER TO postgres`) or BYPASSRLS, then re-run the phase | +| web smoke: `/api/health` 503 | the database is unreachable through the binding (`database: unreachable`) or not migrated (`schema: missing`) — the Hyperdrive and db-migrate lanes for that environment say which | +| `build-app` fails: `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 (lane-scoped install), which Next 16's Turbopack refuses. Pin 0.19.0 — `intent.yaml` says why | +| `verify-app-structure` fails: `test -f wrangler.jsonc` | `apps/web/wrangler.jsonc` is not committed. It must be: the check runs before the build, in a fresh checkout (`pnpm run wire:fixture` renders it) | +| the watch says green, the probe says 404 | another workflow ran on the push and the watch took its run. Only `ci.yml` may run on a push to main | +| re-run lands nothing | the hooks did not run (`--run-hooks`), or the contract names no component — `node tooling/bootstrap/retouch.mjs --check --affects .baseline/tasks/01-product.TaskContract.yaml` in the product's tree says which | + +## Re-running + +Idempotent: placement is additive, the rebrand is a no-op on branded files, +`git init` and the repo step are guarded, the Supabase project, the +Hyperdrive config and the bucket are adopted rather than recreated, and the +migration ledger lives in the database, so only missing migrations apply. A +re-run of a phase whose PR already merged lands the retouch markers alone, +which re-plans exactly the components they name. Once the tree is branded +the phase derives as `drifted`, so `--resume` leaves it alone; re-run it +deliberately with `--phase 01-product` (or `--redo 01-product`). + +## What one convergence will run, before running it + +From a placed product's tree: + +```bash +node <baseline>/tooling/bootstrap/promotion.mjs --defer && node <baseline>/tooling/bootstrap/dev-lanes.mjs --defer +orun plan --intent intent.yaml --trigger github-push-main -v lanes +git checkout intent.yaml +``` diff --git a/docs/phases/02-docs.md b/docs/phases/02-docs.md new file mode 100644 index 0000000..c74288e --- /dev/null +++ b/docs/phases/02-docs.md @@ -0,0 +1,41 @@ +# 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 `/ping` and `/api/health` on both environments, reads from `/api/health` which model provider serves (Workers AI, and whether the AI Gateway is connected), 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, a custom +domain, or connecting the AI Gateway: every generated section is re-rendered +from scratch. + +```bash +orun new --blueprint repo-blueprint.yaml --out <product-checkout> \ + --run-hooks --phase 02-docs --values <values.yaml> +``` + +## If a bootstrap stops before this phase + +The promotion gate and dev's push activation stay deferred: `intent.yaml` +carries a `# @promotion-deferred:…` and a `# @dev-lanes-deferred:…` marker. +Running this phase restores both, or by hand from the baseline checkout: + +```bash +node tooling/bootstrap/promotion.mjs --restore --file <product>/intent.yaml +node tooling/bootstrap/dev-lanes.mjs --restore --file <product>/intent.yaml +``` diff --git a/docs/phases/README.md b/docs/phases/README.md new file mode 100644 index 0000000..ce492d7 --- /dev/null +++ b/docs/phases/README.md @@ -0,0 +1,112 @@ +# The phases — one blueprint, two selections, one landing that deploys + +`repo-blueprint.yaml` declares two phases that take a chatbot product from +**nothing** to **live on stage and prod, documented**. Run them one at a time +with `--phase <name>`, or both 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. + +Each phase follows the same contract: + +> **place its modules → brand them → land them as one pull request → watch +> the convergence that merge triggers (auto-resumed) → verify the outcome.** + +Run from the baseline checkout (the blueprint's source is `path: .`); the +product's repository is wherever `--out` points. + +## Execution order + +| phase | lands | verified by | +|---|---|---| +| [`01-product`](01-product.md) | **the GitHub repo created**, then the WHOLE product in one PR: intent, CI, tooling, the Supabase, Hyperdrive and R2 Terraform roots, the migrations, the app and its tests — one convergence provisions and deploys it in dependency order | convergence green; `SUPABASE_*`, `WIRING_CLOUDFLARE_HYPERDRIVE` and `WIRING_CLOUDFLARE_R2` published on stage and prod; `/ping` and `/api/health` answer on both | +| [`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 builds the product.** The order the data plane needs — the +Supabase project before the Hyperdrive config over its database, both before +the migrations, all of them and the R2 bucket before the app — is not a +sequence of landings. It is the components' own `dependsOn`, every edge +`mode: enforced` on a push to `main` and advisory on a pull request: + +``` +supabase ──▶ cloudflare-hyperdrive ──▶ db-migrate ──▶ web (per environment) + cloudflare-r2 ──▶ web +``` + +A job resolves its secrets when it starts, so each one reads what the apply +before it published: Hyperdrive the project's ref and password, db-migrate +the project's credentials, the app's deploy the Hyperdrive id and the bucket +name it binds. `testing/placement.test.sh` reads that order off the +product's own `orun plan --trigger github-push-main`. + +Every landing is a pull request on a branch named for its task +(`orun/BASE-<n>-<phase>`). 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. + +There is no custom-domain phase: the app answers on workers.dev. Attaching a +domain needs zone permissions the brokered `workers-deploy` token does not +carry, so it is an owner's step after the bootstrap (the product's README, +"Custom domain"). + +## Inputs + +`01-product` takes the product'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 `chatbot-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/products/acme-chat --run-hooks --phase 01-product \ + --values ~/acme-chat.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`). + +## Two Supabase projects + +The convergence creates one Supabase project per environment — stage and +prod — in the organisation the Supabase connection names. Supabase's free +plan allows **two active projects per organisation**, so that organisation +must have room for both before `01-product` runs (BOOTSTRAP.md). + +## The model is not a phase + +The platform brokers no AI vendor, so nothing here mints, asks for or waits +on a model key. The chatbot's models are Workers AI, reached through the +Worker's own `AI` binding on the Cloudflare account the build already +deploys to: a fresh product chats with nothing else configured. The Vercel +AI Gateway's models are optional — the owner adds `AI_GATEWAY_API_KEY` as a +Worker secret afterwards (the product's README, "Models"), and re-running +`02-docs` records it. + +## When a phase fails + +- **Before it lands** (a probe that timed out, a rebrand residue, a refused + link): nothing was merged. Fix what the message names and re-run the phase. +- **After it lands** (the convergence went red): the files are on main. + `orun.run/watch@v1` has already resumed the run up to three times. Re-run + the phase (`--phase 01-product`, `--redo 01-product` under `--resume`, or + the console's Retry): its `retouch` hook gives the landing a diff and the + components it names re-plan. Supabase, Hyperdrive and the bucket are + adopted rather than recreated (`adopt.tf`), and the migration ledger lives + in the database, so a re-run applies only what is missing. diff --git a/hooks/render-deployment-docs.sh b/hooks/render-deployment-docs.sh new file mode 100755 index 0000000..ca7f6d2 --- /dev/null +++ b/hooks/render-deployment-docs.sh @@ -0,0 +1,194 @@ +#!/usr/bin/env bash +# Render the product's LIVE-DEPLOYMENT documentation from verified state. +# Called by phase 02-docs as a `run:` hook (and safe to run by hand, from the +# product's checkout). Idempotent: the generated file and the README section +# are fully re-rendered on every run, so re-running after a redeploy, a custom +# domain or connecting the AI Gateway refreshes them. +# +# hooks/render-deployment-docs.sh <out> <workspace> <baseline-dir> +# +# What it writes (in <out>): +# ai/context/deployment.md — REGENERATED: URLs with live probe results +# (the Worker, its database check, which model +# provider serves), identity, 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 <!-- 02-docs:begin/end --> +# 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 <out> <workspace> <baseline-dir>}" +ws="${2:-}" +L="${3:?usage: render-deployment-docs.sh <out> <workspace> <baseline-dir>}" + +cd "$out" +vals=".rebrand/values.json" +[ -f "$vals" ] || { echo "render-docs: $vals missing — is this a bootstrapped product?" >&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="?" + +# curl emits the -w format even on connection failure (000) — capture, don't +# append, or a failed probe reads "000000". +probe() { local c; c="$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 "$1" 2>/dev/null)" || true; printf '%s' "${c:-000}"; } +badge() { case "$1" in 2*|3*) echo "LIVE ($1)" ;; 000) echo "unreachable" ;; *) echo "answering $1" ;; esac; } + +stage_url="https://${brand}-web-stage.${sub}.workers.dev" +prod_url="https://${brand}-web-prod.${sub}.workers.dev" + +# Which model provider serves: /api/health names the default Workers AI +# model and whether the AI Gateway's key is set (a yes/no, never the key). +# Read only from an answer that is 200: anything else says nothing about it. +models_state() { + local page code + page="$(mktemp)" + code="$(curl -s -o "$page" -w '%{http_code}' --max-time 20 "$1/api/health" 2>/dev/null)" || true + code="${code:-000}" + if [ "$code" != 200 ]; then echo "unknown (/api/health $(badge "$code")) | unknown" + else python3 -c " +import json,sys +m=(json.load(open(sys.argv[1])).get('models') or {}) +print('Workers AI, ' + str(m.get('default', '?')) + ' | ' + str(m.get('gateway', '?')))" "$page" 2>/dev/null || echo "unknown | unknown" + fi + rm -f "$page" +} + +# The app row probes /ping: every page sends a visitor with no session to the +# guest sign-in (a redirect); /ping is the Worker's own answer. +rows="" +for pair in "stage|$stage_url" "prod|$prod_url"; do + env="${pair%%|*}"; url="${pair#*|}" + rows+="| app (${env}) | ${url} (probed at /ping) | $(badge "$(probe "$url/ping")") |"$'\n' + rows+="| database check (${env}) | ${url}/api/health | $(badge "$(probe "$url/api/health")") |"$'\n' +done +models_stage="$(models_state "$stage_url")"; models_prod="$(models_state "$prod_url")" + +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 product predates it. +mkdir -p ai/context +if [ ! -f ai/context/operations.md ] && [ -f "$L/ai/context/operations.md" ]; then + cp "$L/ai/context/operations.md" ai/context/operations.md + git add ai/context/operations.md 2>/dev/null || true + node "$L/tooling/rebrand/rebrand.mjs" --values "$vals" --allow-dirty >/dev/null 2>&1 || true + echo "render-docs: healed ai/context/operations.md" +fi + +cat > ai/context/deployment.md <<EOF +# ${repo} — live deployment manifest + +> GENERATED by the \`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\` | +| CI lane CLI pin | orun \`${lanepin}\` (\`.github/workflows/ci.yml\`) | + +## Public URLs (probed ${now}) + +| surface | URL | status | +|---|---|---| +${rows} +\`/api/health\` answers 200 only when the Worker reaches the Supabase database +through its Hyperdrive binding and the migrations are applied. The \`dev\` +environment is verify-only by design — no deployed URL. + +## Models + +| environment | default model | AI Gateway | +|---|---|---| +| stage | ${models_stage} | +| prod | ${models_prod} | + +The chat runs on Workers AI through the Worker's own \`AI\` binding — no key. +The AI Gateway is not a provider the platform brokers: its key is an optional +Worker secret the owner adds per environment (README, "Models"), which adds +the gateway's models to the picker. + +## 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 +and Supabase connections; no long-lived values at rest). The Supabase +project's ref, password and URL and the Hyperdrive and R2 wiring are +published by the Terraform applies onto the stage and prod rungs. + +## 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. +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 = "<!-- 02-docs:begin -->", "<!-- 02-docs:end -->" +body = f"""{begin} +This product is **live**. Verified URLs, identity, which model provider serves +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/db-migrate/component.yaml b/infra/db-migrate/component.yaml index e0b7938..4c77082 100644 --- a/infra/db-migrate/component.yaml +++ b/infra/db-migrate/component.yaml @@ -15,11 +15,28 @@ spec: owner: platform domain: infra + # Migrations read the Supabase connection from the orun secrets the + # `supabase` apply lease-publishes, so on main they wait for it — and for + # the Hyperdrive config over that database. Nothing here needs Hyperdrive; + # the edge is there because a migration is the one step of a convergence a + # re-run cannot take back, so it runs only once everything the Worker needs + # besides the schema exists, immediately before the Worker deploys. The + # order on main is supabase → cloudflare-hyperdrive → db-migrate → web. + # Enforced on main, advisory on a pull request (which applies nothing). dependsOn: - component: db - # Migrations read the Supabase connection from the orun secrets the - # `supabase` component lease-publishes post-apply. - component: supabase + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + - component: cloudflare-hyperdrive + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request path: packages/db/src/migrations diff --git a/infra/terraform/cloudflare-hyperdrive/component.yaml b/infra/terraform/cloudflare-hyperdrive/component.yaml index 6d6ef1b..4fa4d75 100644 --- a/infra/terraform/cloudflare-hyperdrive/component.yaml +++ b/infra/terraform/cloudflare-hyperdrive/component.yaml @@ -14,10 +14,18 @@ spec: owner: platform domain: infra - # Hyperdrive's origin is the Supabase Postgres connection that `supabase` - # writes to AWS Secrets Manager; it must run after that secret exists. + # Hyperdrive's origin is the Supabase project's Postgres, whose ref and + # password the `supabase` apply lease-publishes (SUPABASE_PROJECT_REF, + # SUPABASE_DB_PASSWORD, read below). A job resolves its secrets when it + # starts, so on main this waits for that apply, `mode: enforced`; a pull + # request applies nothing, so there it is advisory. dependsOn: - component: supabase + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request parameters: orgName: sourceplane diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl b/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl new file mode 100644 index 0000000..c133371 --- /dev/null +++ b/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl @@ -0,0 +1,50 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/cloudflare/cloudflare" { + version = "4.52.7" + constraints = "~> 4.30" + hashes = [ + "h1:pPItIWii5oymR+geZB219ROSPuSODPLTlM4S/u8xLvM=", + "h1:uUUa9dY0XQOycI8pxg16PFFtL0WCTi9uEJz8trTQ7pU=", + "h1:y3rV8KF2q6GEMANNlf5EkKJurlfbKlIKpjGcdxoy7pQ=", + "zh:0c904ce31a4c6c4a5b3bf7ff1560e77c0cc7e2450c8553ded8e8c90398e1418b", + "zh:36183d310c36373fe4cb936b83c595c6fd3b0a94bc7827f28e5789ccbf59752e", + "zh:556a568a6f0235e8f41647de9e4d3a1e7b1d6502df8b19b54ec441f1c653ea10", + "zh:633ebbd5b0245e75e500ef9be4d9e62288f97e8da3baaa51323892a786d90285", + "zh:6acfe60cf52a65ba8f044f748548d2119e7f4fd7f8ebcb14698960d87c68f529", + "zh:890df766e9b839623b1f0437355032a3c006226a6c200cd911e15ee1a9014e9f", + "zh:904acc31ebb9d6ef68c792074b30532ee61bf515f19e0a3c75b46f126cca1f13", + "zh:a1d0a81246afc8750286d3f6fe7a8fbe6460dd2662407b28dbfbabb612e5fa9d", + "zh:a41a36fe253fc365fe2b7ffc749624688b2693b4634862fda161179ab100029f", + "zh:a7ef269e77ffa8715c8945a2c14322c7ff159ea44c15f62505f3cbb2cae3b32d", + "zh:b01aa3bed30610633b762df64332b26f8844a68c3960cebcb30f04918efc67fe", + "zh:b069cc2cd18cae10757df3ae030508eac8d55de7e49eda7a5e3e11f2f7fe6455", + "zh:b2d2c6313729ebb7465dceece374049e2d08bda34473901be9ff46a8836d42b2", + "zh:db0e114edaf4bc2f3d4769958807c83022bfbc619a00bdf4c4bd17faa4ab2d8b", + "zh:ecc0aa8b9044f664fd2aaf8fa992d976578f78478980555b4b8f6148e8d1a5fe", + ] +} + +provider "registry.terraform.io/hashicorp/external" { + version = "2.4.0" + constraints = "~> 2.3" + hashes = [ + "h1:AmY6ZeIvqoTT5ZjzD+P49PeQH6Va1QLMkX+7MUQfYoA=", + "h1:K0eLC86zbhVoyS4THmY00KJZKAQORuz6dt9Ro3xo/wA=", + "h1:gXyK3ZkweDqkwEV9waEDWpljUY4yZXi/nRUSEuJn83k=", + "zh:0772afb42b658468ac5e15df33bf2080456f8f0b8ab163bfe9c50d2b2ea02135", + "zh:0ac31a9aaa43dfcff5944b791596cdc94e153348e4bb4642282d034dff548134", + "zh:32d8492b1bdcc956ca3c6d00c6392d0a83942ff11d4820c7ee63ca6796e06950", + "zh:3c0482e894429f528ce6655a76ab0d8a9f7c0dacc6c828865e1515d4a7dbb852", + "zh:61e68100b4db2f930b31491f23c602126382fd5e51252be1b551f0e17f8ddbee", + "zh:6d60f615a0ad85eb962c9eb94f25e3eba7a72684ce276ba5dfb23f36b295a8f8", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:9ced2745eb5f1346203027d2dd7bf856ad1d279a25730ff7dbc6eec187aaca0c", + "zh:a8378558a177d43f55aa0d79d4fae91a704695122a1b109668c1daa8fb76f09d", + "zh:aadd98086133d3ebea67437d56512fdcc6dfb3bd34dfc23f276c0db9272e27b4", + "zh:beff701b653841e70441978137768f54e7dc6c27e7bf12a4589087f01f5bbcee", + "zh:c91c2223b29fdbc0044d20e1936ccc051d010727a13f2ff1e75e51f09bff33a3", + "zh:d491f9c2d32a39dc4031628469ae7c8aec0074312a7c1f0286b173cdcf854a54", + ] +} diff --git a/infra/terraform/cloudflare-r2/component.yaml b/infra/terraform/cloudflare-r2/component.yaml index 2b86fe5..d33875a 100644 --- a/infra/terraform/cloudflare-r2/component.yaml +++ b/infra/terraform/cloudflare-r2/component.yaml @@ -24,11 +24,14 @@ spec: secretOutputs: "WIRING_CLOUDFLARE_R2=wiring" # The Cloudflare Terraform provider authenticates via the CLOUDFLARE_API_TOKEN - # env var, resolved by orun from the project-rung brokered secret (fresh per - # run, Workers R2 Storage Write scope). Declared at component level because plan-only - # lanes refresh against the live Cloudflare API too, not just apply. + # env var, resolved by orun from the project-rung brokered secret — minted + # fresh per run from the r2-data template (Workers R2 Storage Write; the + # workers-deploy token the app deploys with deliberately cannot touch R2). + # adopt.tf's bucket lookup reads the same variable. Declared at component + # level because plan-only lanes refresh against the live Cloudflare API + # too, not just apply. secretEnv: - CLOUDFLARE_API_TOKEN: "secret://ai-chatbot/ai-chatbot/{{ .environment }}/CLOUDFLARE_API_TOKEN" + CLOUDFLARE_API_TOKEN: "secret://ai-chatbot/ai-chatbot/{{ .environment }}/CLOUDFLARE_R2_TOKEN" # Non-secret connection fact (account-id template) — replaces the ambient # CLOUDFLARE_ACCOUNT_ID / TF_VAR_cloudflare_account_id CI values. CLOUDFLARE_ACCOUNT_ID: "secret://ai-chatbot/ai-chatbot/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" diff --git a/infra/terraform/cloudflare-r2/terraform/.terraform.lock.hcl b/infra/terraform/cloudflare-r2/terraform/.terraform.lock.hcl new file mode 100644 index 0000000..c133371 --- /dev/null +++ b/infra/terraform/cloudflare-r2/terraform/.terraform.lock.hcl @@ -0,0 +1,50 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/cloudflare/cloudflare" { + version = "4.52.7" + constraints = "~> 4.30" + hashes = [ + "h1:pPItIWii5oymR+geZB219ROSPuSODPLTlM4S/u8xLvM=", + "h1:uUUa9dY0XQOycI8pxg16PFFtL0WCTi9uEJz8trTQ7pU=", + "h1:y3rV8KF2q6GEMANNlf5EkKJurlfbKlIKpjGcdxoy7pQ=", + "zh:0c904ce31a4c6c4a5b3bf7ff1560e77c0cc7e2450c8553ded8e8c90398e1418b", + "zh:36183d310c36373fe4cb936b83c595c6fd3b0a94bc7827f28e5789ccbf59752e", + "zh:556a568a6f0235e8f41647de9e4d3a1e7b1d6502df8b19b54ec441f1c653ea10", + "zh:633ebbd5b0245e75e500ef9be4d9e62288f97e8da3baaa51323892a786d90285", + "zh:6acfe60cf52a65ba8f044f748548d2119e7f4fd7f8ebcb14698960d87c68f529", + "zh:890df766e9b839623b1f0437355032a3c006226a6c200cd911e15ee1a9014e9f", + "zh:904acc31ebb9d6ef68c792074b30532ee61bf515f19e0a3c75b46f126cca1f13", + "zh:a1d0a81246afc8750286d3f6fe7a8fbe6460dd2662407b28dbfbabb612e5fa9d", + "zh:a41a36fe253fc365fe2b7ffc749624688b2693b4634862fda161179ab100029f", + "zh:a7ef269e77ffa8715c8945a2c14322c7ff159ea44c15f62505f3cbb2cae3b32d", + "zh:b01aa3bed30610633b762df64332b26f8844a68c3960cebcb30f04918efc67fe", + "zh:b069cc2cd18cae10757df3ae030508eac8d55de7e49eda7a5e3e11f2f7fe6455", + "zh:b2d2c6313729ebb7465dceece374049e2d08bda34473901be9ff46a8836d42b2", + "zh:db0e114edaf4bc2f3d4769958807c83022bfbc619a00bdf4c4bd17faa4ab2d8b", + "zh:ecc0aa8b9044f664fd2aaf8fa992d976578f78478980555b4b8f6148e8d1a5fe", + ] +} + +provider "registry.terraform.io/hashicorp/external" { + version = "2.4.0" + constraints = "~> 2.3" + hashes = [ + "h1:AmY6ZeIvqoTT5ZjzD+P49PeQH6Va1QLMkX+7MUQfYoA=", + "h1:K0eLC86zbhVoyS4THmY00KJZKAQORuz6dt9Ro3xo/wA=", + "h1:gXyK3ZkweDqkwEV9waEDWpljUY4yZXi/nRUSEuJn83k=", + "zh:0772afb42b658468ac5e15df33bf2080456f8f0b8ab163bfe9c50d2b2ea02135", + "zh:0ac31a9aaa43dfcff5944b791596cdc94e153348e4bb4642282d034dff548134", + "zh:32d8492b1bdcc956ca3c6d00c6392d0a83942ff11d4820c7ee63ca6796e06950", + "zh:3c0482e894429f528ce6655a76ab0d8a9f7c0dacc6c828865e1515d4a7dbb852", + "zh:61e68100b4db2f930b31491f23c602126382fd5e51252be1b551f0e17f8ddbee", + "zh:6d60f615a0ad85eb962c9eb94f25e3eba7a72684ce276ba5dfb23f36b295a8f8", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:9ced2745eb5f1346203027d2dd7bf856ad1d279a25730ff7dbc6eec187aaca0c", + "zh:a8378558a177d43f55aa0d79d4fae91a704695122a1b109668c1daa8fb76f09d", + "zh:aadd98086133d3ebea67437d56512fdcc6dfb3bd34dfc23f276c0db9272e27b4", + "zh:beff701b653841e70441978137768f54e7dc6c27e7bf12a4589087f01f5bbcee", + "zh:c91c2223b29fdbc0044d20e1936ccc051d010727a13f2ff1e75e51f09bff33a3", + "zh:d491f9c2d32a39dc4031628469ae7c8aec0074312a7c1f0286b173cdcf854a54", + ] +} diff --git a/infra/terraform/cloudflare-r2/terraform/main.tf b/infra/terraform/cloudflare-r2/terraform/main.tf index 2ab9706..600607b 100644 --- a/infra/terraform/cloudflare-r2/terraform/main.tf +++ b/infra/terraform/cloudflare-r2/terraform/main.tf @@ -18,7 +18,8 @@ terraform { } # Authenticates via the CLOUDFLARE_API_TOKEN env var (provider-native): the -# token is an orun-managed secret resolved into the job env at run time. +# token is an orun-managed secret resolved into the job env at run time — +# CLOUDFLARE_R2_TOKEN, minted from the r2-data template (component.yaml). provider "cloudflare" {} variable "cloudflare_account_id" { diff --git a/infra/terraform/supabase/component.yaml b/infra/terraform/supabase/component.yaml index bc48c71..cec8b75 100644 --- a/infra/terraform/supabase/component.yaml +++ b/infra/terraform/supabase/component.yaml @@ -26,8 +26,11 @@ spec: # parameters also prevents the param→TF_VAR loop from overriding the secret. supabaseRegion: ap-southeast-1 # SEC-JOB: post-apply, these outputs are queued on the runner's sink and - # lease-published onto the project/{{env}} rung by the runner. - secretOutputs: "SUPABASE_PROJECT_REF=project_ref,SUPABASE_DB_PASSWORD=database_password,SUPABASE_DB_URL=connection_uri,SUPABASE_URL=project_url,SUPABASE_ANON_KEY=anon_key,SUPABASE_SERVICE_ROLE_KEY=service_role_key,WIRING_SUPABASE=wiring" + # lease-published onto the project/{{env}} rung by the runner. Exactly + # what the tree reads (Lumen's three): cloudflare-hyperdrive takes the ref + # and the password, db-migrate all three. This app reaches Supabase only + # as Postgres, so no API key is published. + secretOutputs: "SUPABASE_PROJECT_REF=project_ref,SUPABASE_DB_PASSWORD=database_password,SUPABASE_DB_URL=connection_uri" # Both values resolve from orun secrets (project rung, brokered from the # Supabase integration): a short-lived Management-API access token minted diff --git a/infra/terraform/supabase/terraform/.terraform.lock.hcl b/infra/terraform/supabase/terraform/.terraform.lock.hcl new file mode 100644 index 0000000..5b4468d --- /dev/null +++ b/infra/terraform/supabase/terraform/.terraform.lock.hcl @@ -0,0 +1,73 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/external" { + version = "2.4.0" + constraints = "~> 2.3" + hashes = [ + "h1:AmY6ZeIvqoTT5ZjzD+P49PeQH6Va1QLMkX+7MUQfYoA=", + "h1:K0eLC86zbhVoyS4THmY00KJZKAQORuz6dt9Ro3xo/wA=", + "h1:gXyK3ZkweDqkwEV9waEDWpljUY4yZXi/nRUSEuJn83k=", + "zh:0772afb42b658468ac5e15df33bf2080456f8f0b8ab163bfe9c50d2b2ea02135", + "zh:0ac31a9aaa43dfcff5944b791596cdc94e153348e4bb4642282d034dff548134", + "zh:32d8492b1bdcc956ca3c6d00c6392d0a83942ff11d4820c7ee63ca6796e06950", + "zh:3c0482e894429f528ce6655a76ab0d8a9f7c0dacc6c828865e1515d4a7dbb852", + "zh:61e68100b4db2f930b31491f23c602126382fd5e51252be1b551f0e17f8ddbee", + "zh:6d60f615a0ad85eb962c9eb94f25e3eba7a72684ce276ba5dfb23f36b295a8f8", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:9ced2745eb5f1346203027d2dd7bf856ad1d279a25730ff7dbc6eec187aaca0c", + "zh:a8378558a177d43f55aa0d79d4fae91a704695122a1b109668c1daa8fb76f09d", + "zh:aadd98086133d3ebea67437d56512fdcc6dfb3bd34dfc23f276c0db9272e27b4", + "zh:beff701b653841e70441978137768f54e7dc6c27e7bf12a4589087f01f5bbcee", + "zh:c91c2223b29fdbc0044d20e1936ccc051d010727a13f2ff1e75e51f09bff33a3", + "zh:d491f9c2d32a39dc4031628469ae7c8aec0074312a7c1f0286b173cdcf854a54", + ] +} + +provider "registry.terraform.io/hashicorp/random" { + version = "3.9.0" + constraints = "~> 3.0" + hashes = [ + "h1:OO+IuvQJSPmWdN8AyyIEvPJbLvDQpgX/zbktoa9KsJE=", + "h1:UlBuNVuCGJ39tTv2c5gz2NRZnQbXfbIWbTzWcth5o74=", + "h1:lVDv+0AjDjrLfpmaJbWqUmIw/k3/AHXLc3N4m55SNdo=", + "zh:161ad0bd9a75768c82f53fb6e7172a9d8be2d4889b012645a34795031aaf1bf1", + "zh:19dc9a5b17729725ccfc4f45b0500af0ee5bc6b6b160c7adb8f2bf617d2c80ea", + "zh:269eda8fe42daa7974d5a34d166c3ba9defe80cde86c01e4dadcfdf2e1f05e5f", + "zh:373f7c65566f8f2cc7f45d698654feb9d988996957e1266a69ca00c52d6d16d0", + "zh:5599d16804c41c83009ec621b6d6b6f74e102f5827678a4750f8809055546b61", + "zh:583be0440469a22bff70dcfa56593b01566860b29607437264adb51060cf46fc", + "zh:5f211d8ec3f2e1f414870d9584bfe26e6995560ef81c748f8447a48164767398", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:7b547fd16216761ef86efc3ed516ac5ac0c5c42b7c7eb24a08cef2d93f69ed5e", + "zh:7e7c0679daf2a382151d05068c8c3f0dae6b7b7dccf818827b73dd08638df2ef", + "zh:8089dec888a8038b9b4fb23b3df7e1057293dbc5b60b42cc47ff690d69d4b61b", + "zh:c51f15a031edfd6f23ce8ced3446ca7f8d8d647e2499890d7d5d10d5016d7257", + "zh:c94784f005708890dc6895afd53636ec00ec1e430b15d41e5aebfb1d4b39bd04", + ] +} + +provider "registry.terraform.io/supabase/supabase" { + version = "1.5.1" + constraints = "~> 1.5.1" + hashes = [ + "h1:A4kqrLbrPeyfOXuk2eN8L15ue7JSRtkV/FhqFyY9Dzg=", + "h1:X1mvSyjaWyaJmhijgpsXMP7UMIE5kuwbq4wfjpfcxBA=", + "h1:rTxTmQ7IGlQNi5H1oS8e2+AgmiXeWM+jnJN5TNS69vU=", + "zh:1834f1cfbab811ca53eae9bdb6485032a674aef5d84fa7fe65342f72e50e3880", + "zh:1d53f3c0c6d82c50a7a29d658f77f3e44db0c0196714f0891ec2cadfdeb58764", + "zh:1f4dda08ccb39790f3c11fb6b4006827f09bfb8fb85082886eb46803f44b1722", + "zh:38dcad29e57c4d06374f4b557108d0877bb3ba628878c6648508110ff34f3d0f", + "zh:63782085e8da25d78de2a080072e7cc6a35c781c2bdb04f5ca46f65a6d6988d6", + "zh:79d7e5fe9d1571aa5357f98b97e3f12e61f68500e4270e855c1bc5e4cc772a56", + "zh:890df766e9b839623b1f0437355032a3c006226a6c200cd911e15ee1a9014e9f", + "zh:8c8560f8df33c087ab9133fc32b68c4c16c8c1bc32b546c91dc98c2b39f80c3a", + "zh:ab4189d0c843166a1b4eaefe817192c8cee954c441a3a86ef5118931ce0e9d71", + "zh:c9037e7cfadc468ac961786af7e3004c08196543416842746f95b929e6118fd6", + "zh:ca9546b9ca3a27634a6eb37e069e58a44a26fe8c3c6539a17dc4b628ad6e7ae0", + "zh:d0301164210ea4ed0567c9c1c751d1e250ab163a8b0edd8cf256d25d54e4d1e5", + "zh:f048d76cca0083a2b91bef304949d182b3395b3bc013cc8aa1505219538953a1", + "zh:f85b905aa8f049a8769bac933a56ae0ca9c5bb74a6c2376cf9ee4ac8ecf50126", + "zh:fd26c6f338bfab77b145e0755dc39d9873aec8219b3b53909da418250d013973", + ] +} diff --git a/infra/terraform/supabase/terraform/main.tf b/infra/terraform/supabase/terraform/main.tf index 036a49d..5fe85d7 100644 --- a/infra/terraform/supabase/terraform/main.tf +++ b/infra/terraform/supabase/terraform/main.tf @@ -164,35 +164,3 @@ output "connection_uri" { value = "postgresql://postgres:${random_password.db_password.result}@db.${supabase_project.this.id}.supabase.co:5432/postgres" sensitive = true } - -# --- API keys --- -# -# The starter talks to Supabase from the browser and from the Worker with the -# project URL and the publishable (anon) key; Row Level Security is what -# protects the data, the key is public by design. Both leave this module -# through the wiring document the app's deploy reads back. - -data "supabase_apikeys" "this" { - project_ref = supabase_project.this.id -} - -output "anon_key" { - description = "The publishable (anon) API key" - value = data.supabase_apikeys.this.anon_key - sensitive = true -} - -output "service_role_key" { - description = "The service-role key (server only; never shipped to a browser)" - value = data.supabase_apikeys.this.service_role_key - sensitive = true -} - -output "wiring" { - description = "Wiring document for the app's deploy-time configuration (pushed to orun secrets)" - value = jsonencode({ - supabase_url = "https://${supabase_project.this.id}.supabase.co" - supabase_anon_key = data.supabase_apikeys.this.anon_key - }) - sensitive = true -} diff --git a/intent.yaml b/intent.yaml index 4eb7c92..ca7da8e 100644 --- a/intent.yaml +++ b/intent.yaml @@ -3,7 +3,7 @@ kind: Intent metadata: name: ai-chatbot - description: Vercel's Next.js AI Chatbot (AI SDK, next-auth, Drizzle, attachments) on Cloudflare Workers + Static Assets with Supabase Postgres through Hyperdrive, R2 for attachments and the schema managed by Orun, on the Lumen baseline conventions + description: Vercel's Next.js AI Chatbot (AI SDK on Workers AI, next-auth, Drizzle, attachments) on Cloudflare Workers + Static Assets with Supabase Postgres through Hyperdrive, R2 for attachments and the schema managed by Orun, on the Lumen baseline conventions 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. 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 a shared install + # would save nothing anyway. 0.19.0 is also the release whose first deploy + # retries Cloudflare's 10007 race and whose smoke retries with 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 THIS REPOSITORY'S OWN. A product bootstrapped from it has no +# work tree 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 before the first landing. work: epics: specs/epics tasks: tasks @@ -114,6 +130,11 @@ environments: env: BASE_DOMAIN: ai-chatbot.example.com + # SITE_URL, set under an environment's `env:`, is the product's public + # origin for that environment's build — the Open Graph images are absolute + # links. Unset, the build uses the environment's workers.dev URL. Set it once + # a custom domain answers for the environment (README, "Custom domain"); the + # next deploy of apps/web picks it up. stage: description: Deployed on every merge to main, before prod. url: https://ai-chatbot-web-stage.your-workers-subdomain.workers.dev @@ -162,5 +183,5 @@ repo: docs: overview: README.md pages: - - { path: specs/epics/ai-chatbot/README.md, role: reference, title: The epic } - - { path: specs/epics/ai-chatbot/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/db/src/manifest.ts b/packages/db/src/manifest.ts index 12a8df3..bba88f3 100644 --- a/packages/db/src/manifest.ts +++ b/packages/db/src/manifest.ts @@ -26,5 +26,23 @@ export const manifest: MigrationManifest = { description: "The chatbot's schema, verbatim from upstream lib/db/migrations/0000_initial.sql: User, Chat, Message_v2, Vote_v2, Document, Suggestion, Stream", }, + { + id: "020_app_secrets", + context: "app", + path: "020_app_secrets/up.sql", + checksum: + "49fcb09dccfd4679a63a94fe9c975ee03167880ea2e9d6231e4195b59751ff02", + description: + "app_private.secrets, and the session key a fresh environment starts with (apps/web/lib/auth-secret.ts); lib/db/migrations/0001_app_secrets.sql is the same SQL for drizzle-kit", + }, + { + id: "030_row_level_security", + context: "app", + path: "030_row_level_security/up.sql", + checksum: + "7dfc6398290084f8e383ce0bed7b235716ffd745357d91012c5f5ea448b55096", + description: + "Row-level security, with no policies, on every table in public — closed to Supabase's Data API (anon, authenticated), open to the app, which owns them; refuses to run if the app's role would be locked out. lib/db/migrations/0002_row_level_security.sql is the same SQL for drizzle-kit", + }, ], }; diff --git a/packages/db/src/migrations/020_app_secrets/up.sql b/packages/db/src/migrations/020_app_secrets/up.sql new file mode 100644 index 0000000..d245db8 --- /dev/null +++ b/packages/db/src/migrations/020_app_secrets/up.sql @@ -0,0 +1,21 @@ +-- Values the app needs that no platform brokers and no owner has set yet, +-- generated inside the environment's own database (apps/web/lib/auth-secret.ts +-- reads them). Kept out of `public`, which Supabase's Data API exposes. +-- +-- Idempotent, as every migration here must be: the Supabase Management API +-- adapter sends each statement in autocommit mode. + +CREATE SCHEMA IF NOT EXISTS app_private; + +CREATE TABLE IF NOT EXISTS app_private.secrets ( + name TEXT PRIMARY KEY, + value TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- The session-signing key a fresh environment starts with: 64 hex characters +-- from two v4 UUIDs, which gen_random_uuid() draws from pg_strong_random. An +-- AUTH_SECRET Worker secret, once an owner sets one, takes precedence. +INSERT INTO app_private.secrets (name, value) +VALUES ('auth_secret', replace(gen_random_uuid()::text || gen_random_uuid()::text, '-', '')) +ON CONFLICT (name) DO NOTHING; diff --git a/packages/db/src/migrations/030_row_level_security/up.sql b/packages/db/src/migrations/030_row_level_security/up.sql new file mode 100644 index 0000000..1736276 --- /dev/null +++ b/packages/db/src/migrations/030_row_level_security/up.sql @@ -0,0 +1,47 @@ +-- Row-level security on every table in `public`, and no policies. +-- +-- Supabase's Data API (PostgREST) serves `public` to anyone holding the +-- project's anon key, which is public by Supabase's design. Upstream assumed +-- a private Postgres, so its tables — "User" with its password hashes, every +-- chat and message — had no RLS, and the Data API would hand them out. With +-- RLS enabled and no policy, `anon` and `authenticated` read and write +-- NOTHING through it. The app is not affected: it connects through Hyperdrive +-- as `postgres` (the cloudflare-hyperdrive root's database_user), which +-- created and owns these tables, and a table's owner is not subject to its +-- RLS unless FORCE is set (it is not). The migration ledgers (`_migrations`, +-- drizzle-kit's `drizzle`) and `app_private` are schemas the Data API does +-- not expose. +-- +-- apps/web/lib/db/schema.ts declares `.enableRLS()` on each table (its +-- drizzle-kit twin is apps/web/lib/db/migrations/0002_row_level_security.sql); +-- tests/db fails if any table in `public` is left without RLS after the +-- migrations. +-- +-- FIRST, the guard. If `postgres` neither owns every table here nor has +-- SUPERUSER or BYPASSRLS, enabling RLS would lock the app out of its own +-- data: stop. The guard changes nothing and runs before the first ALTER, so +-- a refusal enables nothing. Idempotent: ENABLE on an enabled table is a +-- no-op. +DO $$ +DECLARE + app_bypasses boolean; + not_owned text; +BEGIN + SELECT rolsuper OR rolbypassrls INTO app_bypasses FROM pg_roles WHERE rolname = 'postgres'; + SELECT string_agg(c.relname, ', ' ORDER BY c.relname) INTO not_owned + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') + AND pg_get_userbyid(c.relowner) <> 'postgres'; + IF NOT coalesce(app_bypasses, false) AND not_owned IS NOT NULL THEN + RAISE EXCEPTION 'row-level security would lock the app out of %: postgres (the role Hyperdrive connects as) neither owns them nor has SUPERUSER or BYPASSRLS', not_owned; + END IF; +END +$$; + +ALTER TABLE "Chat" ENABLE ROW LEVEL SECURITY; +ALTER TABLE "Document" ENABLE ROW LEVEL SECURITY; +ALTER TABLE "Message_v2" ENABLE ROW LEVEL SECURITY; +ALTER TABLE "Stream" ENABLE ROW LEVEL SECURITY; +ALTER TABLE "Suggestion" ENABLE ROW LEVEL SECURITY; +ALTER TABLE "User" ENABLE ROW LEVEL SECURITY; +ALTER TABLE "Vote_v2" ENABLE ROW LEVEL SECURITY; diff --git a/packages/db/src/runner/supabase-api-adapter.ts b/packages/db/src/runner/supabase-api-adapter.ts index ba30da9..e7e400c 100644 --- a/packages/db/src/runner/supabase-api-adapter.ts +++ b/packages/db/src/runner/supabase-api-adapter.ts @@ -1,7 +1,10 @@ import type { MigrationEntry } from "../types.js"; import type { AppliedMigration, MigrationAdapter } from "./types.js"; -const SUPABASE_API_BASE = "https://api.supabase.com"; +// The Management API's origin. SUPABASE_API_URL overrides it so a test can +// put a local Postgres behind a stand-in for the one endpoint used here; a +// deployment never sets it. +const SUPABASE_API_BASE = (process.env["SUPABASE_API_URL"] ?? "https://api.supabase.com").replace(/\/+$/, ""); export class SupabaseApiAdapter implements MigrationAdapter { private projectRef: string; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f285e90..cf73bc1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4,6 +4,9 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false +overrides: + '@electric-sql/pglite': 0.5.8 + importers: .: @@ -94,7 +97,7 @@ importers: version: 17.4.2 drizzle-orm: specifier: ^0.45.2 - version: 0.45.4(@cloudflare/workers-types@5.20261014.1)(postgres@3.4.9) + version: 0.45.4(@cloudflare/workers-types@5.20261014.1)(@electric-sql/pglite@0.5.8)(postgres@3.4.9) fast-deep-equal: specifier: ^3.1.3 version: 3.1.3 @@ -200,6 +203,9 @@ importers: usehooks-ts: specifier: ^3.1.1 version: 3.1.1(react@19.2.7) + workers-ai-provider: + specifier: 4.0.0 + version: 4.0.0(@ai-sdk/provider@4.0.2)(ai@7.0.15(zod@4.6.7)) zod: specifier: ^4.4.3 version: 4.6.7 @@ -279,6 +285,9 @@ importers: '@app/tsconfig': specifier: workspace:* version: link:../../tooling/tsconfig + '@electric-sql/pglite': + specifier: 0.5.8 + version: 0.5.8 '@saas/db': specifier: workspace:* version: link:../../packages/db @@ -303,6 +312,9 @@ importers: '@types/node': specifier: ^22.9.0 version: 22.20.5 + ai: + specifier: 7.0.15 + version: 7.0.15(zod@4.6.7) clsx: specifier: ^2.1.1 version: 2.1.1 @@ -312,6 +324,9 @@ importers: next: specifier: 16.3.8 version: 16.3.8(@playwright/test@1.64.1)(@types/node@22.20.5)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + next-auth: + specifier: 5.0.0-beta.25 + version: 5.0.0-beta.25(next@16.3.8(@playwright/test@1.64.1)(@types/node@22.20.5)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) react: specifier: 19.2.7 version: 19.2.7 @@ -813,6 +828,9 @@ packages: '@drizzle-team/brocli@0.10.2': resolution: {integrity: sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w==} + '@electric-sql/pglite@0.5.8': + resolution: {integrity: sha512-n9tsbUOhwx2epK1V0ZG9Ar4SHWUju04dhmzZXiSBXwBoleOvIfals33NAaWgagQVAL4Rbvx/Ptsu3P+pA09f6Q==} + '@emnapi/runtime@1.11.3': resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} @@ -3658,7 +3676,7 @@ packages: peerDependencies: '@aws-sdk/client-rds-data': '>=3' '@cloudflare/workers-types': '>=4' - '@electric-sql/pglite': '>=0.2.0' + '@electric-sql/pglite': 0.5.8 '@libsql/client': '>=0.10.0' '@libsql/client-wasm': '>=0.10.0' '@neondatabase/serverless': '>=0.10.0' @@ -5810,6 +5828,22 @@ packages: engines: {node: '>=16'} hasBin: true + workers-ai-provider@4.0.0: + resolution: {integrity: sha512-FkhwMP1EP/MKXR8Jv1o7wLVKfTqu0h/PUaEmhZ7gyDiioib5Wsh3oPAKhG+7+SWfU3roTDHaEWlJpkJjpXu+fQ==} + peerDependencies: + '@ai-sdk/anthropic': ^4.0.0 + '@ai-sdk/google': ^4.0.0 + '@ai-sdk/openai': ^4.0.0 + '@ai-sdk/provider': ^4.0.0 + ai: ^7.0.0 + peerDependenciesMeta: + '@ai-sdk/anthropic': + optional: true + '@ai-sdk/google': + optional: true + '@ai-sdk/openai': + optional: true + wrangler@4.151.0: resolution: {integrity: sha512-ra8MpzSR+ClkbGofu9S+AmAKjytS60MqSuayXKpa1CAYIzP+NIc8q6EiF55Gz5PS3lxT4qcvMuPHihCNhTPpDg==} engines: {node: '>=22.0.0'} @@ -6702,6 +6736,8 @@ snapshots: '@drizzle-team/brocli@0.10.2': {} + '@electric-sql/pglite@0.5.8': {} + '@emnapi/runtime@1.11.3': dependencies: tslib: 2.8.1 @@ -9387,9 +9423,10 @@ snapshots: esbuild: 0.25.12 tsx: 4.23.15 - drizzle-orm@0.45.4(@cloudflare/workers-types@5.20261014.1)(postgres@3.4.9): + drizzle-orm@0.45.4(@cloudflare/workers-types@5.20261014.1)(@electric-sql/pglite@0.5.8)(postgres@3.4.9): optionalDependencies: '@cloudflare/workers-types': 5.20261014.1 + '@electric-sql/pglite': 0.5.8 postgres: 3.4.9 dunder-proto@1.0.1: @@ -10790,6 +10827,12 @@ snapshots: dependencies: content-type: 2.1.0 + next-auth@5.0.0-beta.25(next@16.3.8(@playwright/test@1.64.1)(@types/node@22.20.5)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7): + dependencies: + '@auth/core': 0.37.2 + next: 16.3.8(@playwright/test@1.64.1)(@types/node@22.20.5)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + react: 19.2.7 + next-auth@5.0.0-beta.25(next@16.3.8(@playwright/test@1.64.1)(@types/node@24.19.2)(babel-plugin-react-compiler@1.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7): dependencies: '@auth/core': 0.37.2 @@ -12062,6 +12105,11 @@ snapshots: '@cloudflare/workerd-linux-arm64': 1.20261012.1 '@cloudflare/workerd-windows-64': 1.20261012.1 + workers-ai-provider@4.0.0(@ai-sdk/provider@4.0.2)(ai@7.0.15(zod@4.6.7)): + dependencies: + '@ai-sdk/provider': 4.0.2 + ai: 7.0.15(zod@4.6.7) + wrangler@4.151.0(@cloudflare/workers-types@5.20261014.1)(@types/node@24.19.2): dependencies: '@cloudflare/kv-asset-handler': 0.5.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 939c4e9..98f243c 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -10,3 +10,10 @@ onlyBuiltDependencies: - esbuild - workerd - sharp + +# tests/db runs the migrations in PGlite (Postgres compiled to WASM), and +# drizzle-orm lists PGlite as an optional peer. One version for both, pinned: +# the app never imports it, and an optional peer must not float to whatever +# was published yesterday. +overrides: + "@electric-sql/pglite": "0.5.8" diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml new file mode 100644 index 0000000..c5bb351 --- /dev/null +++ b/repo-blueprint.yaml @@ -0,0 +1,735 @@ +apiVersion: orun.dev/v1 +kind: Blueprint +metadata: + name: ai-chatbot + description: >- + The ai-chatbot as a Blueprint of itself — instantiate a new chatbot + product repository (Vercel's Next.js AI Chatbot on Cloudflare Workers + + Static Assets, its models on Workers AI through the Worker's AI binding, + its Postgres a Supabase project behind Cloudflare Hyperdrive, its + attachments in an R2 bucket, the schema applied by db-migrate) and take it + from nothing to live on stage and prod in ONE landing, then record what + went live. Run one phase at a + time with `--phase <name>` or both 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-chat) — intent metadata.name, the Worker name + prefix, the secret project, and the `repo` the Supabase project, the + Hyperdrive config and the R2 bucket are named after. + productname: + type: string + required: true + description: The product's display name (e.g. "Acme Chat") — in every page title and the sidebar. + productdomain: + type: string + required: true + description: >- + The domain the product will answer on (e.g. acme.dev) — BASE_DOMAIN and + the custom-domain guidance. It does not need to exist: the app 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 product's repository is created under. 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 app 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 product'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: chatbot-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 state, 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/.dev.vars` 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 + - node_modules + - .orun + - .terraform + - plan.json + - "**/*.tsbuildinfo" + - "**/next-env.d.ts" + - "**/*.tfstate" + - "**/*.tfstate.backup" + # `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` and `.dev.vars.example` are not among them, + # and ship — which is why this names `.dev.vars` and `.dev.vars.local` + # rather than `.dev.vars.*`. + - "**/.env" + - "**/.env.local" + - "**/.env.*.local" + - "**/.dev.vars" + - "**/.dev.vars.local" + # THE FACTORY'S OWN LANES. `github-workflows` copies the whole of `.github`, + # so without these two entries every product built from this baseline would + # carry them — `baseline.yml` runs `testing/*.sh`, which no module places, + # and `tag.yml` cuts baseline tags a product 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, .baseline/) can ship by accident. testing/leak.test.sh holds +# that line. +# +# Every module lands in ONE phase (01-product). `dependsOn` here orders the +# placement only — what has to exist before what is written — and mirrors the +# components' own graph; the DEPLOY order is the components' `dependsOn`, +# which the product's own plan enforces on main. +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 + - 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 PRODUCT's README, not this repository's: this one is about the + # baseline (how to instantiate it, how it is tested), and a product'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 product 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 + + # ── shared tooling ─────────────────────────────────────────────────────── + # Only what a PRODUCT runs: the TypeScript and ESLint configuration, the + # deploy-time wrangler renderer, and the migration-manifest checker + # packages/db's scripts call. 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 + - name: tooling-migrations + mode: copy + source: baseline + from: tooling/migrations + to: tooling/migrations + + # ── the data plane ─────────────────────────────────────────────────────── + # The Lumen roots: a Supabase project per environment, a Hyperdrive config + # over its database, and the migrations, applied after the project exists — + # and the R2 bucket the attachments live in. + - name: db + mode: copy + source: baseline + from: packages/db + to: packages/db + dependsOn: [tooling-eslint, tooling-migrations, tooling-tsconfig] + - name: supabase + mode: copy + source: baseline + from: infra/terraform/supabase + to: infra/terraform/supabase + - name: cloudflare-hyperdrive + mode: copy + source: baseline + from: infra/terraform/cloudflare-hyperdrive + to: infra/terraform/cloudflare-hyperdrive + dependsOn: [supabase] + - name: db-migrate + mode: copy + source: baseline + from: infra/db-migrate + to: infra/db-migrate + dependsOn: [cloudflare-hyperdrive, db, supabase] + - name: cloudflare-r2 + mode: copy + source: baseline + from: infra/terraform/cloudflare-r2 + to: infra/terraform/cloudflare-r2 + + # ── the app ────────────────────────────────────────────────────────────── + - name: web + mode: copy + source: baseline + from: apps/web + to: apps/web + dependsOn: [cloudflare-hyperdrive, cloudflare-r2, db-migrate, tooling-eslint, tooling-tsconfig, tooling-wire] + + # ── the tests ──────────────────────────────────────────────────────────── + - name: db-tests + mode: copy + source: baseline + from: tests/db + to: tests/db + dependsOn: [db, tooling-eslint, tooling-tsconfig] + - name: web-tests + mode: copy + source: baseline + from: tests/web + to: tests/web + dependsOn: [tooling-eslint, tooling-tsconfig, tooling-wire, web] + +# ── THE WORK, UP FRONT ──────────────────────────────────────────────────── +# The bootstrap is work, so it lives where work lives — and all of it is on +# the plane before the first phase places a file: one epic, one milestone per +# phase in the order the phases run, one task per landing. +# +# `hooks.preInstantiate` (orun >= v2.60) runs under no phase, once per run, on +# a resume too. Everything here is find-or-create BY IDENTITY — the epic by +# slug, a milestone by name within its epic, a task by title within its epic — +# so a second run, a resume and a redo all find what the first run made. The +# milestones are created IN ORDER and BEFORE the tasks: the plane appends each +# new milestone after the last, and a task naming a milestone the epic does +# not have yet would create it out of order. +# +# 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. (Under an orun older than v2.60, which has +# no run-level list, that hook is what creates the task — same identity, same +# result, one phase late.) +hooks: + preInstantiate: + - id: epic + uses: orun.task/ensure@v1 + with: + kind: epic + slug: "{{ .inputs.epicSlug }}" + name: "Chatbot baselining — {{ .inputs.productname }}" + description: >- + Everything the ai-chatbot baseline builds for + {{ .inputs.productname }} in {{ .inputs.githuborg }}/{{ .inputs.reponame }}: + the repository and its CI, the Supabase project, the Hyperdrive + config and the R2 bucket per environment, the schema, the chatbot + live on stage and prod, and 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 whole product merged + - Supabase, Hyperdrive and the migrations applied, the R2 bucket created, and the app deployed, on stage and prod — infra before app + - /ping and /api/health answer on both workers.dev URLs + - 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, and dev verifies every merge to main 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 one pull request, branded as + {{ .inputs.productname }}: the intent, CI and tooling, the Supabase, + Hyperdrive and R2 Terraform roots, the migrations and the app. The + convergence that merge triggers provisions, migrates and deploys it, + infra before app, on stage and prod. + 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 — which model + provider is serving included — 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. +# +# TWO PHASES, ONE LANDING THAT DEPLOYS. Everything the product is made of — +# root files, workflows, tooling, the Terraform roots, the migrations, the app +# and its tests — lands as ONE pull request, and ONE convergence on main +# provisions and deploys it. The order the infrastructure needs is not a +# sequence of landings: it is the components' own `dependsOn`, each edge +# `mode: enforced` on a push to main — supabase → cloudflare-hyperdrive → +# db-migrate → web per environment, with cloudflare-r2 → web beside it. A job +# resolves its secrets when it starts, so each one finds what the apply +# before it lease-published. +# `02-docs` places nothing: it records the deployment and puts back what +# 01-product deferred. +phases: + - name: 01-product + title: The product, built in one landing + description: The whole tree — manifests, CI, tooling, the Supabase, Hyperdrive and R2 roots, the migrations, the app and its tests — branded, landed as one pull request, and provisioned and deployed by one convergence. + expectedMinutes: 18 + narrate: + start: "Creating the repository and landing the whole product in one pull request — the chatbot, its migrations, and the Terraform for a Supabase project, a Hyperdrive config and an R2 bucket per environment. Then one convergence provisions and deploys it in order. Usually about {{ .meta.expectedMinutes }} minutes." + await: "One convergence is running per environment: the Supabase project first (five to seven minutes to come up), then Hyperdrive over its database, then the migrations, then the app — with the R2 bucket created beside them. Nothing is stuck." + done: "{{ .inputs.reponame }} is live on stage and prod — {{ .meta.files }} files on main, branded as {{ .inputs.productname }}, chatting on Workers AI with its database reachable through Hyperdrive. That took {{ .meta.elapsed }}." + failed: "The product did not come up. The failing lane above names the component — supabase, cloudflare-hyperdrive, cloudflare-r2, db-migrate or web — and the provider's own error is in its log; whatever was provisioned is still there." + modules: [ai-deployment, ai-operations, cloudflare-hyperdrive, cloudflare-r2, db, db-migrate, db-tests, 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, supabase, tooling-eslint, tooling-migrations, 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 — + # with the Cloudflare and Supabase connections every credential below is + # minted from, since this is the phase that provisions and deploys. + requires: + probe: + - id: providers + uses: orun.doctor/check@v1 + with: + providers: [github, cloudflare, supabase] + githubOwner: "{{ .inputs.githuborg }}" + waitSeconds: 600 + pollSeconds: 20 + hooks: + pre: + # The epic, every milestone and every task 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 + 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 on main; + # orun derives phase state from the tree, so a forced re-run lands an + # EMPTY diff while the product's CI plans `--changed`. retouch.mjs + # rewrites ONE trailing marker line — `# orun: redeploy <phase> + # <stamp>` — in each component.yaml the task contract names, so the + # landing has a diff and exactly those components re-plan. A deploy + # trigger, not state: nothing reads it back. + - id: retouch + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/retouch.mjs", "--phase", "{{ .phase.name }}", "--affects", "{{ .baseline.dir }}/.baseline/tasks/01-product.TaskContract.yaml"] + # The identity chain. rebrand.mjs enumerates the tree with + # `git ls-files`, so the output has to be a git repository with a + # populated index BEFORE it runs. `git add -A` only stages; the + # landing commits. + - 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 product. rebrand.mjs treats the orun state backend as + # org-owned and leaves it alone, so intent.yaml would keep THIS + # repository's `workspace:` — the product'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 product 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 product 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 whole chain (Supabase, + # Hyperdrive, R2, migrations, the app); during a bootstrap both are empty + # and the convergence is watched to green, so it protects nothing and + # doubles the wall-clock. 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 and both test packages on the + # merge prove 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 placed the baseline's complete lockfile and the whole + # tree is here, so this only confirms it — the Checks and every lane + # install with --frozen-lockfile. + - 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 product'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 provider credentials, brokered, one hook per template: + # `integrations/reconcile` mints from ONE connection with ONE scope + # template, and these six keys are six scopes on purpose — the + # deploy token deliberately cannot touch Hyperdrive or R2. Keys that + # already exist are kept. After the link, before the landing whose + # convergence uses them: + # CLOUDFLARE_API_TOKEN web's deploy (the composition's binding) + # CLOUDFLARE_HYPERDRIVE_TOKEN cloudflare-hyperdrive's provider + # CLOUDFLARE_R2_TOKEN cloudflare-r2's provider (r2-data) + # CLOUDFLARE_ACCOUNT_ID web's deploy, cloudflare-hyperdrive, cloudflare-r2 + # SUPABASE_ACCESS_TOKEN supabase's provider, db-migrate's runner + # SUPABASE_ORG_ID supabase (TF_VAR_supabaseOrgId) + # No model key is minted: the chat runs on Workers AI through the + # Worker's own AI binding, which needs none. The AI Gateway's key is + # optional and no connection brokers it (its README, "Models"). + - id: secret-workers-deploy + uses: orun.integrations/reconcile@v1 + with: + provider: cloudflare + keys: [CLOUDFLARE_API_TOKEN] + template: workers-deploy + - id: secret-hyperdrive-edit + uses: orun.integrations/reconcile@v1 + with: + provider: cloudflare + keys: [CLOUDFLARE_HYPERDRIVE_TOKEN] + template: hyperdrive-edit + - id: secret-r2-data + uses: orun.integrations/reconcile@v1 + with: + provider: cloudflare + keys: [CLOUDFLARE_R2_TOKEN] + template: r2-data + - id: secret-account-id + uses: orun.integrations/reconcile@v1 + with: + provider: cloudflare + keys: [CLOUDFLARE_ACCOUNT_ID] + template: account-id + - id: secret-supabase-access + uses: orun.integrations/reconcile@v1 + with: + provider: supabase + keys: [SUPABASE_ACCESS_TOKEN] + template: management-access + - id: secret-supabase-org + uses: orun.integrations/reconcile@v1 + with: + provider: supabase + keys: [SUPABASE_ORG_ID] + template: org-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, 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 + # the convergence after the merge is what this phase watches to green. + - 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 ai-chatbot baseline" + await: + - id: converge + uses: orun.run/watch@v1 + narrate: "Supabase, Hyperdrive, R2, the migrations and the app went out on stage and prod, infra before app, and the convergence run came back green." + with: + # The run for the commit THIS landing merged (an unpinned watch + # reads the previous push's run). The budget is roughly three + # times expectedMinutes: a Supabase project can take ten minutes + # on a busy region, and there is room for one resume. + sha: "{{ .phase.hooks.land.outputs.mergeSha }}" + repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" + resumeBudget: 3 + waitSeconds: 3600 + # WHERE THE OUTPUTS ARE PUBLISHED: each apply lease-publishes its + # outputs to the project's ENVIRONMENT rungs (stage and prod), not to + # the workspace. The Supabase project's three, which Hyperdrive and + # db-migrate read, and the Hyperdrive and R2 wiring the app's deploy + # renders. + - id: wiring + uses: orun.secrets/exists@v1 + narrate: "The Supabase credentials and the Hyperdrive and R2 wiring are published on stage and prod." + with: + keys: [SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD, SUPABASE_DB_URL, WIRING_CLOUDFLARE_HYPERDRIVE, WIRING_CLOUDFLARE_R2] + project: "{{ .inputs.reponame }}" + environments: [stage, prod] + - id: verify + uses: orun.http/probe@v1 + narrate: "The Worker and its database check answered on stage and prod." + with: + urls: + - "https://{{ .inputs.reponame }}-web-stage.{{ .inputs.subdomain }}.workers.dev/ping" + - "https://{{ .inputs.reponame }}-web-stage.{{ .inputs.subdomain }}.workers.dev/api/health" + - "https://{{ .inputs.reponame }}-web-prod.{{ .inputs.subdomain }}.workers.dev/ping" + - "https://{{ .inputs.reponame }}-web-prod.{{ .inputs.subdomain }}.workers.dev/api/health" + + # 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, noting which model provider is serving, 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 product 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 PRODUCT 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/ping" + - "https://{{ .inputs.reponame }}-web-stage.{{ .inputs.subdomain }}.workers.dev/api/health" + - "https://{{ .inputs.reponame }}-web-prod.{{ .inputs.subdomain }}.workers.dev/ping" + - "https://{{ .inputs.reponame }}-web-prod.{{ .inputs.subdomain }}.workers.dev/api/health" diff --git a/specs/epics/README.md b/specs/epics/README.md index 4936a74..5386ab9 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 | |------|---------|--------|------------| -| [`ai-chatbot/`](./ai-chatbot/) | **AC** | ✅ Shipped | Vercel's Next.js AI Chatbot, equivalent in code and function, on Cloudflare Workers with Supabase Postgres, Hyperdrive and R2 | +| [`ai-chatbot/`](./ai-chatbot/) | **AC** | 🔄 AC5 in review | Vercel's Next.js AI Chatbot, equivalent in code and function, on Cloudflare Workers with Supabase Postgres, Hyperdrive and R2 — and an Orun baseline that instantiates it in one landing, chatting on Workers AI (AC5) | As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`. diff --git a/specs/epics/ai-chatbot/IMPLEMENTATION-STATUS.md b/specs/epics/ai-chatbot/IMPLEMENTATION-STATUS.md index 4adcb5b..915c8a4 100644 --- a/specs/epics/ai-chatbot/IMPLEMENTATION-STATUS.md +++ b/specs/epics/ai-chatbot/IMPLEMENTATION-STATUS.md @@ -1,135 +1,159 @@ -# rag-chatbot (RG) — Implementation status +# ai-chatbot (AC) — Implementation status As-built ≠ intent. This file records what actually shipped, and every place the code departed from `design.md` or from the upstream template. +> Rewritten in AC5. The copy AC4 merged (#5) carried another epic's status +> file by mistake (rag-chatbot's, "RG"); its own milestones, departures and +> verification are restored here from the PRs, the risks register and the +> code. + | Milestone | State | PR | |---|---|---| -| RG0 — the spec | ✅ Shipped | [#1](https://github.com/sourceplane/rag-chatbot/pull/1) | -| RG1 — the chatbot on Workers | ✅ Shipped | [#2](https://github.com/sourceplane/rag-chatbot/pull/2) | -| RG2 — the schema through db-migrate | ✅ Shipped (planned offline; apply gated on a linked workspace) | [#3](https://github.com/sourceplane/rag-chatbot/pull/3) | -| RG3 — Supabase and Hyperdrive from Terraform | ✅ Shipped (validated; apply gated on a linked workspace) | [#4](https://github.com/sourceplane/rag-chatbot/pull/4) | -| RG4 — ready to instantiate | ✅ Shipped | [#5](https://github.com/sourceplane/rag-chatbot/pull/5) | - -## Departures from the upstream template - -### `getDb()` in place of the module-level `db` (forced by the Workers runtime) - -Upstream's `lib/db/index.ts` is `const client = postgres(env.DATABASE_URL!); -export const db = drizzle(client);`. On Workers a `postgres` socket opened in -one request cannot be used by another, and the connection string is the -`HYPERDRIVE` binding's, not an env var. The file now exports an async -`getDb()` that builds `postgres(connectionString, { max: 5, fetch_types: -false, prepare: false })` + drizzle per call, the connection string from -`getCloudflareContext({ async: true }).env.HYPERDRIVE.connectionString` -when a Cloudflare context exists and `env.DATABASE_URL` otherwise (throwing -when neither is set). The two callers changed by one line each: -`lib/actions/resources.ts` (`const db = await getDb()` after the schema -parse) and `lib/ai/embedding.ts` (`findRelevantContent`, after the query -embedding). The schema, the queries, the cosine-distance SQL and the chat -route are as written. - -### `DATABASE_URL` optional (`lib/env.mjs`), `drizzle.config.ts` reads `env.DATABASE_URL ?? ""` - -t3-env validated `DATABASE_URL: z.string().min(1)` at import; the Worker has -no `DATABASE_URL` (the database is the binding), so it is -`z.string().optional()`. That makes it `string | undefined` for drizzle-kit's -config, which now reads `env.DATABASE_URL ?? ""`. t3-env's `createEnv` runs -unchanged at module load on the Worker and validates with nothing set -(`NODE_ENV` is defaulted); `dotenv.config({ path: ".env.local" })` finds no -file there and returns silently — verified under `wrangler dev`. - -### drizzle's migrator leaves the build script - -`"build": "tsx lib/db/migrate.ts && next build"` became `next build && -opennextjs-cloudflare build --skipBuild --skipWranglerConfigCheck && -opennextjs-cloudflare populateCache local`. The schema is applied by -`infra/db-migrate` from `packages/db` before the Worker deploys; -`lib/db/migrate.ts` stays as `pnpm --filter @app/web db:migrate` for a local -Postgres, and drizzle-kit (`db:generate`, `db:push`, `db:studio`, …) and -`lib/db/migrations` stay for development. - -### eslint-config-next 16 flat config - -The template's `.eslintrc.json` (`extends: next/core-web-vitals`) and `next -lint` have no Next 16 equivalent. `eslint.config.mjs` is what -`create-next-app` writes for Next 16 (`defineConfig`, `core-web-vitals`, -`typescript`), with two rules off rather than the template rewritten: -`react-hooks/set-state-in-effect` (new in 16; flags the page's -`setIsExpanded` and `setShowLoading` effects) and -`@typescript-eslint/no-empty-object-type` (shadcn's `InputProps extends -React.InputHTMLAttributes<HTMLInputElement> {}` in `components/ui/input.tsx`). -The `lint` script is `eslint .`. - -### `tailwind.config.ts` imports, not requires - -`require("tailwindcss/defaultTheme")`, `require("tailwindcss-animate")` and -`module.exports` — which the TypeScript ESLint rules reject — are `import`s -and `export default`. That leaves one `import/no-anonymous-default-export` -warning (0 errors); it is kept rather than restructuring the template's -config object. - -### `tsconfig.json` rewritten by Next 16; `cloudflare-env.d.ts` added - -`next build` set `jsx` to `react-jsx` and added `.next/dev/types/**/*.ts` -to `include` (Next 16's mandatory change). `cloudflare-env.d.ts` declares -`HYPERDRIVE: Hyperdrive` and `ASSETS: Fetcher` on the `CloudflareEnv` -interface `@opennextjs/cloudflare` types `env` with, over -`@cloudflare/workers-types`. - -### Not departures, for the record - -- `packages/db/src/migrations/010_rag_initial/up.sql` is byte-for-byte - upstream's `lib/db/migrations/0000_yielding_bloodaxe.sql`, including - `CREATE EXTENSION IF NOT EXISTS vector` and drizzle-kit's - `--> statement-breakpoint` comment lines (the runner posts the file whole; - they are SQL comments). -- The chat route, its tools and system prompt, the page, the components and - the styles are unchanged. `export const maxDuration = 30` remains and is - inert on Workers. -- The AI Gateway is used exactly as upstream (model strings, one key); the - key is a Worker secret instead of a project env var. - -### Versions - -| Package | Version | Why | -|---|---|---| -| next, eslint-config-next | 16.3.8 | upstream 15.5.7; newest inside `@opennextjs/cloudflare` 1.20.11's range (16.4.x fails at Worker boot) | -| react, react-dom | ^19.2.1 | Next 16.3's peer; upstream ^19.0.0 | -| @opennextjs/cloudflare | ^1.20.11 | the adapter; static-assets incremental cache + `populateCache local` | -| wrangler | ^4.151.0 | dev and deploy | -| @cloudflare/workers-types | ^5.20261006.1 | wrangler 4.151's peer; `Hyperdrive`, `Fetcher` | -| eslint, typescript | ^9.27.0, ^5.8.3 | flat config; upstream ^9.16.0, ^5.7.2 | -| ai, @ai-sdk/react, drizzle-orm, drizzle-zod, postgres, zod, @t3-oss/env-nextjs, streamdown, framer-motion, nanoid, sonner, tailwindcss, tailwind-merge | upstream's ranges | unchanged (`@t3-oss/env-nextjs` 0.11.1 warns about zod 4's peer, as it did upstream) | +| AC0 — the spec | ✅ Shipped | [#1](https://github.com/sourceplane/ai-chatbot/pull/1) | +| AC1 — the chatbot on Workers | ✅ Shipped | [#2](https://github.com/sourceplane/ai-chatbot/pull/2) | +| AC2 — the schema through db-migrate | ✅ Shipped (planned offline; apply gated on a linked workspace) | [#3](https://github.com/sourceplane/ai-chatbot/pull/3) | +| AC3 — Supabase, Hyperdrive and R2 from Terraform | ✅ Shipped (validated; apply gated on a linked workspace) | [#4](https://github.com/sourceplane/ai-chatbot/pull/4) | +| AC4 — ready to instantiate | ✅ Shipped | [#5](https://github.com/sourceplane/ai-chatbot/pull/5) | +| AC5 — a baseline | 🔄 In review | this PR | + +## Departures from the upstream template (AC1–AC4) + +### `getDb()` in place of the module-level client (forced by the Workers runtime) + +Upstream opened one `postgres(process.env.POSTGRES_URL)` client at module +scope in `lib/db/queries.ts`. On Workers a socket opened in one request +cannot be used by another, and the connection string is the `HYPERDRIVE` +binding's. `getDb()` builds `postgres(connectionString, { max: 5, +fetch_types: false, prepare: false })` + drizzle per call, from +`getCloudflareContext({ async: true }).env.HYPERDRIVE` when a Cloudflare +context exists and `POSTGRES_URL` otherwise. Every query body is upstream's +(risk AC-A). + +### The schema from `packages/db`, applied by db-migrate + +`tsx lib/db/migrate` left the build script, which is `next build && +opennextjs-cloudflare build` (and, since AC5, the static-assets cache copy). +The SQL is upstream's `0000_initial.sql`, verbatim, as `010_initial` in +`packages/db`, applied per environment by `infra/db-migrate`; drizzle-kit +stays for local databases. + +### Attachments in R2, public by unguessable URL + +Vercel Blob's `put(…, { access: "public" })` became a put into the `BLOB` R2 +binding under `<uuid>/<name>`, answered in Blob's response shape; the Worker +serves objects back at `/api/files/<key>` without a session, as Blob's +public URLs were (the model provider and `next/image` fetch them without the +cookie — risk AC-B). + +### The Vercel-only modules + +| Upstream | Here | +|---|---| +| BotID (`checkBotId`, `withBotId`, `initBotId`) | `lib/bot.ts` never flags a request; bot handling is a Cloudflare zone setting or Turnstile (AC-G) | +| `@vercel/functions` `geolocation` / `ipAddress` | `lib/geo.ts`: `request.cf` and `cf-connecting-ip`, same return shape | +| `@vercel/otel` + `@ai-sdk/otel` | Workers observability; `instrumentation.ts` registers nothing | +| `@vercel/analytics` | the Cloudflare Web Analytics beacon, rendered only with `NEXT_PUBLIC_CF_BEACON_TOKEN` | +| Redis resumable streams + IP rate limit | off without `REDIS_URL`, as upstream; per-user entitlements apply (AC-D) | + +### Build, lint and versions + +The template's biome/ultracite is the app's lint; eslint lints the +packages. `next.config.ts` adds `output: "standalone"` and the monorepo +tracing root for OpenNext; `open-next.config.ts` uses the static-assets +incremental cache (AC-C). Five dependencies are pinned to the versions +upstream's lockfile resolved (`streamdown`, `@streamdown/code`, `shiki`, +`@ai-sdk/provider`, …) because floating ranges broke `tsc` in upstream's own +files (AC-E). + +## Departures added by AC5 (a baseline) + +### Workers AI is the default model provider; the gateway is optional + +Upstream sends every model call through the Vercel AI Gateway, which needs a +key no platform brokers. `lib/ai/providers.ts` now runs the Workers AI +models through the Worker's `AI` binding with `workers-ai-provider` 4.0.0 — +the chat (`@cf/moonshotai/kimi-k2.6`, the default), the titles +(`@cf/zai-org/glm-4.7-flash`, thinking off) and the artifact tools (they use +the chat's model). `lib/ai/models.ts` keeps upstream's gateway list as +`gatewayModels`, offered only when `AI_GATEWAY_API_KEY` is set +(`getAvailableModels`); `/api/models` returns `available`, and the picker +shows exactly that list (its logo comes from each model's `provider`, since +a Workers AI id starts with `@cf/`). A request naming a model the deployment +cannot run is answered by the default model (`resolveModelId`). Workers AI's +own errors appear in the chat ("Workers AI could not answer with …") rather +than as "Oops"; the writing-suggestions tool, which needs structured output, +returns its error to the model instead of failing the response. Workers AI +model capabilities are declared rather than fetched, so a chat no longer +makes five capability lookups to the gateway (AC-C). + +### Dev-server bindings only in the dev server; no `populateCache` + +`initOpenNextCloudflareForDev()` runs only for `next dev` (the config is a +phase function): the `AI` binding has no local simulator, so wrangler's +platform proxy opens a remote session, and a build must need no Cloudflare +credential. For the same reason the build's last step is +`scripts/populate-static-assets-cache.mjs` — the copy +`opennextjs-cloudflare populateCache local` makes for the static-assets +cache — instead of that command, which opens the platform proxy first. + +### The session key is the database's own unless `AUTH_SECRET` is set + +`lib/auth-secret.ts` returns `AUTH_SECRET` when set, else the 64-hex key +migration `020_app_secrets` generated into `app_private.secrets` (not a +schema the Data API exposes), read once per isolate. Auth.js is initialised +lazily (`NextAuth(async () => ({ …, secret }))`) so its config can await it; +`proxy.ts` and the guest route decode the session with it too (risk AC-N). +`lib/auth-cookie.ts` picks the session cookie's name as Auth.js does — the +`__Secure-` prefix over https only — where upstream used +`!isDevelopmentEnvironment`, which disagreed with Auth.js for the built +Worker served over http. + +### Row-level security on every table in `public` + +Migration `030_row_level_security` (drizzle twin `0002`; `.enableRLS()` on +each table in `schema.ts`) enables RLS with no policy on `User`, `Chat`, +`Message_v2`, `Vote_v2`, `Document`, `Suggestion` and `Stream`, behind a +guard (AC-M). + +### The rest + +- `apps/web/wrangler.jsonc` is committed (the fixture render, with a + GENERATED banner); every lane re-renders it — stage and prod from their + wiring documents, dev from the fixture (`live.mjs --fixture-envs dev`). +- `/api/health` (database reachable and migrated; which model provider + serves) and `/ping` are what the smoke and the probes read; the proxy lets + both through without a session. +- `lib/site.ts` is the product-name seam (the `<title>`, the sidebar + tooltip, the preview label). +- `metadataBase` is the product's own origin, baked at build + (`NEXT_PUBLIC_SITE_URL` from the environment's `SITE_URL` or its + workers.dev URL), not upstream's `chat.vercel.ai`; the header's "Deploy + with Vercel" button and its mobile icon link are gone, and the sign-in + page says "Powered by Workers AI". +- The R2 root applies with its own `r2-data` key (`CLOUDFLARE_R2_TOKEN`); + the Supabase root publishes Lumen's three outputs only; every infra edge + is enforced on main and advisory on pull requests; stack-tectonic 0.19.0. ## Verified -- Local: `pnpm run wire:fixture`, `pnpm typecheck` (5 packages), `pnpm - lint` (0 errors, the one tailwind warning), `pnpm test` (12 in - `tests/web` — utils 2, embedding 3, resources action 3, `getDb` 4 — and 3 - in `tests/db`), `pnpm build` (`/` and `/_not-found` static, `/api/chat` - dynamic; Worker + static assets) green. `pnpm --filter @saas/db run - manifest:check` green; `node packages/db/dist/runner/cli.js plan --env - stage` lists `000_control_baseline` and `010_rag_initial`. -- `wrangler dev` on the built Worker with the fixture Hyperdrive id (its - `localConnectionString` pointing at a localhost Postgres that was not - running) and a throwaway `AI_GATEWAY_API_KEY`: `/` 200 ("Retrieval - Augmented Generation Preview", "Ask me anything..."), `/nope` 404, `POST - /api/chat` with one user message 200 `text/event-stream` — `start`, - `error "An error occurred."`, `[DONE]` — the Worker log naming the cause: - `GatewayError: Unauthenticated. Configure AI_GATEWAY_API_KEY` (the key is - rejected before any tool runs, so that probe did not reach Hyperdrive; - `getDb()`'s binding and fallback paths are covered by `tests/web`). Local - workerd logged a runtime crash and restart after the stream error. -- `terraform init -backend=false && terraform validate` green on - `infra/terraform/supabase` (supabase/supabase 1.5.1, random 3.9.1, - external 2.4.2) and `infra/terraform/cloudflare-hyperdrive` - (cloudflare/cloudflare 4.52.9). -- CI: `Checks` green on #2, #3 and #4; the Orun jobs skip until the product - is linked. -- Not verified: an apply of the Supabase and Hyperdrive roots, a db-migrate - apply (and so `CREATE EXTENSION vector` through the Management API), a - live deploy, and an end-to-end chat against a real pgvector database with - a real gateway key — all need the product linked to an Orun workspace with - Supabase and Cloudflare connections (`ORUN_CI`) and `AI_GATEWAY_API_KEY` - set per environment with `wrangler secret put` (README → Deploying). +- AC1–AC4: Checks (typecheck, lint, test, build); the Worker under + `wrangler dev` without a Postgres; the offline migration plan; + `terraform validate` on the three roots. +- AC5: the contract, wiring, leak and placement tests; `orun new --status` + at v2.58.11, v2.78.4 and 2.79.0; `orun validate`; `orun work check`; the + e2e tier — the product built in the job tree orun stages, migrated into a + local Postgres by its own runner, served under `wrangler dev` with a guest + signed in by the database's key, a chat streamed through a stand-in AI + binding, titled, persisted and listed, an attachment round-tripped through + local R2, a registration and a sign-in, and `anon`/`authenticated` reading + none of it. + +## Not verified (gated on a live bootstrap) + +- The Supabase, Hyperdrive and R2 applies and db-migrate against a real + project; a real deploy and its smoke. +- Workers AI itself: the model ids served on the account, tool calling + driving the artifact tools, structured output for suggestions (AC-K). +- Whether the `workers-deploy` token may attach the `BLOB` R2 binding + (AC-L). diff --git a/specs/epics/ai-chatbot/README.md b/specs/epics/ai-chatbot/README.md index fd4e907..28655c3 100644 --- a/specs/epics/ai-chatbot/README.md +++ b/specs/epics/ai-chatbot/README.md @@ -8,13 +8,13 @@ The upstream code stays the code: `app/(chat)/api/chat/route.ts` with `streamTex | Field | Value | |-------|-------| -| Status | ✅ Shipped — AC0–AC4 landed (#1–#5); the Supabase, Hyperdrive and R2 applies, db-migrate and a live deploy gated on a linked workspace | -| Cluster | **AC** (AC0–AC4) | +| Status | 🔄 AC5 in review — AC0–AC4 landed (#1–#5); AC5 makes the repository an Orun baseline (one landing), Workers AI the default model provider, the session key the database's own and row-level security universal. The Supabase, Hyperdrive and R2 applies, db-migrate and a live deploy are gated on a linked workspace | +| Cluster | **AC** (AC0–AC5) | | Owner(s) | `apps/web` (the app) · `tests/web` (vitest) · `packages/db` + `tests/db` (the schema) · `infra/terraform/{supabase,cloudflare-hyperdrive,cloudflare-r2}` + `infra/db-migrate` | | Builds on | `lumen` conventions — the `supabase`, `cloudflare-hyperdrive` and `db-migrate` components, `@saas/db`, the orun-secrets wiring, the per-request `postgres` client; `cirrus-baseline` for the R2 root and the repository shape | | Upstream | [vercel/ai-chatbot](https://github.com/vercel/ai-chatbot) v3.1 (AI SDK 7, Next 16, next-auth v5 beta, Drizzle) | | Changes | Adds the Workers build, the monorepo wrapper, tests, the migrations package, the infra roots and the deploy contract; in the template's code: the per-call Postgres client, the R2 attachment routes, and shims for the Vercel-only modules (`lib/bot.ts`, `lib/geo.ts`, an empty `instrumentation.ts`) | -| Decisions locked | (1) OpenNext on Workers + Static Assets, `next` pinned to 16.3.8. (2) Postgres through Hyperdrive, one `postgres` client per `getDb()` call, never at module scope. (3) Attachments in R2 behind `/api/files/<key>`, public by unguessable URL exactly as Vercel Blob's `access: "public"` was. (4) The schema ships in `packages/db` and is applied by db-migrate; drizzle-kit stays for local development. (5) Static-assets incremental cache: the app has no `use cache` and nothing revalidates. (6) No Redis: resumable streams and the IP rate limit stay off, as upstream does without `REDIS_URL`. (7) `AUTH_SECRET` and `AI_GATEWAY_API_KEY` are Worker secrets set once per environment. | +| Decisions locked | (1) OpenNext on Workers + Static Assets, `next` pinned to 16.3.8. (2) Postgres through Hyperdrive, one `postgres` client per `getDb()` call, never at module scope. (3) Attachments in R2 behind `/api/files/<key>`, public by unguessable URL exactly as Vercel Blob's `access: "public"` was. (4) The schema ships in `packages/db` and is applied by db-migrate; drizzle-kit stays for local development. (5) Static-assets incremental cache: the app has no `use cache` and nothing revalidates. (6) No Redis: resumable streams and the IP rate limit stay off, as upstream does without `REDIS_URL`. (7) `AUTH_SECRET` and `AI_GATEWAY_API_KEY` are Worker secrets set once per environment — **superseded by AC5**: both are optional; Workers AI through the `AI` binding is the default model provider, and the session key defaults to one the database generates. | | Gate | AC1 is the first user-visible rung and is verified without a database (the Worker boots, the routes answer). AC2 and AC3 need a workspace with Supabase and Cloudflare connections to apply; they are verified by `plan`, `terraform validate` and the offline migration tests. | | Shipped as | `main` after [#5](https://github.com/sourceplane/ai-chatbot/pull/5); verified locally under `wrangler dev` with dummy secrets and no Postgres (the Worker boots, every route answers) | @@ -34,3 +34,4 @@ The upstream code stays the code: `app/(chat)/api/chat/route.ts` with `streamTex | AC2 — the schema through db-migrate | `packages/db` with the template's SQL, `tests/db`, `infra/db-migrate` | the manifest checks, the offline plan lists the migration | | AC3 — Supabase, Hyperdrive and R2 from Terraform | the three roots and the app's wiring from them | the roots validate; the wiring keys match the template's tokens | | AC4 — ready to instantiate | README, as-built status | a reader can run, test, preview and deploy it | +| AC5 — a baseline | the card, the build document, `.baseline/`, the rebrand engine, the bootstrap helpers, `testing/`; Workers AI by default, the database's session key, RLS, the committed wrangler config, `/api/health`, the R2 root on its own `r2-data` key | Baseline CI green: contract, leak, placement (infra before app) and the e2e tier | diff --git a/specs/epics/ai-chatbot/epic.yaml b/specs/epics/ai-chatbot/epic.yaml index 904cb94..5baea9e 100644 --- a/specs/epics/ai-chatbot/epic.yaml +++ b/specs/epics/ai-chatbot/epic.yaml @@ -8,8 +8,8 @@ metadata: key: AC spec: title: "Vercel's Next.js AI Chatbot on Cloudflare Workers with Supabase Postgres, Hyperdrive and R2" - summary: "The vercel/ai-chatbot template — AI SDK 7 streaming chat with artifacts and tools, next-auth v5 with a guest flow, Drizzle over Postgres, image attachments — runs on Cloudflare Workers + Static Assets through @opennextjs/cloudflare. Its Postgres is a Supabase project reached through Hyperdrive (the Lumen baseline's shape: supabase and cloudflare-hyperdrive Terraform roots, the schema applied by db-migrate from packages/db), its attachments go to an R2 bucket the Worker serves back, and its model calls keep the Vercel AI Gateway. Everything Vercel-only in the code — Blob, BotID, @vercel/functions, @vercel/otel, @vercel/analytics — is replaced by the Cloudflare equivalent or a no-op, each recorded as a departure; the chat, auth, artifact and data code is the template's." - state: completed + summary: "The vercel/ai-chatbot template — AI SDK 7 streaming chat with artifacts and tools, next-auth v5 with a guest flow, Drizzle over Postgres, image attachments — runs on Cloudflare Workers + Static Assets through @opennextjs/cloudflare. Its Postgres is a Supabase project reached through Hyperdrive (the Lumen baseline's shape: supabase and cloudflare-hyperdrive Terraform roots, the schema applied by db-migrate from packages/db), its attachments go to an R2 bucket the Worker serves back, and its model calls keep the Vercel AI Gateway (until AC5, which makes Workers AI the default and the gateway optional). Everything Vercel-only in the code — Blob, BotID, @vercel/functions, @vercel/otel, @vercel/analytics — is replaced by the Cloudflare equivalent or a no-op, each recorded as a departure; the chat, auth, artifact and data code is the template's." + state: started milestones: - name: "AC0 — the spec" exitCriteria: @@ -36,3 +36,12 @@ spec: - "the README says how to run it locally with a Postgres, test, preview and deploy it through Orun, which Worker secrets to set and how attachments and the model gateway are configured" - "the as-built status records every departure from the upstream template" tasks: [AC-5] + - name: "AC5 — a baseline" + exitCriteria: + - "blueprint.yaml (the console card, requires [github, cloudflare, supabase], six brokered keys — an r2-data key for the R2 root among them) and repo-blueprint.yaml (the build) take a new product from nothing to live on stage and prod in ONE landing, then record it (01-product, 02-docs)" + - "the product's own push-to-main plan converges supabase → cloudflare-hyperdrive → db-migrate → web and cloudflare-r2 → web per environment, every edge enforced on main and advisory on a pull request" + - "Workers AI through an AI binding is the default model provider for the chat, the titles and the artifact tools; the AI Gateway's models are offered only with its key; a fresh product chats with no model key" + - "a fresh product signs a guest in and registers a user with no AUTH_SECRET: the session key is one the database generated, kept in a schema the Data API does not expose" + - "every table in public has row-level security and no policy: Supabase's Data API (anon, authenticated) reads and writes nothing, the app, as the tables' owner, everything" + - "Baseline CI is green: contract tests, the blueprint read by the pinned orun, the leak gate, the offline bootstrap and the product's plans, and the end-to-end tier (a stand-in AI binding — Workers AI is not called offline)" + tasks: [AC-6] diff --git a/specs/epics/ai-chatbot/implementation-plan.md b/specs/epics/ai-chatbot/implementation-plan.md index fbf63e1..959d9bf 100644 --- a/specs/epics/ai-chatbot/implementation-plan.md +++ b/specs/epics/ai-chatbot/implementation-plan.md @@ -62,6 +62,40 @@ the Worker secrets, attachments on R2, the model gateway), - the README quick start works from a fresh clone - the status file lists every PR and departure +## AC5 — a baseline 🔄 + +The repository becomes an Orun baseline on the Lumen conventions, built the +way cirrus-baseline v22 builds a product: in ONE landing. `blueprint.yaml` +(the console card) and `repo-blueprint.yaml` (the build: `01-product` places +everything and lands one PR, `02-docs` is hook-only), `.baseline/` (identity, +task contracts, the product's README), the rebrand engine with the +`lib/site.ts` name seam, the bootstrap helpers, the deployment-record hook, +`ai/context/`, the `baseline.yml`/`tag.yml` workflows and `testing/`. + +What a fresh, unattended build forces on the app: +- **Workers AI is the default model provider**, through an `AI` binding in + the committed wrangler config (`workers-ai-provider` 4.0.0, which speaks AI + SDK 7): the chat (Kimi K2.6), the titles and the artifact tools (GLM 4.7 + Flash for titles). The AI Gateway's models are offered only with + `AI_GATEWAY_API_KEY`; the picker shows exactly what can answer. +- **The session key** is `AUTH_SECRET` or, unset, one the database generated + (`020_app_secrets`, in `app_private`, which the Data API does not expose); + the proxy and the guest route read it too. +- **Row-level security** on every table in `public` (`030`), no policy. +- `apps/web/wrangler.jsonc` committed as the fixture render; `/api/health`; + the R2 root on its own `r2-data` key; infra-before-app edges enforced on + main and advisory on pull requests. + +**Done when** +- the contract, wiring, leak and placement tests pass, `orun new --status` + reads the blueprint at v2.58.11, v2.78.4 and 2.79.0, and `orun work check` + is clean +- the e2e tier builds the product in the staged job tree, migrates a local + Postgres with the product's own runner, serves it under `wrangler dev` and + signs a guest in, streams a chat answer through the (stand-in) AI binding, + persists and lists it, round-trips an attachment through local R2, + registers and signs a user in — and the Data API's roles read none of it + ## Sequencing note AC1 is verified without a database: the Worker boots and every route diff --git a/specs/epics/ai-chatbot/risks-and-open-questions.md b/specs/epics/ai-chatbot/risks-and-open-questions.md index 495489f..fe14a9b 100644 --- a/specs/epics/ai-chatbot/risks-and-open-questions.md +++ b/specs/epics/ai-chatbot/risks-and-open-questions.md @@ -48,7 +48,7 @@ followed, and `tsc` failed in upstream's own files. Those five are pinned to the versions upstream's lockfile resolved; everything else floats as upstream wrote it. -## AC-F — The model gateway from a Worker (ACCEPTED) +## AC-F — The model gateway from a Worker (ACCEPTED; superseded by AC-K) The AI Gateway is an HTTPS API; the Worker calls it with `AI_GATEWAY_API_KEY` (no OIDC off Vercel, as upstream's README says for @@ -64,7 +64,7 @@ setting (Bot Management / Super Bot Fight Mode) or a Turnstile challenge on the chat form; neither is in the repository. Per-user entitlements and the guest flow still bound what an unauthenticated visitor can do. -## AC-H — Worker secrets are set by hand (ACCEPTED) +## AC-H — Worker secrets are set by hand (ACCEPTED; superseded by AC5) `AUTH_SECRET` and `AI_GATEWAY_API_KEY` are set once per environment with `wrangler secret put`; the deploy lane renders the wrangler config from the @@ -82,3 +82,64 @@ limits and identical to a cold Vercel function. The build and tests were run on Node 25; CI builds on Node 22. Nothing in this template reads `localStorage` at prerender. + +## AC-K — Workers AI by default; real models unverified offline (OPEN until a live bootstrap) + +The platform brokers no AI vendor, so a product built from the baseline must +chat with only Cloudflare and Supabase connected. Workers AI through the +Worker's `AI` binding is the default (`lib/ai/models.ts`: Kimi K2.6 for the +chat, GLM 4.7 Flash for titles), via `workers-ai-provider` 4.0.0 (AI SDK 7, +`@ai-sdk/provider` 4). The e2e cannot call Workers AI: it stands the binding +in with a deterministic Worker (`testing/lib/fake-ai/`) that answers +`run()` in the binding's own shapes. So what is proven offline is the app's +half — the route picks the model, the provider streams the binding's events, +the title, the persistence, the fallback from an unavailable gateway model. +What is NOT proven until a live deployment: that those model ids are served +on the account, that their tool calls drive the artifact tools, and that the +writing-suggestions tool's structured output is honoured (it answers the +model with the error instead of failing the chat if it is not). Workers AI +usage is billed to the Cloudflare account after its free allocation. + +## AC-L — The deploy token and the R2 binding (OPEN, platform) + +The `cloudflare-r2` root applies with its own `r2-data` key +(`CLOUDFLARE_R2_TOKEN`), not the deploy token. But the Worker's `BLOB` +binding is attached by `wrangler deploy`, which runs with the +`workers-deploy` token (Workers Scripts and KV Storage). Whether Cloudflare +accepts an R2 binding on a script uploaded with that token is unverified +live; if it does not, the first `web` deploy fails, and the fix is the +platform's `workers-deploy` template (blob-starter and commerce carry the +same risk). Nothing in this repository can fix it. + +## AC-M — Row-level security on every table in public (RESOLVED in AC5) + +Supabase's Data API serves `public` to the anon key. Migration +`030_row_level_security` enables RLS with no policy on all seven tables, +after a guard that refuses if `postgres` (Hyperdrive's role) neither owns +them nor bypasses RLS. tests/db fails on any table left without it; the e2e +shows `anon` and `authenticated` read none of the rows a guest's chat wrote. +Unverified live: that the Management API runs migrations as `postgres`, so +that it owns the tables (the guard stops the migration if not). + +## AC-N — The session key before the database answers (SETTLED) + +Auth.js (next-auth v5) is initialised lazily, its config resolved per +request, so `secret` can be the database's key. `proxy.ts` decodes the +session BEFORE any route runs and needs the key too: it reads it the same +way, over the same Hyperdrive binding (OpenNext runs the proxy inside the +Worker), once per isolate. `/ping` and `/api/health` answer before that read, +so a database outage still shows on the health route rather than as a +redirect loop. Separately, the proxy and the guest route now pick the +session cookie's name the way Auth.js does (`__Secure-` over https only): +upstream's `!isDevelopmentEnvironment` disagreed with Auth.js for the built +Worker served over http (`wrangler dev`), where every page redirected back +to the guest sign-in. + +## AC-O — A prerender/resume mismatch is logged on `/` (ACCEPTED, upstream) + +Served by the built Worker, the first `GET /` logs "Expected the resume to +render <h> in this slot but instead it rendered <h2>… React will fallback +to client rendering". It is not AC5's: a build of `main` at AC4 logs the same +line under `wrangler dev`. The page answers 200 and renders on the client; +it is Next 16's `cacheComponents` shell resumed under OpenNext, left for an +upstream or OpenNext release rather than worked around in the template. diff --git a/tasks/AC-1.TaskContract.yaml b/tasks/AC-1.TaskContract.yaml index 593698e..b85e408 100644 --- a/tasks/AC-1.TaskContract.yaml +++ b/tasks/AC-1.TaskContract.yaml @@ -1,5 +1,8 @@ apiVersion: orun.io/v1 kind: TaskContract +metadata: + name: AC-1 + title: "The spec" spec: goal: The ai-chatbot epic — declaration, doc set and task contracts — is on main affects: diff --git a/tasks/AC-2.TaskContract.yaml b/tasks/AC-2.TaskContract.yaml index aad4cd4..4e52443 100644 --- a/tasks/AC-2.TaskContract.yaml +++ b/tasks/AC-2.TaskContract.yaml @@ -1,5 +1,8 @@ apiVersion: orun.io/v1 kind: TaskContract +metadata: + name: AC-2 + title: "The chatbot on Workers" spec: goal: The upstream AI Chatbot runs on Cloudflare Workers + Static Assets with Postgres through the HYPERDRIVE binding, attachments on the BLOB R2 binding, a per-environment rendered wrangler config and green checks affects: diff --git a/tasks/AC-3.TaskContract.yaml b/tasks/AC-3.TaskContract.yaml index 9155cbd..7015e74 100644 --- a/tasks/AC-3.TaskContract.yaml +++ b/tasks/AC-3.TaskContract.yaml @@ -1,5 +1,8 @@ apiVersion: orun.io/v1 kind: TaskContract +metadata: + name: AC-3 + title: "The schema through db-migrate" spec: goal: The template's schema ships in packages/db as a manifest-listed migration and is applied per environment by the db-migrate component affects: diff --git a/tasks/AC-4.TaskContract.yaml b/tasks/AC-4.TaskContract.yaml index fe73bd5..76c06d5 100644 --- a/tasks/AC-4.TaskContract.yaml +++ b/tasks/AC-4.TaskContract.yaml @@ -1,5 +1,8 @@ apiVersion: orun.io/v1 kind: TaskContract +metadata: + name: AC-4 + title: "Supabase, Hyperdrive and R2 from Terraform" spec: goal: The Supabase project, the Hyperdrive config over its Postgres and the attachments R2 bucket are provisioned per environment by Terraform through Orun, publishing the secrets and wiring documents the app and db-migrate components name affects: diff --git a/tasks/AC-5.TaskContract.yaml b/tasks/AC-5.TaskContract.yaml index 5d4e18c..66dd91c 100644 --- a/tasks/AC-5.TaskContract.yaml +++ b/tasks/AC-5.TaskContract.yaml @@ -1,5 +1,8 @@ apiVersion: orun.io/v1 kind: TaskContract +metadata: + name: AC-5 + title: "Ready to instantiate" spec: goal: A reader can run the chatbot locally with a Postgres, test, preview and deploy it through Orun from the README; the as-built status is complete affects: diff --git a/tasks/AC-6.TaskContract.yaml b/tasks/AC-6.TaskContract.yaml new file mode 100644 index 0000000..d94e147 --- /dev/null +++ b/tasks/AC-6.TaskContract.yaml @@ -0,0 +1,41 @@ +apiVersion: orun.io/v1 +kind: TaskContract +metadata: + name: AC-6 + title: "A baseline" +spec: + goal: The repository is an Orun baseline on the Lumen conventions — a card and a build document that take a new chatbot from nothing to live on stage and prod in one landing (Supabase, Hyperdrive and R2, then the migrations, then the app), branded as its own, chatting on Workers AI with no model key and signing guests in with no owner-set secret, 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 + - pnpm-workspace.yaml + - pnpm-lock.yaml + - apps/web/** + - packages/db/** + - infra/** + - tests/web/** + - tests/db/** + - specs/** + - tasks/** + doneWhen: + - orun (the bootstrap floor, the lane pin and 2.79.0) reads repo-blueprint.yaml, and the card agrees with it + - the product's own push-to-main plan orders supabase → cloudflare-hyperdrive → db-migrate → web and cloudflare-r2 → web, enforced, and a pull request's plan holds the same edges advisory + - the R2 root applies with its own r2-data key, not the deploy token + - a product built offline installs, migrates a local Postgres with its own runner, builds in the job tree orun stages, serves, signs a guest in, streams a chat answer through its AI binding (a stand-in offline), persists and lists it, round-trips an attachment through R2, and registers a user — with no model key and no AUTH_SECRET + - every table in public has row-level security; anon and authenticated read none of what the flow wrote + - 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..ca36d4d --- /dev/null +++ b/testing/e2e.test.sh @@ -0,0 +1,651 @@ +#!/usr/bin/env bash +# TIER 2 — the product a bootstrap produces builds, migrates, deploys (dry), +# serves, signs a guest in and chats, with no model key and no AUTH_SECRET. +# +# placement.test.sh proves the tree a bootstrap ends with is the right tree, +# and that its own plan converges in the right order. This proves it WORKS, +# by doing to it what its own pipelines will: +# +# 1. at the 01-product landing (the commit its PR merges), run what +# `checks.yml` runs on that PR — install with the lockfile the phase +# placed, render the wrangler fixture (which must change nothing: the +# render is committed), typecheck, lint, test, build. That landing WAITS +# on its checks; +# 2. a Postgres of its own on a random port, with Supabase's roles — the +# database a Supabase project would be: `postgres` a login role WITHOUT +# superuser or BYPASSRLS, `anon` and `authenticated` with the Data API's +# default grants (testing/lib/local-postgres.sh) — and a stand-in for the +# ONE Supabase Management API endpoint the migration runner calls +# (testing/lib/fake-supabase-api.py), connected as `postgres`; +# 3. the db-migrate lane's own steps, rendered by `orun plan` for a push to +# main and run IN THE TREE THE RUNNER STAGES for the job: install, build +# @saas/db, apply — every migration, the session key the database +# generates for itself and row-level security on every table in `public` +# included — then apply again, which must apply nothing, and the +# pull-request profile's offline plan; +# 4. the web lane's own steps for stage, rendered for a pull request (the +# verify profile carries deploy-dry-run; the deploy profile does not) and +# run in its staged job tree: install, `verify-app-structure` (the +# committed wrangler.jsonc must exist BEFORE the build, in a tree with no +# build output), `build-app` — which re-renders the config from the two +# stage wiring documents it is handed (Hyperdrive's and R2's), as the +# deploy does — then `verify-build-output` and `deploy-dry-run`; +# 5. the built Worker under `wrangler dev`, its HYPERDRIVE binding pointed at +# that Postgres, its BLOB bucket wrangler's local R2, with NO .dev.vars — +# no model key, no AUTH_SECRET — and the component's OWN `smokeCommand` +# against it, verbatim; then every route the product promises and its +# real flow: a visitor is signed in as a guest (the session encrypted +# with the key the database generated), sends a message to the app's own +# chat route and gets a streamed answer, the chat is titled, persisted +# and listed in the history, an image is uploaded to R2 and read back, +# and a visitor registers and signs in; +# 6. the Data API's view of the same database: every table in `public` has +# row-level security, and `anon` and `authenticated` — granted everything +# Supabase grants them — read none of the rows the flow wrote and can +# write none, while the app, as the tables' owner and nothing more, just +# did both. +# +# WORKERS AI CANNOT BE CALLED OFFLINE. In step 5 the Worker's `AI` binding — +# the one thing in its wrangler config this test changes — is a service +# binding to a deterministic stand-in (testing/lib/fake-ai/), run in the same +# `wrangler dev` session, that answers `run()` the way Workers AI's binding +# does: a JSON body, or a server-sent-event stream, of canned text naming the +# model it was asked for. So this proves the app's half — the route, the +# provider, the model it picks, the stream, the title, the persistence — and +# NOT that a real Workers AI model answers, calls tools or honours structured +# output; that is verified only by a live deployment. +# +# What it cannot do either is the platform's half: create the repository, +# mint the brokered tokens, create a real Supabase project, Hyperdrive config +# and R2 bucket (Terraform is validated, not applied, in this repository), +# deploy for real and probe workers.dev. That is a bootstrap against a +# workspace (BOOTSTRAP.md); everything short of it is here. +# +# Needs: orun, node, pnpm, python3 (+PyYAML), git, curl, psql and a +# PostgreSQL server install (initdb, pg_ctl), and the network for +# `pnpm install` (or a warm store). A few minutes: three installs, two builds. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/.." && pwd)" +# shellcheck source=lib/bootstrap.sh +source "$here/lib/bootstrap.sh" +# shellcheck source=lib/local-postgres.sh +source "$here/lib/local-postgres.sh" + +for bin in orun node pnpm python3 git curl psql; do + command -v "$bin" >/dev/null || { echo "e2e.test.sh needs $bin on PATH" >&2; exit 1; } +done +pg_bin >/dev/null || { echo "e2e.test.sh needs a PostgreSQL server install (initdb, pg_ctl)" >&2; exit 1; } + +scratch="$(mktemp -d)" +pgdir="$(mktemp -d)" +dev_pid="" +api_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 each +# server is started as its own process group (setsid) and the group stopped. +stop_group() { + local pid="$1" + [ -n "$pid" ] || return 0 + kill -TERM -- "-$pid" 2>/dev/null || true + for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 -- "-$pid" 2>/dev/null || break; sleep 0.5; done + kill -KILL -- "-$pid" 2>/dev/null || true +} +cleanup() { + stop_group "$dev_pid" + stop_group "$api_pid" + pg_down "$pgdir" + [ -n "$pgdir" ] && [ -d "$pgdir" ] && rm -rf "$pgdir" + [ -n "$scratch" ] && [ -d "$scratch" ] && rm -rf "$scratch" +} +trap cleanup EXIT +free_port() { python3 -c "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print(s.getsockname()[1]);s.close()"; } +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 +) +} + +# One job of a plan, written out as the runner would run it: each `run:` step +# (the `use:` actions are setup-node and setup-pnpm, which this machine has) +# as a numbered script, the job's env, and the component path the steps run +# in. Steps are picked BY ID when given, else every `run:` step in order. +extract_job() { # PLAN JOB-ID OUT-DIR [STEP-ID…] + python3 - "$@" <<'PY' +import json, pathlib, sys +plan, jid, out, *want = sys.argv[1:] +job = next((j for j in json.load(open(plan))["jobs"] if j["id"] == jid), None) +if job is None: + sys.exit(f"the plan has no job {jid}") +out = pathlib.Path(out); out.mkdir(parents=True) +steps = [s for s in job["steps"] if s.get("run")] +if want: + by = {s["id"]: s for s in steps} + missing = [w for w in want if w not in by] + if missing: + sys.exit(f"{jid} has no step(s) {missing}") + steps = [by[w] for w in want] +for i, s in enumerate(steps): + (out / f"{i:02d}.sh").write_text(s["run"]) + (out / f"{i:02d}.id").write_text(s["id"]) +(out / "path").write_text(job.get("path") or ".") +with (out / "env").open("w") as f: + for k, v in (job.get("env") or {}).items(): + f.write(f"export {k}={json.dumps(v)}\n") +PY +} +run_job() { # STEPS-DIR WORK-TREE ENV LOG-PREFIX + local steps="$1" work="$2" envname="$3" logp="$4" s id + for s in "$steps"/[0-9][0-9].sh; do + id="$(cat "${s%.sh}.id")" + echo " ▸ $id" + if ! (cd "$work/$(cat "$steps/path")" && source "$steps/env" && export ORUN_ENVIRONMENT="$envname" \ + && bash -e "$s") > "$logp-$id.log" 2>&1; then + echo "FAIL: the lane's $id step" >&2; tail -40 "$logp-$id.log" >&2; return 1 + fi + done +} + +echo "── the offline bootstrap (testing/lib/bootstrap.sh)" +tree="$scratch/$repo" +bootstrap_offline "$root" "$tree" "$values" "$scratch/logs" > "$scratch/bootstrap.log" 2>&1 || { + echo "FAIL: the offline bootstrap stopped" >&2; tail -40 "$scratch/bootstrap.log" >&2; exit 1; } +echo " 2 phases placed and landed" + +# ── 1. the product's own pull request ────────────────────────────────────── +echo "── 01-product's landing, under the checks its PR waits on" +s01="$(git -C "$tree" rev-parse HEAD~1)" +at01="$scratch/at-01/$repo" +git -C "$tree" worktree add -q "$at01" "$s01" +checks "$at01" "$scratch/checks.log" +dirty="$(git -C "$at01" status --porcelain)" +[ -z "$dirty" ] || { echo "FAIL: the checks changed tracked files — the committed wrangler.jsonc is not the fixture render:" >&2; echo "$dirty" >&2; exit 1; } +echo " the checks left the tree as committed (wire:fixture rendered the committed wrangler.jsonc)" + +# ── 2. a database, and the one API the migration runner calls ────────────── +echo "── a local Postgres and the Supabase Management API stand-in" +pgurl="$(pg_up "$pgdir" "$(free_port)")" || { echo "FAIL: Postgres did not start" >&2; exit 1; } +api_port="$(free_port)" +ref="localproject" +setsid python3 "$here/lib/fake-supabase-api.py" "$api_port" "$pgurl" --ref "$ref" > "$scratch/api.log" 2>&1 < /dev/null & +api_pid=$! +for _ in $(seq 1 30); do curl -s -o /dev/null "http://127.0.0.1:$api_port/" && break; sleep 0.3; done +echo " $pgurl; the API on :$api_port" + +# The two plans the lanes below run from, each in the product's own tree: a +# push to main at the 01-product commit (the db-migrate lane's APPLY profile), +# and a pull request over the finished product against an empty base (the web +# lane's VERIFY profile, which carries deploy-dry-run, and db-migrate's PLAN). +(cd "$at01" && orun plan --intent intent.yaml --trigger github-push-main --env stage --output "$scratch/plan-main.json") > "$scratch/plan-main.log" 2>&1 \ + || { echo "FAIL: orun plan (push to main)" >&2; tail -15 "$scratch/plan-main.log" >&2; exit 1; } +git -C "$tree" worktree remove --force "$at01" +mkdir -p "$scratch/pr" +git clone -q "$tree" "$scratch/pr/$repo" +prtree="$scratch/pr/$repo" +git -C "$prtree" checkout -q --orphan empty +git -C "$prtree" rm -rqf . +git -C "$prtree" -c user.email=t@example.invalid -c user.name=t commit -qm empty --allow-empty +git -C "$prtree" checkout -q main +(cd "$prtree" && orun plan --intent intent.yaml --trigger github-pull-request --base empty --head HEAD --env stage \ + --output "$scratch/plan-pr.json") > "$scratch/plan-pr.log" 2>&1 \ + || { echo "FAIL: orun plan (pull request)" >&2; tail -15 "$scratch/plan-pr.log" >&2; exit 1; } +# This tier runs the orun the product's CI pins, which reads the per-edge +# `modeRules`: on a pull request — which applies and deploys nothing — the +# infrastructure edges that order a push to main are advisory, so no lane +# waits on another. (placement.test.sh checks the push to main's order.) +python3 - "$scratch/plan-pr.json" <<'PY' +import json, sys +jobs = {j["component"]: j for j in json.load(open(sys.argv[1]))["jobs"] if j["environment"] == "stage"} +chain = ["supabase", "cloudflare-hyperdrive", "db-migrate", "web"] +for a, b in list(zip(chain, chain[1:])) + [("cloudflare-r2", "web")]: + ja, jb = jobs[a], jobs[b] + if ja["id"] in (jb.get("dependsOn") or []) or ja["id"] not in (jb.get("advisoryDependsOn") or []): + sys.exit(f"FAIL: on a pull request {b}@stage must name {a}@stage as advisory, not wait on it") +print(" pull request: " + " → ".join(chain) + " and cloudflare-r2 → web, every edge advisory") +PY + +# ── 3. the db-migrate lane, in its staged job tree ───────────────────────── +echo "── the stage db-migrate lane: install, build @saas/db, apply — then apply again, and the PR's plan" +extract_job "$scratch/plan-main.json" db-migrate.stage.migrate "$scratch/steps-migrate" \ + install-dependencies build-db-package "Migration Apply" +extract_job "$scratch/plan-main.json" db-migrate.stage.migrate "$scratch/steps-migrate-again" "Migration Apply" +extract_job "$scratch/plan-pr.json" db-migrate.stage.migrate "$scratch/steps-migrate-plan" "Migration Plan" +# Staged from the fresh clone (a CI checkout: no build output, no +# node_modules); its migrations are the 01-product commit's, byte for byte. +mwork="$prtree/.orun/runs/e2e/db-migrate.stage.migrate/work" +python3 "$here/lib/stage-job.py" "$prtree" "$mwork" +# The component's secretEnv, as the lane resolves it: the supabase apply's +# published credentials and the brokered access token. SUPABASE_API_URL is +# the one value no lane has — it points the runner at the stand-in. +export SUPABASE_ACCESS_TOKEN=e2e-token SUPABASE_PROJECT_REF="$ref" SUPABASE_DB_PASSWORD=postgres \ + SUPABASE_DB_URL="$pgurl" SUPABASE_API_URL="http://127.0.0.1:$api_port" +run_job "$scratch/steps-migrate" "$mwork" stage "$scratch/migrate" +applied() { python3 -c "import json,sys;t=open(sys.argv[1]).read();print(' '.join(json.loads(t[t.index('{'):t.rindex('}')+1])['applied']))" "$1"; } +want="000_control_baseline 010_initial 020_app_secrets 030_row_level_security" +[ "$(applied "$scratch/migrate-Migration Apply.log")" = "$want" ] \ + || { echo "FAIL: the first apply applied '$(applied "$scratch/migrate-Migration Apply.log")', not '$want'" >&2; exit 1; } +echo " applied $want" +run_job "$scratch/steps-migrate-again" "$mwork" stage "$scratch/migrate-again" +[ -z "$(applied "$scratch/migrate-again-Migration Apply.log")" ] \ + || { echo "FAIL: a second apply applied '$(applied "$scratch/migrate-again-Migration Apply.log")'" >&2; exit 1; } +echo " a second apply applied nothing (the ledger holds $(psql "$pgurl" -XAtc 'select count(*) from _migrations.applied') migrations)" +key_len="$(psql "$pgurl" -XAtc "select length(value) from app_private.secrets where name = 'auth_secret'")" +[ "$key_len" = 64 ] || { echo "FAIL: the database generated no 64-character session key (got '$key_len')" >&2; exit 1; } +echo " the database generated its own session key (64 hex characters)" +run_job "$scratch/steps-migrate-plan" "$mwork" stage "$scratch/migrate-plan" +[ "$(applied "$scratch/migrate-plan-Migration Plan.log")" = "$want" ] \ + || { echo "FAIL: the pull request's offline plan did not verify every migration" >&2; exit 1; } +echo " the pull request's plan step verifies every migration's checksum offline" +unset SUPABASE_ACCESS_TOKEN SUPABASE_PROJECT_REF SUPABASE_DB_PASSWORD SUPABASE_DB_URL SUPABASE_API_URL +rm -rf "$mwork" + +# ── 4. the web lane's steps, for stage ───────────────────────────────────── +echo "── the stage web lane: install, verify-app-structure, build-app, verify-build-output, deploy-dry-run" +extract_job "$scratch/plan-pr.json" web.stage.verify-deploy "$scratch/steps-web" \ + install-workspace-dependencies verify-app-structure build-app verify-build-output deploy-dry-run +work="$prtree/.orun/runs/e2e/web.stage.verify-deploy/work" +# The job's private tree, staged as orun stages it — no build output, no +# node_modules: under stack-tectonic 0.19.0 the job installs inside it. +python3 "$here/lib/stage-job.py" "$prtree" "$work" +[ ! -e "$work/apps/web/.open-next" ] && [ -f "$work/apps/web/wrangler.jsonc" ] \ + || { echo "FAIL: the staged tree is not a fresh checkout with the committed wrangler.jsonc" >&2; exit 1; } +echo " staged: $(realpath --relative-to="$prtree" "$work") — no build output, the committed wrangler.jsonc" +# The two stage wiring documents, as the cloudflare-hyperdrive and +# cloudflare-r2 applies publish them and the lane resolves them (secretEnv +# WIRING_CLOUDFLARE_HYPERDRIVE_STAGE, WIRING_CLOUDFLARE_R2_STAGE). +hd_id="e2e0000000000000000000000000c0de" +bucket="stg-$repo-stage-e2e" +export WIRING_CLOUDFLARE_HYPERDRIVE_STAGE="{\"hyperdrive_id\":\"$hd_id\",\"hyperdrive_name\":\"stg-$repo-stage\"}" +export WIRING_CLOUDFLARE_R2_STAGE="{\"r2_bucket_name\":\"$bucket\"}" +run_job "$scratch/steps-web" "$work" stage "$scratch/web" +unset WIRING_CLOUDFLARE_HYPERDRIVE_STAGE WIRING_CLOUDFLARE_R2_STAGE +build_log="$(ls "$scratch"/web-build-app.log)" +grep -q '(Turbopack)' "$build_log" \ + || { echo "FAIL: the staged build did not run on Turbopack" >&2; grep -m3 'Next.js' "$build_log" >&2; exit 1; } +grep -q "\"id\": \"$hd_id\"" "$work/apps/web/wrangler.jsonc" && grep -q "\"bucket_name\": \"$bucket\"" "$work/apps/web/wrangler.jsonc" \ + || { echo "FAIL: build-app did not re-render wrangler.jsonc from the stage wiring documents" >&2; exit 1; } +[ "$(node -e 'const fs=require("fs");process.stdout.write(String(fs.readdirSync(process.argv[1]).length))' "$work/node_modules")" -gt 0 ] && [ ! -L "$work/node_modules" ] \ + || { echo "FAIL: the job's install did not land inside its own tree" >&2; exit 1; } +echo " the staged build ran on Turbopack, inside its own tree, bound to the stage Hyperdrive id and bucket it was handed" + +# ── 5. serve it with no model key and no AUTH_SECRET ─────────────────────── +echo "── wrangler dev over the built Worker: HYPERDRIVE on the local Postgres, BLOB on local R2, AI on the stand-in" +[ ! -e "$work/apps/web/.dev.vars" ] || { echo "FAIL: the staged tree carries a .dev.vars" >&2; exit 1; } +# The ONE change to the config the lane built with: the AI binding becomes a +# service binding to the Workers AI stand-in. Everything else is the stage +# render build-app wrote. +python3 - "$work/apps/web/wrangler.jsonc" "$work/apps/web/wrangler.e2e.jsonc" <<'PY' +import re, sys +text = open(sys.argv[1]).read() +swapped, n = re.subn(r'"ai":\s*\{\s*"binding":\s*"AI"\s*\}', + '"services": [{ "binding": "AI", "service": "fake-workers-ai", "entrypoint": "FakeAI" }]', text) +if n != 1: + sys.exit("FAIL: the built config does not bind Workers AI as `\"ai\": { \"binding\": \"AI\" }`") +open(sys.argv[2], "w").write(swapped) +PY +cp -r "$here/lib/fake-ai" "$scratch/fake-ai" +port="$(free_port)" +(cd "$work/apps/web" && CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE="$pgurl" \ + exec setsid pnpm exec wrangler dev -c wrangler.e2e.jsonc -c "$scratch/fake-ai/wrangler.jsonc" \ + --ip 127.0.0.1 --port "$port" --persist-to "$scratch/wrangler-state" \ + --show-interactive-dev-session=false) > "$scratch/dev.log" 2>&1 < /dev/null & +dev_pid=$! +url="http://127.0.0.1:$port" +for _ in $(seq 1 120); do + curl -s -o /dev/null "$url/ping" && 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/ping" || { echo "FAIL: wrangler dev never answered" >&2; tail -30 "$scratch/dev.log" >&2; exit 1; } + +echo " ▸ the component's own smokeCommand, DEPLOYED_URL=$url" +smoke="$(python3 -c "import yaml,sys;print(yaml.safe_load(open(sys.argv[1]))['spec']['parameters']['smokeCommand'])" "$tree/apps/web/component.yaml")" +DEPLOYED_URL="$url" bash -c "$smoke" || { echo "FAIL: the deploy's smoke refused the product" >&2; tail -20 "$scratch/dev.log" >&2; exit 1; } + +echo " ▸ every route the product promises, a guest's chat, an attachment, a registration" +python3 - "$url" "$values" "$pgurl" "$work/apps/web" "$scratch" <<'PY' || { echo "FAIL: the routes; wrangler dev said:" >&2; tail -60 "$scratch/dev.log" >&2; exit 1; } +import html, http.client, json, re, struct, subprocess, sys, time, urllib.error, urllib.parse +import urllib.request, uuid, zlib +base, values, pgurl, app, scratch = sys.argv[1], json.load(open(sys.argv[2])), sys.argv[3], sys.argv[4], sys.argv[5] +name = values["productname"] +problems = [] +def bad(m): problems.append(m) + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *a, **k): return None +opener = urllib.request.build_opener(NoRedirect) + +def req(path, data=None, headers=None, method=None, cookies=None): + """(status, headers as a Message, body bytes). A GET whose CONNECTION + drops (not one that answers an error) is asked again, twice at most, and + says so: `wrangler dev` on a loaded machine has dropped one. A POST is + never repeated — it would submit twice.""" + h = dict(headers or {}) + if cookies: + h["cookie"] = "; ".join(f"{k}={v}" for k, v in cookies.items()) + for attempt in range(3): + r = urllib.request.Request(path if path.startswith("http") else base + path, + data=data, headers=h, method=method) + try: + with opener.open(r, timeout=120) as resp: + return resp.status, resp.headers, resp.read() + except urllib.error.HTTPError as e: + return e.code, e.headers, e.read() + except (http.client.RemoteDisconnected, ConnectionResetError) as e: + if data is not None or attempt == 2: + raise + print(f" (GET {path}: the connection dropped ({e.__class__.__name__}) — asking again)") + time.sleep(1) + +def set_cookies(h): + out = {} + for line in h.get_all("set-cookie") or []: + k, _, v = line.split(";", 1)[0].partition("=") + out[k.strip()] = v + return out + +def location(h): + return urllib.parse.urlparse(h.get("location", "")).path + +def psql(sql): + return subprocess.run(["psql", pgurl, "-XAtc", sql], capture_output=True, text=True, check=True).stdout.strip() + +SESSION = re.compile(r"^(__Secure-)?authjs\.session-token$") +def session_of(cookies): + return next(((k, v) for k, v in cookies.items() if SESSION.match(k)), (None, None)) + +# ── what only the Worker answers, with no session ───────────────────────── +s, _, body = req("/ping") +if s != 200 or body.decode().strip() != "pong": + bad(f"/ping answered {s} {body[:40]!r}") +s, _, body = req("/api/health") +health = json.loads(body) if s == 200 else {} +if s != 200 or health.get("ok") is not True or health.get("schema") != "migrated" \ + or (health.get("models") or {}).get("default") != "@cf/moonshotai/kimi-k2.6" \ + or (health.get("models") or {}).get("gateway") != "not connected": + bad(f"/api/health answered {s} {body[:200]!r}") + +# ── a visitor with no session is signed in as a guest ───────────────────── +s, h, _ = req("/") +if s != 307 or not h.get("location", "").endswith("/api/auth/guest?redirectUrl=%2F"): + bad(f"/ with no session answered {s} → {h.get('location')}, not the guest sign-in") +s, h, _ = req("/api/auth/guest?redirectUrl=%2F") +jar = set_cookies(h) +cookie_name, token = session_of(jar) +if s not in (302, 303, 307) or location(h) != "/" or not token: + bad(f"the guest sign-in answered {s} → {h.get('location')} with cookies {sorted(jar)}") + token = None +guest_jar = {cookie_name: token} if token else {} +guest_id = None +if token: + # The session is encrypted with the key the database generated for + # itself: Auth.js's own decode, run in the app's tree, opens it with that + # key — and AUTH_SECRET is set nowhere. + key = psql("select value from app_private.secrets where name = 'auth_secret'") + script = ("import { decode } from 'next-auth/jwt';" + "const [token, secret, salt] = process.argv.slice(1);" + "const t = await decode({ token, secret, salt });" + "process.stdout.write(JSON.stringify(t));") + out = subprocess.run(["node", "--input-type=module", "-e", script, token, key, cookie_name], + cwd=app, capture_output=True, text=True) + try: + claims = json.loads(out.stdout) + except ValueError: + claims = {} + bad(f"the guest's session does not open with the database's key: {out.stderr.strip()[:200]}") + if claims and not re.match(r"^guest-\d+$", claims.get("email") or ""): + bad(f"the guest's session carries {claims!r}") + guest_id = claims.get("id") + +# ── the pages, signed in, under the product's own name ──────────────────── +s, _, page = req("/", cookies=guest_jar) +page = page.decode() +title = re.search(r"<title>(.*?)", page, re.S) +if s != 200 or not title or html.unescape(title.group(1)) != name: + bad(f"/ signed in answered {s} with {title and title.group(1)!r}, not {name!r}") +if ">Chatbot<" in page: + bad("the home page still carries the baseline's name") +# Absolute metadata URLs — the Open Graph and Twitter images — are on the +# product's own origin: this stage build's workers.dev URL, baked in by the +# lane's build command (no SITE_URL set). Not upstream's demo, not Vercel's. +origin = f"https://{values['reponame']}-web-stage.{values['subdomain']}.workers.dev" +metas = re.findall(r'<meta\s+(?:property|name)="((?:og|twitter):[a-z:_]+)"\s+content="([^"]*)"', page) +absolute = [(k, html.unescape(v)) for k, v in metas if re.match(r"https?://", html.unescape(v))] +if not any(k in ("og:image", "twitter:image") for k, _ in absolute): + bad(f"/ carries no absolute og:image or twitter:image to check: {metas[:6]}") +for k, v in absolute: + if not v.startswith(origin + "/"): + bad(f"/'s {k} is {v!r}, not on the product's origin {origin}") +if re.search(r"vercel\.(ai|app|com)|Deploy with Vercel", page, re.I): + bad("the served page links to Vercel (a demo origin or a deploy-to-Vercel call to action)") +for path, want in (("/login", 200), ("/register", 200), ("/no-such-page", 404), + ("/api/chat/00000000-0000-4000-8000-000000000000/stream", 204)): + s, _, _ = req(path, cookies=guest_jar) + if s != want: + bad(f"{path} signed in as a guest answered {s}, want {want}") + +# ── the model picker offers only what can answer: Workers AI ────────────── +s, _, body = req("/api/models", cookies=guest_jar) +models = json.loads(body) if s == 200 else {} +ids = [m["id"] for m in models.get("available") or []] +if s != 200 or not ids or not all(i.startswith("@cf/") for i in ids) or "@cf/moonshotai/kimi-k2.6" not in ids: + bad(f"/api/models answered {s} with {ids} — without a gateway key only Workers AI's models are available") + +# ── an attachment, into R2 and back ─────────────────────────────────────── +def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) +png = (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(b"\x00\xff\x00\x00")) + chunk(b"IEND", b"")) +boundary = uuid.uuid4().hex +form = (f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="dot.png"\r\n' + f"Content-Type: image/png\r\n\r\n").encode() + png + f"\r\n--{boundary}--\r\n".encode() +s, _, body = req("/api/files/upload", form, {"content-type": f"multipart/form-data; boundary={boundary}"}, + "POST", cookies=guest_jar) +uploaded = json.loads(body) if s == 200 else {} +if s != 200 or uploaded.get("contentType") != "image/png" or "/api/files/" not in uploaded.get("url", ""): + bad(f"the upload answered {s} {body[:200]!r}") +else: + path = urllib.parse.urlparse(uploaded["url"]).path + s, h, back = req(path) # public by URL, as Vercel Blob's were: no cookie + if s != 200 or back != png or h.get("content-type") != "image/png": + bad(f"reading the attachment back answered {s} {h.get('content-type')} ({len(back)} bytes)") + s, h, _ = req(path + "?download=1") + if s != 200 or "attachment" not in (h.get("content-disposition") or ""): + bad(f"the attachment's download link answered {s} {h.get('content-disposition')}") +s, _, _ = req("/api/files/upload", form, {"content-type": f"multipart/form-data; boundary={boundary}"}, "POST") +if s != 307: + bad(f"an upload with no session answered {s}, not the guest redirect") + +# ── a message to the app's own chat route, answered as a stream ─────────── +def chat(chat_id, text, model): + payload = {"id": chat_id, + "message": {"id": str(uuid.uuid4()), "parts": [{"text": text, "type": "text"}], "role": "user"}, + "selectedChatModel": model, "selectedVisibilityType": "private"} + s, h, body = req("/api/chat", json.dumps(payload).encode(), {"content-type": "application/json"}, + "POST", cookies=guest_jar) + events = [] + for line in body.decode().splitlines(): + if line.startswith("data: ") and line[6:].strip() not in ("", "[DONE]"): + try: + events.append(json.loads(line[6:])) + except ValueError: + pass + text_out = "".join(e.get("delta", "") for e in events if e.get("type") == "text-delta") + return s, h, events, text_out + +chat_id = str(uuid.uuid4()) +s, h, events, answer = chat(chat_id, "Hello there — who are you?", "@cf/moonshotai/kimi-k2.6") +deltas = [e for e in events if e.get("type") == "text-delta"] +if s != 200 or "text/event-stream" not in (h.get("content-type") or ""): + bad(f"the chat route answered {s} {h.get('content-type')}") +if answer != "Canned answer from @cf/moonshotai/kimi-k2.6: the stand-in for Workers AI streamed this." or len(deltas) < 3: + bad(f"the chat streamed {len(deltas)} delta(s): {answer!r}") +titles = [e.get("data") for e in events if e.get("type") == "data-chat-title"] +if titles != ["Canned title from glm-4.7-flash"]: + bad(f"the chat was titled {titles} — the title comes from the fast Workers AI model") +if not any(e.get("type") == "finish" for e in events): + bad("the chat stream never finished") + +# A gateway model, asked for with no gateway key: answered by the default +# Workers AI model, never failed. +s, _, _, answer2 = chat(chat_id, "And again, with a model this deployment does not have.", + "xai/grok-4.1-fast-non-reasoning") +if s != 200 or not answer2.startswith("Canned answer from @cf/moonshotai/kimi-k2.6"): + bad(f"a gateway model without its key answered {s} {answer2!r}, not the default Workers AI model") + +# ── persisted, and listed in the history ────────────────────────────────── +for _ in range(20): + rows = psql(f"""select role from "Message_v2" where "chatId" = '{chat_id}' order by "createdAt" """).split() + if rows.count("assistant") >= 2: + break + time.sleep(0.5) +if rows != ["user", "assistant", "user", "assistant"]: + bad(f"the chat's messages in the database are {rows}") +stored = psql(f"""select parts::text from "Message_v2" where "chatId" = '{chat_id}' and role = 'assistant' order by "createdAt" limit 1""") +if "Canned answer from @cf/moonshotai/kimi-k2.6" not in stored: + bad(f"the assistant's answer was not persisted: {stored[:160]!r}") +owner, chat_title = (psql(f"""select "userId" || '|' || title from "Chat" where id = '{chat_id}'""") or "|").split("|", 1) +if guest_id and owner != guest_id: + bad(f"the chat belongs to {owner!r}, not the guest {guest_id!r}") +if chat_title != "Canned title from glm-4.7-flash": + bad(f"the chat's stored title is {chat_title!r}") +s, _, body = req("/api/history?limit=20", cookies=guest_jar) +history = json.loads(body) if s == 200 else {} +listed = [(c.get("id"), c.get("title")) for c in history.get("chats") or []] +if s != 200 or (chat_id, "Canned title from glm-4.7-flash") not in listed: + bad(f"/api/history answered {s} listing {listed}") +s, _, _ = req(f"/chat/{chat_id}", cookies=guest_jar) +if s != 200: + bad(f"/chat/<id> answered {s}") +s, _, body = req(f"/api/messages?chatId={chat_id}", cookies=guest_jar) +if s == 200 and b"Canned answer" not in body: + bad("/api/messages does not return the stored answer") + +# ── a visitor registers, and signs in again ─────────────────────────────── +# Both forms submit a server action (`register`, `login`), as React's client +# does: a multipart body with the action's arguments — the previous state, +# then the form's fields, prefixed `_1_` — to the page, with its action id, +# read from the build's own manifest. +manifest = json.load(open(f"{app}/.next/server/server-reference-manifest.json")) +def action_id(export): + hits = [k for k, v in manifest["node"].items() + if v.get("exportedName") == export and v.get("filename", "").endswith("app/(auth)/actions.ts")] + if len(hits) != 1: + raise SystemExit(f"FAIL: no single `{export}` action in the build's manifest ({hits})") + return hits[0] +def act(path, export, fields, jar): + b = uuid.uuid4().hex + parts = {"0": json.dumps([{"status": "idle"}, "$K1"]), **{f"_1_{k}": v for k, v in fields.items()}} + body = "".join(f'--{b}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n' + for k, v in parts.items()) + f"--{b}--\r\n" + s, h, out = req(path, body.encode(), {"content-type": f"multipart/form-data; boundary={b}", + "next-action": action_id(export), "accept": "text/x-component", + "origin": base}, "POST", cookies=jar) + status = re.findall(r'"status":"([a-z_]+)"', out.decode(errors="replace")) + return s, set_cookies(h), status[0] if status else None + +email, password = "sam@answers.example", "correct horse battery" +s, jar, status = act("/register", "register", {"email": email, "password": password}, guest_jar) +_, reg_token = session_of(jar) +if s != 200 or status != "success" or not reg_token: + bad(f"registering answered {s} with status {status!r} and cookies {sorted(jar)}") +else: + hashed = psql(f"""select password from "User" where email = '{email}'""") + if not hashed.startswith("$2"): + bad("the registered user has no bcrypt hash") + # A registered (not guest) session: the proxy sends it away from /login. + s, h, _ = req("/login", cookies={session_of(jar)[0]: reg_token}) + if s != 307 or location(h) != "/": + bad(f"/login with the new user's session answered {s} → {h.get('location')}, not → /") +s, jar, status = act("/register", "register", {"email": email, "password": password}, guest_jar) +if status != "user_exists": + bad(f"registering the same address again answered {status!r}, not user_exists") +s, jar, status = act("/login", "login", {"email": email, "password": "not the password"}, guest_jar) +if status != "failed" or session_of(jar)[1]: + bad(f"a wrong password answered {status!r}") +s, jar, status = act("/login", "login", {"email": email, "password": password}, guest_jar) +if status != "success" or not session_of(jar)[1]: + bad(f"signing in answered {s} with status {status!r}") + +if problems: + for p in problems: + print(f" ✕ {p}", file=sys.stderr) + sys.exit(1) +print(f" /ping, /api/health; a guest signed in with the database's own key; /, /login, /register, " + f"a 404, the history, the models (Workers AI only), an attachment in R2 and back; a chat " + f"streamed through the AI binding in {len(deltas)} deltas, titled, persisted and listed, a " + f"gateway model answered by Workers AI; a registration and a sign-in — as {name!r}") +PY + +# ── 6. what Supabase's Data API would see ────────────────────────────────── +echo "── the Data API's roles (anon, authenticated) against the same database" +psql "$pgurl" -X -q -v ON_ERROR_STOP=1 -At > "$scratch/rls.out" 2> "$scratch/rls.err" <<'SQL' \ + || { echo "FAIL: the row-level security checks" >&2; cat "$scratch/rls.err" >&2; exit 1; } +SELECT 'app role: superuser=' || rolsuper || ' bypassrls=' || rolbypassrls FROM pg_roles WHERE rolname = current_user; +SELECT 'public tables without RLS: ' || count(*) FILTER (WHERE NOT c.relrowsecurity) || ' of ' || count(*) + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p'); +SELECT 'not owned by the app: ' || count(*) FILTER (WHERE pg_get_userbyid(c.relowner) <> current_user) + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p'); +SELECT 'app sees users: ' || count(*) FROM "User"; +SELECT 'app sees chats: ' || count(*) FROM "Chat"; +SELECT 'app sees messages: ' || count(*) FROM "Message_v2"; +SET ROLE anon; +SELECT 'anon sees users: ' || count(*) FROM "User"; +SELECT 'anon sees chats: ' || count(*) FROM "Chat"; +SELECT 'anon sees messages: ' || count(*) FROM "Message_v2"; +RESET ROLE; +SET ROLE authenticated; +SELECT 'authenticated sees users: ' || count(*) FROM "User"; +SELECT 'authenticated sees chats: ' || count(*) FROM "Chat"; +SELECT 'authenticated sees messages: ' || count(*) FROM "Message_v2"; +RESET ROLE; +SQL +sed 's/^/ /' "$scratch/rls.out" +grep -qx "app role: superuser=false bypassrls=false" "$scratch/rls.out" \ + && grep -qE "^public tables without RLS: 0 of [1-9][0-9]*$" "$scratch/rls.out" \ + && grep -qx "not owned by the app: 0" "$scratch/rls.out" \ + || { echo "FAIL: the app's role, the tables' owner or their row-level security is not what Supabase's would be" >&2; exit 1; } +for what in users chats messages; do + n="$(sed -n "s/^app sees $what: //p" "$scratch/rls.out")" + [ "${n:-0}" -ge 1 ] || { echo "FAIL: the flow wrote no $what the app can see" >&2; exit 1; } + for role in anon authenticated; do + grep -qx "$role sees $what: 0" "$scratch/rls.out" || { echo "FAIL: expected '$role sees $what: 0'" >&2; exit 1; } + done +done +# A write through the Data API's role is refused by row-level security, and +# app_private (the session key) is not theirs to read at all. +for role in anon authenticated; do + if psql "$pgurl" -X -q -At -c "SET ROLE $role; INSERT INTO \"User\" (email, password) VALUES ('$role@example.invalid', 'x')" > "$scratch/rls-write.log" 2>&1; then + echo "FAIL: $role wrote a user through row-level security" >&2; exit 1 + fi + grep -q "row-level security" "$scratch/rls-write.log" \ + || { echo "FAIL: $role's write was refused for another reason:" >&2; cat "$scratch/rls-write.log" >&2; exit 1; } + if psql "$pgurl" -X -q -At -c "SET ROLE $role; SELECT value FROM app_private.secrets" > "$scratch/rls-secret.log" 2>&1; then + echo "FAIL: $role read app_private.secrets" >&2; exit 1 + fi + grep -q "permission denied" "$scratch/rls-secret.log" \ + || { echo "FAIL: $role's read of app_private was refused for another reason" >&2; cat "$scratch/rls-secret.log" >&2; exit 1; } +done +echo " anon and authenticated, granted what Supabase grants them, read 0 users, chats and messages and write none; app_private is closed to them" + +echo "e2e.test.sh: ok" diff --git a/testing/fixtures/acme.json b/testing/fixtures/acme.json new file mode 100644 index 0000000..197014a --- /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 product 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 product name with an apostrophe and an", + "ampersand (both legal in the card's pattern, both special in TypeScript", + "strings, HTML and a PR title), a hyphenated repo slug that CONTAINS the", + "word `chatbot`, 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-chatbot-hq", + "productname": "Sam's Chat & Answers", + "productdomain": "chat.acme.dev", + "githuborg": "acme-inc", + "subdomain": "acme", + "orunWorkspace": "ws_0000000000000000000000000000000f", + "epicSlug": "chatbot-baselining" +} diff --git a/testing/fixtures/baseline-identity.ai-chatbot.json b/testing/fixtures/baseline-identity.ai-chatbot.json new file mode 100644 index 0000000..e342e65 --- /dev/null +++ b/testing/fixtures/baseline-identity.ai-chatbot.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": "ai-chatbot", + "pascal": "AiChatbot", + "productName": "Chatbot", + "domain": "ai-chatbot.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..1df9159 --- /dev/null +++ b/testing/leak.test.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# THE LEAK GATE — what a product carries, and what stays in the factory. +# +# A product built from this baseline is somebody's chatbot, not a copy of this +# repository. It gets the product: the app, the Terraform roots, the +# migrations, the 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 NAME one of those paths, because in the +# product they point at nothing. +# +# This asks orun to DERIVE the placement — every file every phase would write +# — and gates that set, then reads every shipped file's source. 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 (+PyYAML) + node. 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 ships with this repository's `work:` block, and the bootstrap +# strips it before the first landing (work-tree.mjs). Read the intent the +# product actually gets. +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 product's file set. +placed = sorted({f for ph in status["phases"] for f in (ph.get("missing") or [])}) +if len(placed) < 100: + sys.exit(f"only {len(placed)} files derived — the tree is not a product") + +# ── 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 product 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 product") + +# ── nothing local and nothing built ─────────────────────────────────────── +# `.env.example` and `.dev.vars.example` ship (they document the keys); a +# real `.env`, `.dev.vars` or Terraform state never does. +LOCAL = re.compile(r"(^|/)(\.env(\.[^/]*\.local|\.local)?|\.dev\.vars(\.local)?|node_modules|\.next|" + r"\.open-next|\.wrangler|\.turbo|\.orun|\.terraform|[^/]*\.tfstate(\.backup)?|" + r"next-env\.d\.ts|[^/]*\.tsbuildinfo|dist)(/|$)") +for p in placed: + if LOCAL.search(p): + bad(f"{p} would ship — a local or built file of whoever ran the bootstrap") + +# ── what a product cannot run without ───────────────────────────────────── +if "README.md" not in placed: + bad("README.md would not ship") +MUST = ( + ".github/workflows/ci.yml", ".github/workflows/checks.yml", ".rebrand/values.json", + "apps/web/component.yaml", "apps/web/lib/site.ts", "apps/web/lib/auth-secret.ts", + # The model provider: Workers AI through the AI binding, no key. + "apps/web/lib/ai/providers.ts", "apps/web/lib/ai/models.ts", + # COMMITTED, because the composition checks it exists before the build: + "apps/web/wrangler.jsonc", "apps/web/wrangler.template.jsonc", "apps/web/wiring.fixture.json", + "apps/web/app/api/health/route.ts", "apps/web/.env.example", "apps/web/.dev.vars.example", + "infra/terraform/supabase/component.yaml", "infra/terraform/supabase/terraform/main.tf", + "infra/terraform/supabase/terraform/adopt.tf", + "infra/terraform/cloudflare-hyperdrive/component.yaml", + "infra/terraform/cloudflare-hyperdrive/terraform/main.tf", + "infra/terraform/cloudflare-r2/component.yaml", + "infra/terraform/cloudflare-r2/terraform/main.tf", + "infra/db-migrate/component.yaml", + "packages/db/src/manifest.ts", "packages/db/src/migrations/020_app_secrets/up.sql", + "packages/db/src/migrations/030_row_level_security/up.sql", + "apps/web/lib/db/migrations/0001_app_secrets.sql", + "apps/web/lib/db/migrations/0002_row_level_security.sql", + "tooling/wire/live.mjs", "tooling/migrations/manifest.mjs", + "tests/web/component.yaml", "tests/db/component.yaml", +) +for must in MUST: + if must not in placed: + bad(f"{must} would not ship, and a product needs it") + +# ── every shipped file, read for the factory's paths ────────────────────── +# A file that ships naming `testing/`, `.baseline/` or `repo-blueprint` +# points the product's reader — or its CI — at something it does not have. +# Each placed path is mapped back to the source its module copies from. +bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text()) +copies = [(m["to"].rstrip("/"), m["from"].rstrip("/")) for m in bp.get("modules") or [] + if m.get("mode") == "copy"] +def source_of(dest): + for to, frm in sorted(copies, key=lambda c: -len(c[0])): + if dest == to: + return root / frm + if dest.startswith(to + "/"): + return root / frm / dest[len(to) + 1:] + return None +FACTORY_PATH = re.compile(r"repo-blueprint|(?<![\w./-])(?:testing|specs|tasks|\.baseline|docs/phases)/" + r"|BOOTSTRAP\.md|tooling/(?:rebrand|bootstrap)\b") +scanned = 0 +for p in placed: + src = stripped_intent if p == "intent.yaml" else source_of(p) + if src is None or not src.is_file(): + continue + try: + text = src.read_text() + except UnicodeDecodeError: + continue + scanned += 1 + for n, line in enumerate(text.splitlines(), 1): + m = FACTORY_PATH.search(line) + if m: + bad(f"{p}:{n} names the factory's {m.group(0)!r}, which the product does not have: {line.strip()[:80]}") + +# ── 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 product 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", + "apps/web/README.md": "apps/web/README.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 product about the factory: {line.strip()[:80]}") + +if problems: + print("FAIL: the product 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; {scanned} text files read") +print(f" ai/context is exactly {len(ALLOWED_AI)} declared file(s); none of the " + f"{len(NEVER)} factory paths ships or is named by a shipped file; nothing local or " + f"built; no provenance prose") +PY + +echo "leak.test.sh: ok" diff --git a/testing/lib/bootstrap.sh b/testing/lib/bootstrap.sh new file mode 100755 index 0000000..b4a75f7 --- /dev/null +++ b/testing/lib/bootstrap.sh @@ -0,0 +1,63 @@ +#!/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 product 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 retouch marker, the rebrand, the re-tenant, the +# work-tree strip, the deferrals and their restore, the lockfile, the +# deployment-docs render — runs exactly as declared. +# +# The output directory starts EMPTY, as a real one does: no discovery root is +# made here, so a phase that leaves orun's repo-scale gate one to find (apps/, +# infra/, packages/, tests/) fails here as it would live. +# +# 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" "$logs" + + 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/fake-ai/worker.js b/testing/lib/fake-ai/worker.js new file mode 100644 index 0000000..d298588 --- /dev/null +++ b/testing/lib/fake-ai/worker.js @@ -0,0 +1,57 @@ +// A DETERMINISTIC STAND-IN FOR WORKERS AI, for testing/e2e.test.sh only. +// +// The product's chat, titles and artifact tools call Workers AI through the +// Worker's `AI` binding (apps/web/lib/ai/providers.ts, via +// workers-ai-provider): `env.AI.run(model, inputs, options)`, answered with a +// JSON body or — when `inputs.stream` is true — a server-sent-event stream of +// `data: {"response": "<delta>"}` events ending in `data: [DONE]`. Workers AI +// has no local mode and cannot be called offline, so under `wrangler dev` the +// e2e points the `AI` binding at this Worker instead (a service binding to its +// `FakeAI` entrypoint, an RPC method with the binding's own shape), and it +// answers every call with canned text that names the model it was asked for. +// What that proves is the app's half — the route, the provider, the stream, +// the persistence — not that a real model answers: that is only verified live. +import { WorkerEntrypoint } from "cloudflare:workers"; + +const calls = []; + +function sse(text) { + const enc = new TextEncoder(); + // A few words per event, as a model streams them. + const words = text.split(/(?<= )/); + return new ReadableStream({ + start(controller) { + for (const w of words) { + controller.enqueue(enc.encode(`data: ${JSON.stringify({ response: w })}\n\n`)); + } + controller.enqueue( + enc.encode(`data: ${JSON.stringify({ response: "", usage: { prompt_tokens: 7, completion_tokens: words.length, total_tokens: 7 + words.length } })}\n\n`), + ); + controller.enqueue(enc.encode("data: [DONE]\n\n")); + controller.close(); + }, + }); +} + +export class FakeAI extends WorkerEntrypoint { + async run(model, inputs) { + const tools = Array.isArray(inputs?.tools) ? inputs.tools.map((t) => t?.function?.name).filter(Boolean) : []; + calls.push({ model, stream: Boolean(inputs?.stream), tools }); + const short = String(model).split("/").pop(); + if (inputs?.stream) { + return sse(`Canned answer from ${model}: the stand-in for Workers AI streamed this.`); + } + return { + response: `Canned title from ${short}`, + usage: { prompt_tokens: 7, completion_tokens: 4, total_tokens: 11 }, + }; + } +} + +export default { + // What the stand-in was asked, for the e2e to read back (it is reachable + // only through the app's service binding, so this is for debugging). + fetch() { + return Response.json(calls); + }, +}; diff --git a/testing/lib/fake-ai/wrangler.jsonc b/testing/lib/fake-ai/wrangler.jsonc new file mode 100644 index 0000000..3885fe1 --- /dev/null +++ b/testing/lib/fake-ai/wrangler.jsonc @@ -0,0 +1,7 @@ +// The Workers AI stand-in's own config, run beside the product's Worker in +// one `wrangler dev` session by testing/e2e.test.sh. Never deployed. +{ + "name": "fake-workers-ai", + "main": "worker.js", + "compatibility_date": "2026-10-01" +} diff --git a/testing/lib/fake-supabase-api.py b/testing/lib/fake-supabase-api.py new file mode 100755 index 0000000..1750e86 --- /dev/null +++ b/testing/lib/fake-supabase-api.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""A stand-in for the ONE Supabase Management API endpoint the migration +runner uses, over a local Postgres. + + fake-supabase-api.py <port> <postgres-url> [--ref <project-ref>] + +packages/db's runner applies migrations through +`POST /v1/projects/<ref>/database/query` with `{"query": "<sql>"}` and reads +back the rows of the last statement as a JSON array; an error is a non-2xx +answer whose JSON `message` carries Postgres's own text (the runner treats +"does not exist" on its ledger as a first run). This serves exactly that, by +handing the SQL to `psql`, so the e2e can run the runner's real `apply` — +checksums, ledger, idempotent re-run — against the database the Worker then +reads. Only the bearer token's presence is checked; nothing else of the API +exists here. +""" +import http.server +import json +import re +import subprocess +import sys + +PORT = int(sys.argv[1]) +DB = sys.argv[2] +REF = sys.argv[sys.argv.index("--ref") + 1] if "--ref" in sys.argv else None +ROUTE = re.compile(r"^/v1/projects/([a-z0-9]+)/database/query$") + + +def psql(sql: str) -> subprocess.CompletedProcess: + return subprocess.run( + ["psql", DB, "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1"], + input=sql, capture_output=True, text=True, + ) + + +class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, fmt, *args): # quiet: the e2e prints what matters + pass + + def answer(self, status: int, body) -> None: + data = json.dumps(body).encode() + self.send_response(status) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_POST(self): + m = ROUTE.match(self.path) + if not m or (REF and m.group(1) != REF): + return self.answer(404, {"message": f"no such endpoint {self.path}"}) + if not (self.headers.get("authorization") or "").startswith("Bearer "): + return self.answer(401, {"message": "missing bearer token"}) + query = json.loads(self.rfile.read(int(self.headers.get("content-length") or 0)))["query"] + # A read returns its rows; anything else runs as written and returns + # none, as the real endpoint does for DDL. + if re.match(r"^\s*select\b", query, re.I): + run = psql(f"select coalesce(json_agg(t), '[]'::json) from ({query.rstrip().rstrip(';')}) t;") + else: + run = psql(query) + if run.returncode != 0: + return self.answer(400, {"message": run.stderr.strip()}) + out = run.stdout.strip() + return self.answer(201, json.loads(out) if out.startswith("[") else []) + + +http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever() diff --git a/testing/lib/local-postgres.sh b/testing/lib/local-postgres.sh new file mode 100755 index 0000000..adcd5d5 --- /dev/null +++ b/testing/lib/local-postgres.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# A throwaway Postgres for the e2e — the database a Supabase project would be, +# with Supabase's roles — on a random local port. Sourced. +# +# pg_up <dir> <port> start it in <dir> — a fresh `mktemp -d`, which it +# takes over — and print the URL the app and the +# migrations use (role `postgres`) on stdout +# pg_down <dir> stop it +# +# THE ROLES ARE SUPABASE'S, because what is tested here is whether the app +# still works once every table in `public` has row-level security: +# supabase_admin the bootstrap superuser (Supabase's own) +# postgres LOGIN, NOT a superuser and WITHOUT BYPASSRLS: what the +# app connects as through Hyperdrive and what db-migrate +# runs as, so it owns the tables — and ownership is the only +# thing that exempts it from row-level security here +# anon, authenticated +# what Supabase's Data API runs requests as, with the grants +# Supabase gives them on `public` by default (every table the +# `postgres` role creates), and `postgres` a member of both +# so a test can `SET ROLE` to them +# +# Postgres refuses to run as root, so when the caller is root the server runs +# as the `postgres` system user (Debian's packages create one). Trust auth on +# 127.0.0.1 only: a URL's password is ignored, which is what lets the same +# `postgres://postgres:postgres@…` shape the wrangler config uses reach it. +# +# Needs: a PostgreSQL server install (initdb, pg_ctl) — /usr/lib/postgresql/*/bin +# is searched when they are not on PATH — and psql. + +pg_bin() { + local b + if command -v initdb >/dev/null 2>&1; then dirname "$(command -v initdb)"; return; fi + for b in /usr/lib/postgresql/*/bin; do [ -x "$b/initdb" ] && { echo "$b"; return; }; done + return 1 +} + +pg_as() { # run a command as the user that owns the cluster + if [ "$(id -u)" = 0 ]; then runuser -u postgres -- "$@"; else "$@"; fi +} + +pg_up() { + local dir="$1" port="$2" bin + bin="$(pg_bin)" || { echo "pg_up: no PostgreSQL server binaries (initdb, pg_ctl)" >&2; return 1; } + mkdir -p "$dir" + [ "$(id -u)" = 0 ] && chown postgres "$dir" && chmod 700 "$dir" + pg_as "$bin/initdb" -D "$dir/data" -U supabase_admin --auth=trust -E UTF8 >"$dir/initdb.log" 2>&1 \ + || { cat "$dir/initdb.log" >&2; return 1; } + pg_as "$bin/pg_ctl" -D "$dir/data" -l "$dir/server.log" -w -t 60 \ + -o "-p $port -c listen_addresses=127.0.0.1 -k $dir -c fsync=off" start >/dev/null \ + || { cat "$dir/server.log" >&2; return 1; } + psql "postgres://supabase_admin@127.0.0.1:$port/postgres" -X -q -v ON_ERROR_STOP=1 >"$dir/roles.log" 2>&1 <<'SQL' \ + || { cat "$dir/roles.log" >&2; return 1; } +CREATE ROLE postgres LOGIN NOSUPERUSER NOBYPASSRLS CREATEDB CREATEROLE; +GRANT CREATE ON DATABASE postgres TO postgres; +GRANT USAGE, CREATE ON SCHEMA public TO postgres; +CREATE ROLE anon NOLOGIN NOINHERIT; +CREATE ROLE authenticated NOLOGIN NOINHERIT; +GRANT anon, authenticated TO postgres; +GRANT USAGE ON SCHEMA public TO anon, authenticated; +ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO anon, authenticated; +ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO anon, authenticated; +SQL + echo "postgres://postgres:postgres@127.0.0.1:$port/postgres" +} + +pg_down() { + local dir="$1" bin + bin="$(pg_bin)" || return 0 + [ -d "$dir/data" ] && pg_as "$bin/pg_ctl" -D "$dir/data" -m immediate stop >/dev/null 2>&1 || true +} 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..d6a61e3 --- /dev/null +++ b/testing/phases.test.sh @@ -0,0 +1,373 @@ +#!/usr/bin/env bash +# The phases in `repo-blueprint.yaml` must be the phases the bootstrap runs, +# placing what they are meant to place, in the order their hooks must run, +# saying what they are, and naming only what the engine can resolve. +# +# TWO PHASES, ONE LANDING THAT DEPLOYS. `01-product` places every module the +# blueprint declares — root files, workflows, tooling, the Supabase, +# Hyperdrive and R2 roots, the migrations, the app and the tests — and lands +# them as ONE pull request; the convergence after that merge provisions and deploys it +# all, the order carried by the components' enforced `dependsOn` (placement +# proves it on the product's own plan). `02-docs` places nothing: it records +# the deployment and restores what 01-product deferred. +# +# The partition is written down a second time below on purpose: a module that +# drifts out of 01-product, or a phase that grows back between the two, is a +# change to how a product is built and has to be argued in the diff that edits +# both places. The hook ORDER is written down too: every step of the identity +# chain depends on the one before it (rebrand reads `git ls-files`, the verify +# reads the restaged tree, the credentials are minted after the link and +# before the landing whose convergence uses them), and a reorder fails live. +# +# 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") + +PRODUCT = ["ai-deployment", "ai-operations", "cloudflare-hyperdrive", "cloudflare-r2", "db", "db-migrate", + "db-tests", "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", "supabase", "tooling-eslint", + "tooling-migrations", "tooling-tsconfig", "tooling-wire", "vscode", "web", + "web-tests"] +PARTITION = {"01-product": PRODUCT, "02-docs": []} +HOOK_ONLY = {"02-docs"} +# The phase that DEPLOYS, and so must give a re-run something to land. +DEPLOYS = {"01-product"} + +# The post hooks, in the order they must run (the brief's chain): the +# re-run marker and the git index; the rebrand and the re-tenant; the three +# rewrites a product needs before it lands; the restage and the verify; the +# lockfile; the repository and its link; one brokered reconcile per key; +# the landing. `secret-*` stands for the reconcile hooks, checked below. +POST_ORDER = { + "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"], +} +# The scripts behind the run: hooks that rewrite intent.yaml, with the mode +# each must be called in. +RUNS = { + ("01-product", "work-tree"): ("tooling/bootstrap/work-tree.mjs", "--strip"), + ("01-product", "promotion"): ("tooling/bootstrap/promotion.mjs", "--defer"), + ("01-product", "dev-lanes"): ("tooling/bootstrap/dev-lanes.mjs", "--defer"), + ("02-docs", "promotion"): ("tooling/bootstrap/promotion.mjs", "--restore"), + ("02-docs", "dev-lanes"): ("tooling/bootstrap/dev-lanes.mjs", "--restore"), + ("02-docs", "render"): ("hooks/render-deployment-docs.sh", None), +} +AWAIT_ORDER = {"01-product": ["orun.run/watch@", "orun.secrets/exists@", "orun.http/probe@"], + "02-docs": ["orun.http/probe@"]} + +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 m in sorted(declared - set(PRODUCT)): + bad(f"module {m} is declared and 01-product does not place it — every module lands in the one landing") +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 ──────────────── +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") + +# ── 01-product asks for every connection it mints from, before it creates anything +probe = ((by_name.get("01-product") or {}).get("requires") or {}).get("probe") or [] +doctor = [h for h in probe if (h.get("uses") or "").startswith("orun.doctor/check@")] +want_providers = {"github", "cloudflare", "supabase"} +if not doctor or set((doctor[0].get("with") or {}).get("providers") or []) != want_providers: + bad(f"01-product must probe {sorted(want_providers)} with orun.doctor/check@v1 before it places") +elif (doctor[0].get("with") or {}).get("githubOwner") != "{{ .inputs.githuborg }}": + bad("01-product's doctor probe must wait for the GitHub App on the repository's owner") + +# ── 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 []) + +# ── the hook chain, in order ────────────────────────────────────────────── +for name, want in POST_ORDER.items(): + p = by_name.get(name) + if not p: + continue + post = (p.get("hooks") or {}).get("post") or [] + ids = [h.get("id") for h in post] + folded = [] + for i in ids: + tok = "secret-*" if (i or "").startswith("secret-") else i + if not folded or folded[-1] != tok: + folded.append(tok) + if folded != want: + bad(f"phase {name}'s post hooks run {ids}; the chain is {want}") + for h in post: + if (h.get("id") or "").startswith("secret-") and not (h.get("uses") or "").startswith("orun.integrations/reconcile@"): + bad(f"phase {name} hook {h.get('id')} is not an orun.integrations/reconcile@v1") + if (h.get("uses") or "").startswith("orun.integrations/reconcile@"): + keys = (h.get("with") or {}).get("keys") or [] + if len(keys) != 1: + bad(f"phase {name} hook {h.get('id')} reconciles {keys} — one key per hook, one scope per key") + for (ph, hid), (script, mode) in RUNS.items(): + if ph != name: + continue + hook = next((h for h in post if h.get("id") == hid), None) + argv = " ".join((hook or {}).get("run") or []) + if script not in argv or (mode and mode not in argv): + bad(f"phase {name} hook {hid} must run {script} {mode or ''}".rstrip()) +for name, want in AWAIT_ORDER.items(): + awaits = ((by_name.get(name) or {}).get("hooks") or {}).get("await") or [] + got = [h.get("uses") or "" for h in awaits] + if len(got) != len(want) or not all(g.startswith(w) for g, w in zip(got, want)): + bad(f"phase {name}'s await hooks are {got}; they must be {want} (in that order)") + +# ── the await checks what the infrastructure publishes, on stage and prod ─ +# Each infra component's `secretOutputs` is what its apply lease-publishes; +# the landing's `orun.secrets/exists@v1` must ask for exactly those keys — +# every WIRING_* document (Hyperdrive's and R2's) and the Supabase project's +# credentials — on the environments that apply them. Derived, so a root that +# starts publishing a key the await does not ask for fails here. +published = set() +for comp in sorted(root.glob("infra/**/component.yaml")): + params = ((yaml.safe_load(comp.read_text()) or {}).get("spec") or {}).get("parameters") or {} + for pair in str(params.get("secretOutputs") or "").split(","): + if "=" in pair: + published.add(pair.split("=", 1)[0].strip()) +if not published: + bad("no infra component declares secretOutputs — this check has gone blind") +awaits = ((by_name.get("01-product") or {}).get("hooks") or {}).get("await") or [] +exists = [h for h in awaits if (h.get("uses") or "").startswith("orun.secrets/exists@")] +if exists: + w = exists[0].get("with") or {} + if set(w.get("keys") or []) != published: + bad(f"01-product awaits secrets {sorted(w.get('keys') or [])}; the infrastructure " + f"publishes {sorted(published)}") + if sorted(w.get("environments") or []) != ["prod", "stage"]: + bad(f"01-product awaits the published secrets on {w.get('environments')}, not stage and prod") + if w.get("project") != "{{ .inputs.reponame }}": + bad("01-product awaits the published secrets in another project than the product's") +for name in names: + for h in ((by_name[name].get("hooks") or {}).get("await") or []): + if (h.get("uses") or "").startswith("orun.http/probe@"): + urls = (h.get("with") or {}).get("urls") or [] + # `/ping` and `/api/health`, not `/`: every page of the chatbot + # sends a visitor without a session to the guest sign-in (a 307), + # and the probe wants a 200. `/ping` is answered by the Worker's + # proxy; `/api/health` by the Worker over its database. + for env in ("stage", "prod"): + base = f"https://{{{{ .inputs.reponame }}}}-web-{env}.{{{{ .inputs.subdomain }}}}.workers.dev" + for want in (base + "/ping", base + "/api/health"): + if want not in urls: + bad(f"phase {name}'s probe does not ask {want}") + +# ── 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)") + +# ── 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}") +for h in run_hooks + [x for p in phases for x in hooks_of(p)]: + if (h.get("with") or {}).get("prefix") not in (None, "BASE"): + bad(f"hook {h.get('id')} files its task under prefix {h['with']['prefix']}, not BASE") + +# ── 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) +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 (all in 01-product), {len(HOOK_ONLY)} hook-only — in execution order") +print(f" the hook chain in order; 01-product awaits {sorted(published)} on stage and prod") +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..ab7a839 --- /dev/null +++ b/testing/placement.test.sh @@ -0,0 +1,431 @@ +#!/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, each finished by the blueprint's OWN `run:` hooks (the retouch +# marker, 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, carrying nothing of +# the factory and naming none of it, re-tenanted, its gates restored, its +# record rendered, its wrangler config committed; +# 4. what the product's own CI does with the 01-product merge: `orun plan +# --trigger github-push-main` over exactly that commit. Per environment: +# supabase → cloudflare-hyperdrive → db-migrate → web, and +# cloudflare-r2 → web, every edge ENFORCED, read off the plan's own +# dependency graph; stage and prod side +# by side; nothing on dev; every brokered key the plan resolves minted by +# the blueprint, and every other the infrastructure publishes. The same +# commit planned as a pull request: every one of those edges advisory; +# 5. after 02-docs: prod waits on stage again and dev verifies main again; +# 6. a `--resume` over the finished product places nothing and un-brands +# nothing. +# +# testing/e2e.test.sh goes on from here: it installs, migrates, builds and +# serves the product, signs a guest in and chats on it. +# +# Needs: orun, node, pnpm, python3 (+PyYAML), git. No credential. The pnpm +# lockfile confirmation 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 + +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" +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 100 ] || fail "only $n files placed — that is not a product" +[ "$fails" -eq 0 ] && echo " $n files placed into an empty directory; 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")) + +# NUL-separated: the template ships an image whose name has spaces in it. +tracked = [f for f in subprocess.run(["git", "ls-files", "-z"], cwd=tree, capture_output=True, text=True, + check=True).stdout.split("\0") if f] + +# 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)(/|$)", 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 tracked file names one of the factory's paths. +FACTORY_PATH = re.compile(r"repo-blueprint|(?<![\w./-])(?:testing|specs|tasks|\.baseline|docs/phases)/" + r"|BOOTSTRAP\.md|tooling/(?:rebrand|bootstrap)\b") +for p in tracked: + try: + text = (tree / p).read_text() + except (UnicodeDecodeError, IsADirectoryError): + continue + for n, line in enumerate(text.splitlines(), 1): + if FACTORY_PATH.search(line): + bad(f"{p}:{n} names the factory: {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 product {name!r}") +comp = yaml.safe_load((tree / "apps/web/component.yaml").read_text())["spec"] +params = comp["parameters"] +if params["workerName"] != f"{repo}-web": + bad(f"workerName is {params['workerName']}, not {repo}-web") +if params["workersDevSubdomain"] != sub: + bad(f"workersDevSubdomain is {params['workersDevSubdomain']}, not {sub}") +if json.loads((tree / "package.json").read_text())["name"] != repo: + bad("package.json is not named for the product") +for comp_path in ("apps/web", "infra/terraform/supabase", "infra/terraform/cloudflare-hyperdrive", + "infra/terraform/cloudflare-r2", "infra/db-migrate"): + doc = yaml.safe_load((tree / comp_path / "component.yaml").read_text())["spec"] + for k, ref in (doc.get("secretEnv") or {}).items(): + if not ref.startswith(f"secret://{ws}/{repo}/"): + bad(f"{comp_path} {k} resolves from {ref} — not the product's workspace and project") + +# The upstream template's own repository link survives the rename. +for rel in ("README.md", "apps/web/README.md"): + if "https://github.com/vercel/ai-chatbot" not in (tree / rel).read_text(): + bad(f"{rel}'s link to the upstream template was renamed") + +# The wrangler config is committed, and is the fixture render of the +# (rebranded) template — the composition checks it exists before the build. +if "apps/web/wrangler.jsonc" not in tracked: + bad("apps/web/wrangler.jsonc is not committed — verify-app-structure would fail in every lane") +else: + rendered = tree / "wrangler.check.jsonc" + subprocess.run(["node", "tooling/wire/render.mjs", "--template", "apps/web/wrangler.template.jsonc", + "--out", str(rendered), "--map", "apps/web/wiring.fixture.json", "--env", "stage"], + cwd=tree, check=True, capture_output=True) + if rendered.read_text() != (tree / "apps/web/wrangler.jsonc").read_text(): + bad("apps/web/wrangler.jsonc is not the fixture render of its template") + if f'"name": "{repo}-web"' not in rendered.read_text() or f'"bucket_name": "stg-{repo}-stage"' not in rendered.read_text(): + bad("the committed wrangler config does not carry the product's Worker name and bucket") + if '"binding": "AI"' not in rendered.read_text(): + bad("the committed wrangler config does not bind Workers AI") + rendered.unlink() + +# The intent: re-tenanted, no work tree, both gates back. +intent_text = (tree / "intent.yaml").read_text() +intent = yaml.safe_load(intent_text) +if intent["metadata"]["name"] != repo: + bad(f"intent metadata.name is {intent['metadata']['name']}") +if intent["execution"]["state"]["workspace"] != 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}") + if intent["environments"][env]["parameterDefaults"]["terraform"]["repo"] != repo: + bad(f"environments.{env} names the Supabase project, Hyperdrive config and bucket after another 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: a redeploy marker on every +# component 01-product's contract names, the record rendered by 02-docs. +contract = yaml.safe_load((root / ".baseline/tasks/01-product.TaskContract.yaml").read_text()) +for comp_name in contract["spec"]["affects"]: + hits = [p for p in tracked if p.endswith("component.yaml") + and (yaml.safe_load((tree / p).read_text()) or {}).get("metadata", {}).get("name") == comp_name] + if len(hits) != 1 or not re.search(r"^# orun: redeploy 01-product \S+$", (tree / hits[0]).read_text(), re.M): + bad(f"component {comp_name} 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 \ + or "/api/health" not in dep or "## Models" 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 product 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, re-tenanted, naming nothing of the factory, 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)" +# A clone, so the bootstrap's own tree is never moved: at the 01-product +# commit (promotion and dev's push lanes still deferred), with an empty branch +# beside it to plan a pull request against. Named as the repository is. +mkdir -p "$scratch/at-01" +git clone -q "$tree" "$scratch/at-01/$repo" +at01="$scratch/at-01/$repo" +git -C "$at01" checkout -q --orphan empty +git -C "$at01" rm -rqf . +git -C "$at01" -c user.email=t@example.invalid -c user.name=t commit -qm empty --allow-empty +git -C "$at01" checkout -q "$s01" +(cd "$at01" && 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 merge is the repository's first content: every file is new, so the +# push's `--changed` set is every component — the full plan. +(cd "$at01" && orun plan --intent intent.yaml --trigger github-push-main --output "$scratch/plan-main.json") > "$scratch/plan-main.log" 2>&1 \ + || { fail "orun plan (push to main) failed in the product at 01-product"; tail -15 "$scratch/plan-main.log" >&2; } +(cd "$at01" && orun plan --intent intent.yaml --trigger github-pull-request --base empty --head HEAD \ + --output "$scratch/plan-pr.json") > "$scratch/plan-pr.log" 2>&1 \ + || { fail "orun plan (pull request) failed in the product at 01-product"; tail -15 "$scratch/plan-pr.log" >&2; } + +# The PRODUCT's CI plans with its own lane pin (ci.yml), not with the orun +# that places the blueprint: per-edge `modeRules` — advisory on a pull +# request — are read by that pin, and the bootstrap floor (v2.58.11) plans +# them enforced everywhere. So the pull-request half below holds only when +# this orun is at least the product's pin; e2e.test.sh, pinned at the lane +# version, asserts it again. +lane_pin="$(sed -n 's/^ *version: *v\([0-9.]*\) *$/\1/p' "$tree/.github/workflows/ci.yml" | head -1)" +this_orun="$(orun --version | sed -n 's/.*version v\{0,1\}\([0-9.]*\).*/\1/p' | head -1)" + +python3 - "$scratch/plan-main.json" "$scratch/plan-pr.json" "$values" "$root" "$at01" "$this_orun" "$lane_pin" <<'PLAN' || fails=$((fails + 1)) +import json, pathlib, sys +import yaml +plan, pr = json.load(open(sys.argv[1])), json.load(open(sys.argv[2])) +values, root, tree = json.load(open(sys.argv[3])), pathlib.Path(sys.argv[4]), pathlib.Path(sys.argv[5]) +this_orun, lane_pin = (tuple(int(x) for x in v.split(".")) for v in sys.argv[6:8]) +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"]} +ids = {j["id"]: j for j in plan["jobs"]} + +CHAIN = ["supabase", "cloudflare-hyperdrive", "db-migrate", "web"] +PROFILE = {"supabase": "terraform.apply", "cloudflare-hyperdrive": "terraform.apply", + "cloudflare-r2": "terraform.apply", + "db-migrate": "db-migrate.apply", "web": "cloudflare-workers-assets-turbo.deploy", + "db": "turbo-package.quick-check"} +want = {(c, e) for c in PROFILE for e in ("stage", "prod")} +if set(jobs) != want: + bad(f"the 01-product merge plans {sorted(jobs)}; it must plan {sorted(want)} — and nothing on dev") +for (comp, env), j in jobs.items(): + if comp in PROFILE and j["profile"] != PROFILE[comp]: + bad(f"{comp}@{env} plans {j['profile']}, not {PROFILE[comp]}") + if j.get("dependencyMode") != "enforced": + bad(f"{j['id']} plans dependencyMode {j.get('dependencyMode')}, not enforced") + for dep in j.get("dependsOn") or []: + if ids[dep]["environment"] != j["environment"]: + bad(f"{j['id']} waits on {dep} — during the bootstrap stage and prod run side by side") + +# THE ORDER, read off the plan's own graph: each link of the chain is an +# ENFORCED edge (`dependsOn`, not `advisoryDependsOn`), and the depth of each +# job — the longest chain of enforced edges into it — puts the four on four +# different levels, in order. +depth = {} +def level(jid): + if jid not in depth: + depth[jid] = 1 + max((level(d) for d in ids[jid].get("dependsOn") or []), default=-1) + return depth[jid] +for env in ("stage", "prod"): + by = {c: jobs.get((c, env)) for c in CHAIN} + if not all(by.values()): + continue + for a, b in zip(CHAIN, CHAIN[1:]): + if by[a]["id"] not in (by[b].get("dependsOn") or []): + bad(f"{b}@{env} does not wait on {a}@{env} — the order is {' → '.join(CHAIN)}") + for dep in ("cloudflare-hyperdrive", "cloudflare-r2", "db-migrate"): + dj = jobs.get((dep, env)) + if not dj or dj["id"] not in (by["web"].get("dependsOn") or []): + bad(f"web@{env} reads {dep}'s output and does not wait on it") + r2 = jobs.get(("cloudflare-r2", env)) + if r2 and (r2.get("dependsOn") or []): + bad(f"cloudflare-r2@{env} waits on {r2['dependsOn']} — the bucket needs nothing first") + order = sorted(CHAIN, key=lambda c: level(by[c]["id"])) + levels = [level(by[c]["id"]) for c in order] + if order != CHAIN or len(set(levels)) != len(levels): + bad(f"{env} converges {order} at levels {levels}; it must be {' → '.join(CHAIN)}, one after another") + else: + print(f" {env}, enforced: " + " → ".join(order) + ", and cloudflare-r2 → web") + +# …and on a pull request every one of those edges is ADVISORY: nothing is +# applied or deployed there, so nothing waits. +prj = {(j["component"], j["environment"]): j for j in pr["jobs"]} +pr_edges = this_orun >= lane_pin +for env in ("stage", "prod"): + for a, b in (list(zip(CHAIN, CHAIN[1:])) + [("cloudflare-r2", "web")]) if pr_edges else (): + jb, ja = prj.get((b, env)), prj.get((a, env)) + if not ja or not jb: + bad(f"the pull-request plan has no {a}@{env} or {b}@{env}") + continue + if ja["id"] in (jb.get("dependsOn") or []): + bad(f"on a pull request {b}@{env} still waits on {a}@{env} — the edge must be advisory there") + if ja["id"] not in (jb.get("advisoryDependsOn") or []): + bad(f"on a pull request {b}@{env} does not name {a}@{env} as advisory") + for comp, prof in (("supabase", "plan-only"), ("cloudflare-hyperdrive", "plan-only"), + ("cloudflare-r2", "plan-only"), ("db-migrate", "plan"), ("web", "verify")): + j = prj.get((comp, env)) + if j and not j["profile"].endswith("." + prof): + bad(f"on a pull request {comp}@{env} plans {j['profile']}, which may mutate") +if pr_edges: + print(" pull request: the same edges, advisory; plan-only, plan and verify — nothing applied") +else: + print(f" pull request: plan-only, plan and verify — nothing applied (the edges' advisory mode is " + f"read by the product's lane pin v{'.'.join(map(str, lane_pin))}; this orun is " + f"v{'.'.join(map(str, this_orun))} — not checked here)") + +# Every brokered key the plan resolves is one the blueprint mints, and every +# other key it resolves is one an apply publishes — nothing else. Derived +# from the product's own plan (component secretEnv AND the compositions' +# bindings), the blueprint's reconcile hooks and the components' secretOutputs. +bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text()) +minted = {k for p in bp["phases"] for slot in (p.get("hooks") or {}).values() for h in slot + if (h.get("uses") or "").startswith("orun.integrations/reconcile@") for k in h["with"]["keys"]} +published = set() +for comp in tree.glob("infra/**/component.yaml"): + so = str(((yaml.safe_load(comp.read_text()) or {}).get("spec") or {}).get("parameters", {}).get("secretOutputs") or "") + published |= {pair.split("=", 1)[0] for pair in so.split(",") if "=" in pair} +resolved = set() +for (comp, env), j in jobs.items(): + for r in j.get("secretRefs") or []: + ref = r["ref"] + resolved.add(ref.rsplit("/", 1)[1]) + if not ref.startswith(f"secret://{ws}/"): + bad(f"{comp}@{env} resolves {r['asEnv']} from {ref} — not the product's workspace") + if f"/{repo}/" not in ref and f"project:{repo}/" not in ref: + bad(f"{comp}@{env} resolves {r['asEnv']} from {ref} — not the product's project") +if resolved - published != minted: + bad(f"the plan resolves brokered keys {sorted(resolved - published)}; the blueprint mints {sorted(minted)}") +if not published <= resolved: + bad(f"the infrastructure publishes {sorted(published - resolved)} and nothing reads it") +print(f" the plan resolves exactly the {len(minted)} keys the blueprint mints, " + f"and reads all {len(published)} the applies publish") + +# The deploy itself: the structure check, the live wiring render, the +# Worker's name, the smoke. +for env in ("stage", "prod"): + j = jobs.get(("web", env)) + if not j: + continue + steps = {s["id"]: s.get("run") or "" for s in j["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 'test -f "wrangler.jsonc"' not in steps.get("verify-app-structure", ""): + bad(f"web@{env} checks another config before the build: {steps.get('verify-app-structure','').strip()}") + if "tooling/wire/live.mjs" not in steps.get("build-app", "") or "cloudflare-hyperdrive,cloudflare-r2" not in steps.get("build-app", ""): + bad(f"web@{env} does not render its wrangler config from the Hyperdrive and R2 wiring before it builds") + if f'NEXT_PUBLIC_SITE_URL="${{SITE_URL:-https://{repo}-web-${{ORUN_ENVIRONMENT}}.{sub}.workers.dev}}"' not in steps.get("build-app", ""): + bad(f"web@{env} does not bake the product's own origin into its build (NEXT_PUBLIC_SITE_URL)") + if f'EFFECTIVE_WORKER_NAME="{repo}-web-{env}"' not in steps.get("deploy", ""): + bad(f"web@{env} deploys a Worker not named {repo}-web-{env}") + if "/api/health" not in steps.get("smoke", "") or f'export WORKERS_DEV_SUBDOMAIN="{sub}"' not in steps.get("smoke", ""): + bad(f"web@{env}'s smoke does not check the product's own /api/health") + +if problems: + for p in problems: + print(f" ✕ {p}", file=sys.stderr) + sys.exit(1) +print(" stage and prod side by side; nothing on dev; the Worker, its wiring render and its smoke the product's own") +PLAN + +# ── 5. after the record: the gates are back ──────────────────────────────── +echo "── orun plan in the finished product: prod waits on stage, dev verifies main" +(cd "$tree" && orun plan --intent intent.yaml --trigger github-push-main --output "$scratch/plan-after.json") > "$scratch/plan-after.log" 2>&1 \ + || { fail "orun plan failed in the finished product"; tail -15 "$scratch/plan-after.log" >&2; } +python3 - "$scratch/plan-after.json" <<'AFTER' || 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 comp in ("supabase", "cloudflare-hyperdrive", "cloudflare-r2", "db-migrate", "web"): + prod, stage = jobs.get((comp, "prod")), jobs.get((comp, "stage")) + if not prod or not stage or stage["id"] not in (prod.get("dependsOn") or []): + problems.append(f"{comp}@prod does not wait on {comp}@stage — the promotion gate is not back") +dev = sorted(c for (c, e) in jobs if e == "dev") +if dev != ["db", "db-tests", "web", "web-tests"]: + problems.append(f"dev verifies {dev} on a push to main; it must verify db, db-tests, web and web-tests") +for p in problems: + print(f" ✕ {p}", file=sys.stderr) +if problems: + sys.exit(1) +print(" prod waits on stage for every component; dev verifies db, db-tests, web and web-tests") +AFTER + +# ── 6. a resume over the finished product ───────────────────────────────── +echo "── --resume over the finished product" +before="$(git -C "$tree" status --porcelain; git -C "$tree" rev-parse HEAD)" +orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" --resume "${sets[@]}" > "$scratch/resume.log" 2>&1 \ + || { fail "--resume did not run"; tail -10 "$scratch/resume.log" >&2; } +after="$(git -C "$tree" status --porcelain; git -C "$tree" rev-parse HEAD)" +[ "$before" = "$after" ] || { fail "--resume changed the finished product:"; git -C "$tree" status --short | head -10 >&2; } +grep -q "SITE_NAME = \"Sam's Chat & Answers\"" "$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..99533d3 --- /dev/null +++ b/testing/rebrand.test.sh @@ -0,0 +1,187 @@ +#!/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 name seam, the worker name, the Worker's own origin, the +# placeholder domain, a secret ref, the `repo` the Supabase project, the +# Hyperdrive config and the bucket are named after — and each runs through as +# many passes as a bootstrap might make, so a value written once must survive +# every later pass unchanged. Two things must NOT be renamed although they +# spell the slug: the upstream template's repository link (`vercel/ai-chatbot` +# — its name is this baseline's slug), and a migration (its checksum is in the +# manifest and in every database it was applied to). +# +# The identity is PINNED (fixtures/baseline-identity.ai-chatbot.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.ai-chatbot.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-chat","productname":"Acme Chat","productdomain":"acme.dev","githuborg":"acme-inc","subdomain":"acme","orunWorkspace":"ws_79BDXAZQ"}' + +echo "── rebrand: the product's own identity" +check "the name seam takes the product's name" \ + "$acme" apps/web/lib/site.ts 'export const SITE_NAME = "Chatbot";' \ + 'export const SITE_NAME = "Acme Chat";' +check "…and stays a valid string for a name with an apostrophe and an ampersand" \ + '{"reponame":"sams-chat","productname":"Sam'"'"'s Chat & Answers","productdomain":"sam.dev"}' \ + apps/web/lib/site.ts 'export const SITE_NAME = "Chatbot";' \ + 'export const SITE_NAME = "Sam'"'"'s Chat & Answers";' +check "the display name elsewhere is content, and is left alone" \ + "$acme" apps/web/app/x.tsx '<p>Ask the Chatbot.</p>' \ + '<p>Ask the Chatbot.</p>' +check "the worker name is re-prefixed, the environment suffix kept" \ + "$acme" apps/web/component.yaml 'workerName: ai-chatbot-web' \ + 'workerName: acme-chat-web' +check "the Worker's own wrangler name" \ + "$acme" apps/web/wrangler.template.jsonc ' "name": "ai-chatbot-web",' \ + ' "name": "acme-chat-web",' +check "the Worker's origin in the docs: worker name and subdomain" \ + "$acme" README.md 'https://ai-chatbot-web-stage.your-workers-subdomain.workers.dev/ping' \ + 'https://acme-chat-web-stage.acme.workers.dev/ping' +check "the origin the build bakes into absolute metadata URLs: worker name and subdomain" \ + "$acme" apps/web/component.yaml 'NEXT_PUBLIC_SITE_URL="${SITE_URL:-https://ai-chatbot-web-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}"' \ + 'NEXT_PUBLIC_SITE_URL="${SITE_URL:-https://acme-chat-web-${ORUN_ENVIRONMENT}.acme.workers.dev}"' +check "the placeholder domain is the product's domain, not a renamed slug" \ + "$acme" intent.yaml ' BASE_DOMAIN: ai-chatbot.example.com' \ + ' BASE_DOMAIN: acme.dev' +check "the repo slug" \ + "$acme" package.json ' "name": "ai-chatbot",' \ + ' "name": "acme-chat",' +check "the repo Terraform names the Supabase project, Hyperdrive config and bucket after" \ + "$acme" intent.yaml ' repo: ai-chatbot' \ + ' repo: acme-chat' +check "the fixture's Hyperdrive name follows it" \ + "$acme" apps/web/wiring.fixture.json ' "hyperdrive_name": "stg-ai-chatbot-stage"' \ + ' "hyperdrive_name": "stg-acme-chat-stage"' +check "…and so does its bucket name" \ + "$acme" apps/web/wiring.fixture.json ' "r2_bucket_name": "prod-ai-chatbot-prod"' \ + ' "r2_bucket_name": "prod-acme-chat-prod"' +check "a secret ref names the product's workspace and project" \ + "$acme" infra/terraform/cloudflare-r2/component.yaml \ + ' CLOUDFLARE_API_TOKEN: "secret://ai-chatbot/ai-chatbot/{{ .environment }}/CLOUDFLARE_R2_TOKEN"' \ + ' CLOUDFLARE_API_TOKEN: "secret://ws_79BDXAZQ/acme-chat/{{ .environment }}/CLOUDFLARE_R2_TOKEN"' +check "this repository's source link names the product's owner and repository" \ + "$acme" README.md 'See https://github.com/sourceplane/ai-chatbot.' \ + 'See https://github.com/acme-inc/acme-chat.' +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' + +echo "── rebrand: what spells the slug and is not this baseline's" +check "the upstream template's repository is upstream's" \ + "$acme" README.md 'Vercel'"'"'s [Next.js AI Chatbot](https://github.com/vercel/ai-chatbot) — AI' \ + 'Vercel'"'"'s [Next.js AI Chatbot](https://github.com/vercel/ai-chatbot) — AI' +check "…in the app's own README too" \ + "$acme" apps/web/README.md 'A chatbot from Vercel'"'"'s [Next.js AI Chatbot](https://github.com/vercel/ai-chatbot)' \ + 'A chatbot from Vercel'"'"'s [Next.js AI Chatbot](https://github.com/vercel/ai-chatbot)' +check "a Workers AI model id is not an identity" \ + "$acme" apps/web/lib/ai/models.ts 'export const DEFAULT_CHAT_MODEL = "@cf/moonshotai/kimi-k2.6";' \ + 'export const DEFAULT_CHAT_MODEL = "@cf/moonshotai/kimi-k2.6";' +check "a migration is never rewritten (its checksum is in the manifest)" \ + "$acme" packages/db/src/migrations/030_x/up.sql '-- ai-chatbot: a comment the checksum covers' \ + '-- ai-chatbot: a comment the checksum covers' +check "nor is its drizzle-kit twin" \ + "$acme" apps/web/lib/db/migrations/0002_x.sql '-- ai-chatbot: a comment the checksum covers' \ + '-- ai-chatbot: a comment the checksum covers' + +echo "── rebrand: a written value is not rewritten, in any later pass" +contains='{"reponame":"ai-chatbot-2","productname":"Chatbot 2","productdomain":"ai-chatbot.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": "ai-chatbot",' \ + ' "name": "ai-chatbot-2",' 3 +check "a worker name built on it survives three passes" \ + "$contains" apps/web/component.yaml 'workerName: ai-chatbot-web' \ + 'workerName: ai-chatbot-2-web' 3 +check "a domain containing the baseline's domain survives three passes" \ + "$contains" intent.yaml 'BASE_DOMAIN: ai-chatbot.example.com' \ + 'BASE_DOMAIN: ai-chatbot.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 name containing the baseline's name survives three passes" \ + "$contains" apps/web/lib/site.ts 'export const SITE_NAME = "Chatbot";' \ + 'export const SITE_NAME = "Chatbot 2";' 3 + +# --verify runs after every rebrand. 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": "ai-chatbot-2"' pass --values +verify "without them it cannot know, and fails" \ + "$contains" package.json '"name": "ai-chatbot-2"' fail +verify "given the values, a real leftover still fails" \ + "$acme" package.json '"name": "ai-chatbot"' fail --values +verify "a leftover worker name fails" \ + "$acme" apps/web/component.yaml 'workerName: ai-chatbot-web' fail --values +verify "a leftover code identifier fails (no rule renames it — so nothing may spell it)" \ + "$acme" apps/web/app/x.ts 'export class AiChatbot {}' fail --values +verify "the upstream template's repository link is not residue" \ + "$acme" README.md 'See https://github.com/vercel/ai-chatbot for upstream.' pass --values +verify "a clean product passes" \ + "$acme" package.json '"name": "acme-chat"' 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 = "AI_CHATBOT_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/db/package.json b/tests/db/package.json index 95ebe5b..ad6e1e3 100644 --- a/tests/db/package.json +++ b/tests/db/package.json @@ -12,6 +12,7 @@ "devDependencies": { "@app/eslint-config": "workspace:*", "@app/tsconfig": "workspace:*", + "@electric-sql/pglite": "0.5.8", "@saas/db": "workspace:*", "@types/node": "^22.9.0", "typescript": "^5.8.3", diff --git a/tests/db/src/migrations.test.ts b/tests/db/src/migrations.test.ts index 8ef10ab..b94e6be 100644 --- a/tests/db/src/migrations.test.ts +++ b/tests/db/src/migrations.test.ts @@ -6,6 +6,25 @@ import { manifest } from "@saas/db/manifest"; import { buildPlan, runMigrations } from "@saas/db/runner"; const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations"); +const drizzleDir = path.resolve(__dirname, "../../../apps/web/lib/db/migrations"); + +// db-migrate applies packages/db's copy to stage and prod; drizzle-kit applies +// apps/web's to a local database. They must be the same statements. +const DRIZZLE_TWIN: Record<string, string> = { + "010_initial": "0000_initial.sql", + "020_app_secrets": "0001_app_secrets.sql", + "030_row_level_security": "0002_row_level_security.sql", +}; + +function statements(sql: string): string[] { + return sql + .split("\n") + .filter((line) => !line.trim().startsWith("--")) + .join("\n") + .split(";") + .map((s) => s.replace(/\s+/g, " ").trim()) + .filter(Boolean); +} describe("the migration manifest (packages/db)", () => { it("starts with the control migration and names every file with its checksum", () => { @@ -22,6 +41,23 @@ describe("the migration manifest (packages/db)", () => { expect(result.applied).toEqual(manifest.migrations.map((m) => m.id)); }); + it("gives every app migration a drizzle-kit twin with the same statements", () => { + const app = manifest.migrations.filter((m) => m.context === "app"); + expect(app.map((m) => m.id)).toEqual(Object.keys(DRIZZLE_TWIN)); + for (const entry of app) { + const ours = readFileSync(path.join(migrationsDir, entry.path), "utf8"); + const twin = readFileSync(path.join(drizzleDir, DRIZZLE_TWIN[entry.id]!), "utf8"); + expect(statements(twin), entry.id).toEqual(statements(ours)); + } + }); + + it("generates the session key in the database, idempotently", () => { + const sql = readFileSync(path.join(migrationsDir, "020_app_secrets/up.sql"), "utf8"); + expect(sql).toMatch(/CREATE SCHEMA IF NOT EXISTS app_private/); + expect(sql).toMatch(/CREATE TABLE IF NOT EXISTS app_private\.secrets/); + expect(sql).toMatch(/'auth_secret'[\s\S]*gen_random_uuid\(\)[\s\S]*ON CONFLICT \(name\) DO NOTHING/); + }); + it("skips what the database already recorded", () => { const applied = new Map([[manifest.migrations[0]!.id, manifest.migrations[0]!.checksum]]); const plan = buildPlan(manifest, applied, migrationsDir); diff --git a/tests/db/src/row-level-security.test.ts b/tests/db/src/row-level-security.test.ts new file mode 100644 index 0000000..7f58a53 --- /dev/null +++ b/tests/db/src/row-level-security.test.ts @@ -0,0 +1,116 @@ +import { beforeAll, describe, expect, it } from "vitest"; +import { PGlite } from "@electric-sql/pglite"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { manifest } from "@saas/db/manifest"; + +// Supabase's Data API (PostgREST) serves the `public` schema to anyone holding +// the project's anon key. Migration 030 enables row-level security, with no +// policy, on every table there: `anon` and `authenticated` get nothing, and the +// app — which owns the tables — keeps everything. These run every migration +// db-migrate applies, in the manifest's order, on a real Postgres in process +// (PGlite: Postgres compiled to WASM), and read the catalog it leaves. +const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations"); +const sqlOf = (rel: string) => readFileSync(path.join(migrationsDir, rel), "utf8"); + +async function migrated(): Promise<PGlite> { + const db = new PGlite(); + for (const entry of manifest.migrations) { + await db.exec(sqlOf(entry.path)); + } + return db; +} + +type Rel = { relname: string; relrowsecurity: boolean; relforcerowsecurity: boolean }; +const PUBLIC_TABLES = ` + select c.relname, c.relrowsecurity, c.relforcerowsecurity + from pg_class c join pg_namespace n on n.oid = c.relnamespace + where n.nspname = 'public' and c.relkind in ('r', 'p') + order by c.relname`; + +describe("row-level security on public (after every migration)", () => { + let db: PGlite; + beforeAll(async () => { + db = await migrated(); + }, 60_000); + + it("leaves no table in public without row-level security", async () => { + const { rows } = await db.query<Rel>(PUBLIC_TABLES); + // Not vacuous: the template's tables are all there. + expect(rows.map((r) => r.relname)).toEqual( + expect.arrayContaining(["Chat", "Document", "Message_v2", "Stream", "Suggestion", "User", "Vote_v2"]), + ); + expect(rows.filter((r) => !r.relrowsecurity).map((r) => r.relname)).toEqual([]); + }); + + it("adds no policy and forces none — the owner is never subject to it", async () => { + const { rows } = await db.query<Rel>(PUBLIC_TABLES); + expect(rows.filter((r) => r.relforcerowsecurity).map((r) => r.relname)).toEqual([]); + const policies = await db.query<{ n: number }>( + "select count(*)::int as n from pg_policies where schemaname = 'public'", + ); + expect(policies.rows[0]!.n).toBe(0); + }); + + it("gives a role with the Data API's grants nothing, and the owner everything", async () => { + await db.exec(`insert into "User" (email, password) values ('owner-row@example.invalid', 'h')`); + await db.exec(`insert into "Chat" ("createdAt", title, "userId") select now(), 'a chat', id from "User"`); + // What Supabase grants `anon` on public by default — so a refusal below is + // row-level security's, not a missing grant's. + await db.exec(` + create role anon nologin; + grant usage on schema public to anon; + grant select, insert, update, delete on all tables in schema public to anon; + grant usage on all sequences in schema public to anon;`); + await db.exec("set role anon"); + try { + const seen = await db.query<{ n: number }>(`select count(*)::int as n from "User"`); + expect(seen.rows[0]!.n).toBe(0); + const chats = await db.query<{ n: number }>(`select count(*)::int as n from "Chat"`); + expect(chats.rows[0]!.n).toBe(0); + await expect( + db.exec(`insert into "User" (email, password) values ('anon@example.invalid', 'h')`), + ).rejects.toThrow(/row-level security/); + await expect(db.query("select value from app_private.secrets")).rejects.toThrow(/permission denied/); + } finally { + await db.exec("reset role"); + } + const owner = await db.query<{ n: number }>(`select count(*)::int as n from "User"`); + expect(owner.rows[0]!.n).toBe(1); + const ownerChats = await db.query<{ n: number }>(`select count(*)::int as n from "Chat"`); + expect(ownerChats.rows[0]!.n).toBe(1); + }); +}); + +describe("migration 030's guard", () => { + // The guard names `postgres`, the role Hyperdrive connects as, which PGlite + // cannot take SUPERUSER from. Pointed instead at a role that neither owns the + // tables nor bypasses RLS, it must refuse — and enable nothing. + const migration = sqlOf("030_row_level_security/up.sql"); + const aimedAt = (role: string) => + migration.replaceAll("rolname = 'postgres'", `rolname = '${role}'`).replaceAll("<> 'postgres'", `<> '${role}'`); + + async function beforeRls(): Promise<PGlite> { + const db = new PGlite(); + for (const entry of manifest.migrations.filter((m) => m.id < "030")) { + await db.exec(sqlOf(entry.path)); + } + return db; + } + + it("refuses when the app's role would be locked out, enabling nothing", async () => { + const db = await beforeRls(); + await db.exec("create role app_without_bypass nologin"); + await expect(db.exec(aimedAt("app_without_bypass"))).rejects.toThrow(/would lock the app out/); + const { rows } = await db.query<Rel>(PUBLIC_TABLES); + expect(rows.filter((r) => r.relrowsecurity)).toEqual([]); + }, 60_000); + + it("passes for a role with BYPASSRLS", async () => { + const db = await beforeRls(); + await db.exec("create role app_with_bypass nologin bypassrls"); + await db.exec(aimedAt("app_with_bypass")); + const { rows } = await db.query<Rel>(PUBLIC_TABLES); + expect(rows.every((r) => r.relrowsecurity)).toBe(true); + }, 60_000); +}); diff --git a/tests/web/package.json b/tests/web/package.json index 0b04e10..7d4cbfc 100644 --- a/tests/web/package.json +++ b/tests/web/package.json @@ -13,9 +13,11 @@ "@app/eslint-config": "workspace:*", "@app/tsconfig": "workspace:*", "@types/node": "^22.9.0", + "ai": "7.0.15", "clsx": "^2.1.1", "date-fns": "^4.4.0", "next": "16.3.8", + "next-auth": "5.0.0-beta.25", "react": "19.2.7", "react-dom": "19.2.7", "tailwind-merge": "^3.6.0", diff --git a/tests/web/src/auth-secret.test.ts b/tests/web/src/auth-secret.test.ts new file mode 100644 index 0000000..dfbf08d --- /dev/null +++ b/tests/web/src/auth-secret.test.ts @@ -0,0 +1,50 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// lib/auth-secret.ts: the key Auth.js signs and encrypts the session cookie +// with is AUTH_SECRET when one is set, and otherwise the key the +// environment's database generated for itself (migration 020_app_secrets) — +// read once per isolate. The database client is mocked: what is tested is +// which key wins and when the database is asked. +const execute = vi.fn(); +const getDb = vi.fn(async () => ({ execute })); + +vi.mock("@/lib/db/queries", () => ({ getDb: () => getDb() })); + +const STORED = "a".repeat(64); + +describe("the session key (lib/auth-secret.ts)", () => { + beforeEach(() => { + vi.resetModules(); + execute.mockReset(); + getDb.mockClear(); + delete process.env.AUTH_SECRET; + }); + + it("is AUTH_SECRET when one is set, without asking the database", async () => { + process.env.AUTH_SECRET = "an-owner-set-secret-of-enough-length"; + const { authSecret } = await import("@/lib/auth-secret"); + expect(await authSecret()).toBe("an-owner-set-secret-of-enough-length"); + expect(getDb).not.toHaveBeenCalled(); + }); + + it("is the stored key otherwise, read once per isolate", async () => { + execute.mockResolvedValue([{ value: STORED }]); + const { authSecret } = await import("@/lib/auth-secret"); + expect(await authSecret()).toBe(STORED); + expect(await authSecret()).toBe(STORED); + expect(execute).toHaveBeenCalledTimes(1); + }); + + it("treats an empty AUTH_SECRET (an .env line left blank) as unset", async () => { + process.env.AUTH_SECRET = ""; + execute.mockResolvedValue([{ value: STORED }]); + const { authSecret } = await import("@/lib/auth-secret"); + expect(await authSecret()).toBe(STORED); + }); + + it("names the missing migration when there is neither", async () => { + execute.mockResolvedValue([]); + const { authSecret } = await import("@/lib/auth-secret"); + await expect(authSecret()).rejects.toThrow(/020_app_secrets/); + }); +}); diff --git a/tests/web/src/health.test.ts b/tests/web/src/health.test.ts new file mode 100644 index 0000000..3edd7c3 --- /dev/null +++ b/tests/web/src/health.test.ts @@ -0,0 +1,52 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// app/api/health/route.ts, which the deploy's smoke and the bootstrap's +// probes read: 200 only when the database answers and the schema — the +// template's tables and the session key's — is there. The database client is +// mocked; `connection()` (which only marks the route request-time) too. +const execute = vi.fn(); +vi.mock("@/lib/db/queries", () => ({ getDb: async () => ({ execute }) })); +vi.mock("next/server", async (original) => ({ + ...(await original<typeof import("next/server")>()), + connection: async () => undefined, +})); + +async function health() { + const { GET } = await import("@/app/api/health/route"); + const res = await GET(); + return { body: await res.json(), status: res.status }; +} + +describe("GET /api/health", () => { + beforeEach(() => { + vi.resetModules(); + execute.mockReset(); + delete process.env.AI_GATEWAY_API_KEY; + }); + + it("is ok when the database is reachable and migrated, and names the model provider", async () => { + execute.mockResolvedValue([{ secrets: "app_private.secrets", users: '"User"' }]); + const { body, status } = await health(); + expect(status).toBe(200); + expect(body).toEqual({ + database: "reachable", + models: { default: "@cf/moonshotai/kimi-k2.6", gateway: "not connected", provider: "workers-ai" }, + ok: true, + schema: "migrated", + }); + }); + + it("is 503 when the schema is missing", async () => { + execute.mockResolvedValue([{ secrets: null, users: '"User"' }]); + const { body, status } = await health(); + expect(status).toBe(503); + expect(body).toMatchObject({ ok: false, schema: "missing" }); + }); + + it("is 503 when the database cannot be reached", async () => { + execute.mockRejectedValue(new Error("connect ECONNREFUSED")); + const { body, status } = await health(); + expect(status).toBe(503); + expect(body).toEqual({ database: "unreachable", ok: false }); + }); +}); diff --git a/tests/web/src/models.test.ts b/tests/web/src/models.test.ts new file mode 100644 index 0000000..1846348 --- /dev/null +++ b/tests/web/src/models.test.ts @@ -0,0 +1,113 @@ +import { generateText, streamText } from "ai"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +// The model provider (lib/ai/models.ts, lib/ai/providers.ts). Workers AI, +// through the Worker's AI binding, is the default and needs no key; the AI +// Gateway's models are offered only with AI_GATEWAY_API_KEY. The binding is a +// stand-in here — it records what it was asked and answers the way Workers +// AI's binding does: a JSON body, or a server-sent-event stream when the +// inputs ask for `stream: true`. +const run = vi.fn(); +vi.mock("@opennextjs/cloudflare", () => ({ + getCloudflareContext: () => ({ env: { AI: { run } } }), +})); + +function sse(chunks: string[]): ReadableStream<Uint8Array> { + const enc = new TextEncoder(); + return new ReadableStream({ + start(controller) { + for (const chunk of chunks) { + controller.enqueue(enc.encode(`data: ${JSON.stringify({ response: chunk })}\n\n`)); + } + controller.enqueue(enc.encode("data: [DONE]\n\n")); + controller.close(); + }, + }); +} + +describe("the models a deployment offers (lib/ai/models.ts)", () => { + beforeEach(() => { + vi.resetModules(); + delete process.env.AI_GATEWAY_API_KEY; + }); + afterEach(() => { + delete process.env.AI_GATEWAY_API_KEY; + }); + + it("offers only Workers AI with no gateway key, the default among them", async () => { + const models = await import("@/lib/ai/models"); + const ids = models.getAvailableModels().map((m) => m.id); + expect(ids.every((id) => id.startsWith("@cf/"))).toBe(true); + expect(ids).toContain(models.DEFAULT_CHAT_MODEL); + expect(models.isAvailableModel("moonshotai/kimi-k2.5")).toBe(false); + }); + + it("adds the gateway's models once its key is set", async () => { + process.env.AI_GATEWAY_API_KEY = "a-key"; + const models = await import("@/lib/ai/models"); + const ids = models.getAvailableModels().map((m) => m.id); + expect(ids).toEqual(expect.arrayContaining(["@cf/moonshotai/kimi-k2.6", "moonshotai/kimi-k2.5"])); + }); + + it("knows each Workers AI model's capabilities without a network call", async () => { + const fetchSpy = vi.spyOn(globalThis, "fetch"); + const models = await import("@/lib/ai/models"); + const caps = await models.getCapabilities(); + expect(caps[models.DEFAULT_CHAT_MODEL]).toEqual({ reasoning: true, tools: true, vision: true }); + expect(Object.keys(caps).every((id) => id.startsWith("@cf/"))).toBe(true); + expect(fetchSpy).not.toHaveBeenCalled(); + fetchSpy.mockRestore(); + }); +}); + +describe("the provider (lib/ai/providers.ts)", () => { + beforeEach(() => { + vi.resetModules(); + run.mockReset(); + delete process.env.AI_GATEWAY_API_KEY; + }); + + it("answers a gateway model with no key by the default Workers AI model", async () => { + const { resolveModelId } = await import("@/lib/ai/providers"); + const { DEFAULT_CHAT_MODEL } = await import("@/lib/ai/models"); + expect(resolveModelId("xai/grok-4.1-fast-non-reasoning")).toBe(DEFAULT_CHAT_MODEL); + expect(resolveModelId("@cf/zai-org/glm-4.7-flash")).toBe("@cf/zai-org/glm-4.7-flash"); + process.env.AI_GATEWAY_API_KEY = "a-key"; + expect(resolveModelId("xai/grok-4.1-fast-non-reasoning")).toBe("xai/grok-4.1-fast-non-reasoning"); + }); + + it("runs a chat model on the AI binding", async () => { + run.mockResolvedValue({ response: "Hello from Workers AI" }); + const { getLanguageModel } = await import("@/lib/ai/providers"); + const { text } = await generateText({ + model: getLanguageModel("@cf/moonshotai/kimi-k2.6"), + prompt: "hi", + }); + expect(text).toBe("Hello from Workers AI"); + expect(run).toHaveBeenCalledTimes(1); + expect(run.mock.calls[0]![0]).toBe("@cf/moonshotai/kimi-k2.6"); + }); + + it("streams a chat model's answer from the binding's event stream", async () => { + run.mockResolvedValue(sse(["Streamed ", "through ", "the binding."])); + const { getLanguageModel } = await import("@/lib/ai/providers"); + const result = streamText({ + model: getLanguageModel("@cf/moonshotai/kimi-k2.6"), + prompt: "hi", + }); + let text = ""; + for await (const delta of result.textStream) { + text += delta; + } + expect(text).toBe("Streamed through the binding."); + expect(run.mock.calls[0]![1]).toMatchObject({ stream: true }); + }); + + it("titles chats with the fast Workers AI model", async () => { + run.mockResolvedValue({ response: "A title" }); + const { getTitleModel } = await import("@/lib/ai/providers"); + const { titleModel } = await import("@/lib/ai/models"); + await generateText({ model: getTitleModel(), prompt: "hi" }); + expect(run.mock.calls[0]![0]).toBe(titleModel.id); + }); +}); diff --git a/tests/web/src/proxy.test.ts b/tests/web/src/proxy.test.ts new file mode 100644 index 0000000..fb9ffd3 --- /dev/null +++ b/tests/web/src/proxy.test.ts @@ -0,0 +1,96 @@ +import { encode } from "next-auth/jwt"; +import { NextRequest } from "next/server"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// proxy.ts decodes the Auth.js session cookie BEFORE any route runs, so it +// needs the session key too — and with no AUTH_SECRET that key is the one in +// the database (lib/auth-secret.ts). These drive the real proxy with the +// database mocked: the health routes answer without a session and without +// the database; a visitor without a session goes to the guest sign-in; a +// cookie encrypted under the database's key is a session; one encrypted +// under another key is not. +const execute = vi.fn(); +vi.mock("@/lib/db/queries", () => ({ getDb: async () => ({ execute }) })); + +const STORED = "b".repeat(64); +// Over https (a deployment) Auth.js names the cookie with the `__Secure-` +// prefix; over http (the built Worker served locally) without it. +const SECURE = "__Secure-authjs.session-token"; +const PLAIN = "authjs.session-token"; + +async function sessionCookie(secret: string, email: string, name = SECURE) { + const value = await encode({ + salt: name, + secret, + token: { email, id: "00000000-0000-0000-0000-000000000001", type: "guest" }, + }); + return `${name}=${value}`; +} + +async function proxy(path: string, cookie?: string, origin = "https://chat.example.com") { + const { proxy: run } = await import("@/proxy"); + return run( + new NextRequest(`${origin}${path}`, { + headers: cookie ? { cookie } : {}, + }) + ); +} + +describe("proxy.ts", () => { + beforeEach(() => { + vi.resetModules(); + execute.mockReset(); + execute.mockResolvedValue([{ value: STORED }]); + delete process.env.AUTH_SECRET; + }); + + it("answers /ping itself, without the database", async () => { + const res = await proxy("/ping"); + expect(res.status).toBe(200); + expect(await res.text()).toBe("pong"); + expect(execute).not.toHaveBeenCalled(); + }); + + it("lets /api/health through without a session or the database", async () => { + const res = await proxy("/api/health"); + expect(res.headers.get("x-middleware-next")).toBe("1"); + expect(execute).not.toHaveBeenCalled(); + }); + + it("sends a visitor without a session to the guest sign-in", async () => { + const res = await proxy("/chat/abc"); + expect(res.status).toBe(307); + expect(res.headers.get("location")).toBe( + "https://chat.example.com/api/auth/guest?redirectUrl=%2Fchat%2Fabc" + ); + }); + + it("accepts a session encrypted under the database's key", async () => { + const res = await proxy("/", await sessionCookie(STORED, "guest-1")); + expect(res.headers.get("x-middleware-next")).toBe("1"); + expect(execute).toHaveBeenCalledTimes(1); + }); + + it("reads the cookie Auth.js sets over http — the built Worker served locally — without the prefix", async () => { + const plain = await sessionCookie(STORED, "guest-1", PLAIN); + const res = await proxy("/", plain, "http://127.0.0.1:8787"); + expect(res.headers.get("x-middleware-next")).toBe("1"); + // …and over https only the prefixed one, as Auth.js would have set it. + expect((await proxy("/", plain)).status).toBe(307); + }); + + it("refuses one encrypted under another key", async () => { + const res = await proxy("/", await sessionCookie("c".repeat(64), "guest-1")); + expect(res.status).toBe(307); + }); + + it("uses AUTH_SECRET instead, when it is set", async () => { + process.env.AUTH_SECRET = "an-owner-set-secret-of-enough-length"; + const res = await proxy( + "/", + await sessionCookie("an-owner-set-secret-of-enough-length", "guest-1") + ); + expect(res.headers.get("x-middleware-next")).toBe("1"); + expect(execute).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/web/src/wrangler-config.test.ts b/tests/web/src/wrangler-config.test.ts new file mode 100644 index 0000000..45b0526 --- /dev/null +++ b/tests/web/src/wrangler-config.test.ts @@ -0,0 +1,123 @@ +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import * as path from "node:path"; +import { describe, expect, it } from "vitest"; + +// apps/web's wrangler.jsonc is COMMITTED: the composition checks that it +// exists before the build, in a fresh checkout, so it cannot be a file a build +// generates. It is the render of wrangler.template.jsonc from +// wiring.fixture.json, and every lane re-renders it (apps/web/component.yaml's +// buildCommand): stage and prod from their live wiring documents, dev from +// the fixture. These hold the committed file to the template, and the live +// render to the documents it is given. +const app = path.resolve(__dirname, "../../../apps/web"); +const wire = path.resolve(__dirname, "../../../tooling/wire"); +const tmp = () => mkdtempSync(path.join(tmpdir(), "wire-")); + +function renderFixture(env: string): string { + const dir = tmp(); + try { + const out = path.join(dir, "wrangler.jsonc"); + execFileSync(process.execPath, [ + path.join(wire, "render.mjs"), + "--template", + path.join(app, "wrangler.template.jsonc"), + "--out", + out, + "--map", + path.join(app, "wiring.fixture.json"), + "--env", + env, + ]); + return readFileSync(out, "utf8"); + } finally { + rmSync(dir, { force: true, recursive: true }); + } +} + +function renderLive(env: string, wiring: Record<string, string>, fixture = false): string { + const dir = tmp(); + try { + const out = path.join(dir, "wrangler.jsonc"); + const clean = { ...process.env }; + for (const k of Object.keys(clean)) { + if (k.startsWith("WIRING_")) { + delete clean[k]; + } + } + execFileSync( + process.execPath, + [ + path.join(wire, "live.mjs"), + "--template", + path.join(app, "wrangler.template.jsonc"), + "--out", + out, + "--components", + "cloudflare-hyperdrive,cloudflare-r2", + "--env", + env, + ...(fixture ? ["--fixture", path.join(app, "wiring.fixture.json"), "--fixture-envs", "dev"] : []), + ], + { env: { ...clean, ...wiring }, stdio: "pipe" } + ); + return readFileSync(out, "utf8"); + } finally { + rmSync(dir, { force: true, recursive: true }); + } +} + +describe("apps/web wrangler config", () => { + it("is committed as the fixture render of the template (pnpm run wire:fixture)", () => { + expect(readFileSync(path.join(app, "wrangler.jsonc"), "utf8")).toBe(renderFixture("stage")); + }); + + it("binds Workers AI, Hyperdrive and R2 — and no model key", () => { + const committed = readFileSync(path.join(app, "wrangler.jsonc"), "utf8"); + expect(committed).toMatch(/"ai":\s*\{\s*"binding":\s*"AI"\s*\}/); + expect(committed).toMatch(/"binding":\s*"HYPERDRIVE"/); + expect(committed).toMatch(/"binding":\s*"BLOB"/); + expect(committed).not.toMatch(/"vars"/); + expect(committed).not.toMatch(/AI_GATEWAY_API_KEY"\s*:/); + }); + + it("keeps every resource id and bucket in the template a wiring token", () => { + const template = readFileSync(path.join(app, "wrangler.template.jsonc"), "utf8"); + expect(template).not.toMatch(/"id":\s*"[0-9a-f]{32}"/); + expect(template).toMatch(/@@wiring\(cloudflare-hyperdrive\/__ENV__:hyperdrive_id\)@@/); + expect(template).toMatch(/@@wiring\(cloudflare-r2\/__ENV__:r2_bucket_name\)@@/); + }); + + it("renders a deploy lane its own environment from the live wiring documents", () => { + const rendered = renderLive("prod", { + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: JSON.stringify({ hyperdrive_id: "f".repeat(32), hyperdrive_name: "prod-x-prod" }), + WIRING_CLOUDFLARE_R2_PROD: JSON.stringify({ r2_bucket_name: "prod-x-prod-bucket" }), + }); + expect(rendered).toContain(`"id": "${"f".repeat(32)}"`); + expect(rendered).toContain('"bucket_name": "prod-x-prod-bucket"'); + expect(rendered).not.toContain("__ENV__"); + }); + + it("refuses a deploy render missing either wiring document", () => { + expect(() => + renderLive("stage", { + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: JSON.stringify({ hyperdrive_id: "e".repeat(32), hyperdrive_name: "x" }), + }) + ).toThrow(); + }); + + it("renders dev — which no root applies to — from the fixture, as the build command does", () => { + const rendered = renderLive("dev", {}, true); + expect(rendered).toContain('"id": "00000000000000000000000000000002"'); + expect(rendered).toContain('"bucket_name": "dev-ai-chatbot-dev"'); + }); + + it("is what the component builds with: the live render, fixture for dev only", () => { + const component = readFileSync(path.join(app, "component.yaml"), "utf8"); + expect(component).toContain("wranglerConfig: wrangler.jsonc"); + expect(component).toMatch( + /buildCommand: node \.\.\/\.\.\/tooling\/wire\/live\.mjs --template wrangler\.template\.jsonc --out wrangler\.jsonc --components cloudflare-hyperdrive,cloudflare-r2 --env "\$\{ORUN_ENVIRONMENT\}" --fixture wiring\.fixture\.json --fixture-envs dev && / + ); + }); +}); diff --git a/tests/web/vitest.config.ts b/tests/web/vitest.config.ts index 2cb9045..b9cabe7 100644 --- a/tests/web/vitest.config.ts +++ b/tests/web/vitest.config.ts @@ -10,6 +10,10 @@ export default defineConfig({ // apps/web's own copy; pointing the tests' mocks at that same copy is // what makes `vi.mock("@opennextjs/cloudflare")` apply to them. "@opennextjs/cloudflare": path.resolve(web, "node_modules/@opennextjs/cloudflare"), + // The same for next/server: the health route's `connection()` is mocked + // (it only marks the route request-time, and throws outside a request), + // and the proxy's NextRequest must be the class the proxy itself uses. + "next/server": path.resolve(web, "node_modules/next/server.js"), "@": web, }, }, diff --git a/tooling/bootstrap/dev-lanes.mjs b/tooling/bootstrap/dev-lanes.mjs new file mode 100755 index 0000000..4684043 --- /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 environment; a third, on the dev rung (with +// the two test packages 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..c31e99a --- /dev/null +++ b/tooling/bootstrap/retouch.mjs @@ -0,0 +1,254 @@ +#!/usr/bin/env node +// Give a re-run phase something to land (zero-dependency). +// +// A phase lands as a pull request and is verified by the convergence run that +// follows the merge. When that convergence FAILS — a provider error, a runner +// starved out, a smoke that raced route propagation past its retries — the +// merge has already happened, so every file the phase places is on main. orun +// derives phase state from the files on disk (never from a stored record), so +// a retried build finds the phase placed, and even a forced re-run of it +// produces an EMPTY diff: `orun.pr/land@v1` has nothing to commit, and the +// product's CI (`orun plan --changed`) deploys a component only when one of +// its files changed in the push. Nothing lands, nothing redeploys, and the +// operator is told the phase is fine. +// +// This tool is what the phase's `retouch` hook runs before it stages and +// lands: for each component the phase deploys, it rewrites ONE trailing line +// in that component's `component.yaml`, +// +// # orun: redeploy <phase> <stamp> +// +// replacing the previous marker if there is one (never accumulating), so the +// landing has a diff and exactly those components are in the changed set. The +// same convention was hand-edited before this existed (`# ci: re-trigger +// deploy …` lines, duplicated by hand); this is that edit with a name, a +// stamp, and a phase to answer for it. +// +// THE MARKER IS A DEPLOY TRIGGER, NOT STATE. Nothing reads it back: orun does +// not learn from it whether a phase ran, and this repository's invariant — +// phase state is DERIVED from the tree, never stored in it — holds. Delete the +// line and nothing is lost but the next redeploy's reason to happen. +// +// node retouch.mjs --phase 01-product --affects .baseline/tasks/01-product.TaskContract.yaml +// node retouch.mjs --phase 01-product --components web,db-migrate +// +// 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..70fa4ad --- /dev/null +++ b/tooling/rebrand/rebrand.mjs @@ -0,0 +1,484 @@ +#!/usr/bin/env node +// Rebrand renamer for the ai-chatbot baseline (zero-dependency). +// +// This repository is a baseline: a product is instantiated from it, branded, +// and deployed as somebody's own chatbot. This script rewrites every +// *instance identity* literal in the product tree — repo slug (the intent, +// the secret project, the Supabase project, Hyperdrive config and R2 bucket +// names Terraform derives from it), the product's display name, the product +// domain, Cloudflare worker resource names (so an instance is account-safe +// even when it shares an account with another), the workers.dev subdomain +// placeholder — to the values in a values file, and leaves *org-owned* +// identity alone (the orun state backend, the `sourceplane.io` manifest +// apiVersion, company mailboxes) and the UPSTREAM template's own identity too +// (its GitHub repository, which the README links to: it names where the code +// came from, not this product). +// +// 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-chat", // required — repo slug +// "productname": "Acme Chat", // required — the product's display name +// "productdomain": "acme.dev", // required — the product domain +// "githuborg": "acme-inc", // owner of the product repo (source link in docs) +// "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, +// the `repo` Terraform names the Supabase project, the +// Hyperdrive config and the R2 bucket after +// 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 this repository'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: "ai-chatbot", + pascal: "AiChatbot", + productName: "Chatbot", + domain: "ai-chatbot.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$", + // Migrations are immutable once applied: db-migrate compares each file's + // sha256 to packages/db/src/manifest.ts and to the database's ledger, so + // a byte renamed here would stop every later deploy. (None names this + // baseline's identity; packages/db's tests hold their checksums.) + "^packages/db/src/migrations/", + "^apps/web/lib/db/migrations/", + "\\.(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; + } + }); +} + +// ── The upstream template's identity (never rewritten) ───────── +// +// This tree IS Vercel's Next.js AI Chatbot, whose own repository name happens +// to be this baseline's slug. Where the docs name the upstream, the slug is +// the upstream's, and renaming it would point a product's readers at +// `github.com/vercel/<their-repo>`, which does not exist. Protected from +// every rule, and allowed by the leftover sweep. +const UPSTREAM = [ + /github\.com\/vercel\/ai-chatbot\b/g, // the template's repository +]; + +// ── 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 + ...UPSTREAM, +]; +const MASK = (i, j) => `\u0000REBRAND_PROTECTED_${i}_${j}\u0000`; + +// ── Substituted values are opaque ────────────────────────────── +// +// The rules run in sequence over one buffer. If each wrote its VALUE into it, +// every later rule could match that value again — a product whose domain +// contains the baseline's slug would have it renamed a second time by the +// repo-slug rule, and every phase of a bootstrap re-runs this over the whole +// tree. So a rule writes a TOKEN standing for its value, and every token is +// expanded once, after the last rule. A token is NUL, `H<n>`, NUL; its outer +// characters take the word/non-word class of the value's own edges, so a +// later rule's `\b` sees the boundary the value would have given it. +const heldValues = []; +const heldIndex = new Map(); +function hold(value) { + if (value === "") return ""; + let i = heldIndex.get(value); + if (i === undefined) { + i = heldValues.push(value) - 1; + heldIndex.set(value, i); + } + const edge = (c) => (/\w/.test(c) ? "0" : "\u0001"); + return `${edge(value[0])}\u0000H${i}\u0000${edge(value[value.length - 1])}`; +} +const HELD_RE = /[0\u0001]\u0000H(\d+)\u0000[0\u0001]/g; +function release(text) { + return text.replace(HELD_RE, (_, i) => heldValues[Number(i)]); +} + +// ── Worker resource names ────────────────────────────────────── +// +// Every Cloudflare worker ships prefixed with the slug (`<slug>-<base>`, the +// base being its `apps/<base>/` directory): the component's `workerName`, the +// environment URLs, the deploy smoke. Re-prefix it so an instance's workers +// never collide with another's in a shared account. +function workerBases(files) { + const bases = new Set(); + for (const file of files) { + const m = /^apps\/([^/]+)\//.exec(file); + if (m) bases.add(m[1]); + } + return [...bases]; +} + +// ── Rename map (ordered, most specific first) ────────────────── + +function literalPairs() { + return [ + // This repository's source link, wherever the docs give it. 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 (apps/web/lib/site.ts). 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 Supabase + // project, the Hyperdrive config and the R2 bucket are named after it), the + // root package name, the fixture's Hyperdrive and bucket names, docs. Runs + // AFTER the worker pass so `<slug>-<base>` has already been consumed. + list.push({ + re: new RegExp(`\\b${rx(baseline.slug)}\\b`, "g"), + replacement: () => reponame, + label: "repo slug", + }); + return list; +} + +// ── Leftover sweep ───────────────────────────────────────────── +// +// After a rebrand (or under --verify) every remaining baseline-identity +// literal is residue: either org-owned (allowed, masked above) or a missed +// rename (reported, non-zero exit). The pascal form and the env-var prefix +// have no rule because nothing in this tree spells them; they are swept so +// that the first file that does fails here, naming itself, rather than +// shipping the baseline's name. +// +// The placeholder subdomain is residue only when the product changed it — a +// product that kept the placeholder has not deployed yet, and that is not a +// missed rename. Under --verify without values it is skipped for the same +// reason. +const subdomainChanged = !verifyOnly && subdomain !== baseline.subdomain; +const RESIDUE_RE = new RegExp( + (subdomainChanged ? `${rx(baseline.subdomain)}|` : "") + + [ + `\\b${rx(baseline.slug)}\\b`, + `${rx(baseline.slug)}-`, + rx(baseline.pascal), + `${rx(baseline.envPrefix)}_`, + rx(baseline.domain), + ].join("|"), + "g", +); +const ALLOWED_RESIDUE = [ + /https:\/\/orun-api\.sourceplane\.ai/, // orun state backend + /[A-Za-z0-9._%+-]+@sourceplane\.ai/, // company mailboxes + ...UPSTREAM, +]; + +function sweep(files, allowedLiterals = []) { + const residue = []; + for (const file of files) { + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch { + continue; + } + for (const line of text.split("\n")) { + let cleaned = ALLOWED_RESIDUE.reduce((l, re) => l.replace(new RegExp(re.source, "g"), ""), line); + // The rename's own TARGET values: a product legitimately named with the + // baseline's slug inside it is not residue. + for (const lit of allowedLiterals) { + if (lit) cleaned = cleaned.split(lit).join(""); + } + if (new RegExp(RESIDUE_RE.source).test(cleaned)) { + residue.push(`${file}: ${line.trim().slice(0, 120)}`); + } + } + } + return residue; +} + +// ── Main ─────────────────────────────────────────────────────── + +const files = trackedFiles(); +const literals = literalPairs(); +const regexes = regexPairs(files); + +// Every value a rule can write. A value some rule would match again is HELD +// wherever it already stands: every phase of a bootstrap re-runs this over the +// whole tree, so what an earlier phase wrote is input to the next pass and +// must come out of it unchanged. +const produced = [ + ...literals.map(([, to]) => to), + `SITE_NAME = ${JSON.stringify(productname)}`, + `secret://${orunWorkspaceSlug}/${reponame}/`, + reponame, + ...workerBases(files).map((base) => `${brandSlug}-${base}`), +].filter((v, i, all) => v && all.indexOf(v) === i); +const rematchable = (v) => + literals.some(([from]) => v.includes(from)) || regexes.some(({ re }) => new RegExp(re.source).test(v)); +// Longest first, so a held value is never split by a shorter one inside it. +const guarded = produced.filter(rematchable).sort((a, b) => b.length - a.length); +const allowedTargets = produced.filter((to) => new RegExp(RESIDUE_RE.source).test(to)); + +if (verifyOnly) { + const residue = sweep(files, valuesPath ? allowedTargets : []); + if (residue.length > 0) { + console.error(`rebrand --verify: ${residue.length} baseline-identity leftover(s):`); + for (const r of residue) console.error(` ${r}`); + process.exit(1); + } + console.log("rebrand --verify: no baseline-identity leftovers."); + process.exit(0); +} + +const counts = new Map(); +const touched = new Set(); +const count = (label, n = 1) => counts.set(label, (counts.get(label) ?? 0) + n); + +for (const file of files) { + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch { + continue; + } + if (text.includes("\0")) continue; // binary safety net + const original = text; + + const masks = []; + PROTECTED.forEach((re, i) => { + text = text.replace(re, (m) => { + const token = MASK(i, masks.length); + masks.push([token, m]); + return token; + }); + }); + + // What a previous pass already wrote stays as written. + for (const value of guarded) text = text.split(value).join(hold(value)); + + for (const [from, to, label] of literals) { + const n = text.split(from).length - 1; + if (n === 0) continue; + text = text.split(from).join(hold(to)); + count(label, n); + } + for (const { re, replacement, label } of regexes) { + text = text.replace(re, (...m) => { + count(label); + return hold(replacement(...m)); + }); + } + + // Every rule has run; only now do the values it wrote appear. + text = release(text); + for (const [token, value] of masks) text = text.split(token).join(value); + + if (text !== original) { + touched.add(file); + if (!dryRun) fs.writeFileSync(file, text); + } +} + +console.log(`rebrand${dryRun ? " (dry-run)" : ""}: ${touched.size} file(s) affected`); +for (const [label, n] of counts) console.log(` ${String(n).padStart(5)} ${label}`); +if (dryRun) process.exit(0); + +const residue = sweep(trackedFiles(), allowedTargets); +if (residue.length > 0) { + console.error(`rebrand: ${residue.length} baseline-identity leftover(s) after rename:`); + for (const r of residue) console.error(` ${r}`); + process.exit(1); +} +console.log("rebrand: leftover sweep clean."); diff --git a/tooling/rebrand/values.example.json b/tooling/rebrand/values.example.json new file mode 100644 index 0000000..a51fad2 --- /dev/null +++ b/tooling/rebrand/values.example.json @@ -0,0 +1,8 @@ +{ + "reponame": "acme-chat", + "productname": "Acme Chat", + "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))`, );