Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .baseline/identity.json
Original file line number Diff line number Diff line change
@@ -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"
}
165 changes: 165 additions & 0 deletions .baseline/product/README.md
Original file line number Diff line number Diff line change
@@ -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

<!-- 02-docs:begin -->
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).
<!-- 02-docs:end -->

## 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/<key>`.

## 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 |
33 changes: 33 additions & 0 deletions .baseline/tasks/01-product.TaskContract.yaml
Original file line number Diff line number Diff line change
@@ -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: []
14 changes: 14 additions & 0 deletions .baseline/tasks/02-docs.TaskContract.yaml
Original file line number Diff line number Diff line change
@@ -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: []
145 changes: 145 additions & 0 deletions .github/workflows/baseline.yml
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading