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
1 change: 1 addition & 0 deletions specs/epics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ folder is the adoption; the merge creates the epic in the workspace.

| Epic | Cluster | Status | What it is |
|------|---------|--------|------------|
| [`nl-postgres/`](./nl-postgres/) | **NL** | In progress (NL0) | Vercel's Natural Language Postgres — plain-English questions answered in SQL — on Cloudflare Workers with Workers AI and Supabase Postgres through Hyperdrive, the model's SQL run as a read-only role, and an Orun baseline that instantiates it in one landing (NL2) |

As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`.
11 changes: 11 additions & 0 deletions specs/epics/nl-postgres/IMPLEMENTATION-STATUS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# nl-postgres — implementation status

| Milestone | State | Landed |
|---|---|---|
| NL0 — the spec | ✅ | NL-1 |
| NL1 — the app on Workers and Supabase | planned | NL-2 |
| NL2 — a baseline | planned | NL-3 |

## Departures from the upstream template

Recorded as they land, from NL1 on.
33 changes: 33 additions & 0 deletions specs/epics/nl-postgres/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# nl-postgres — Vercel's Natural Language Postgres on Cloudflare

**The template's app as it is — a question in plain English, the SQL a model
writes for it, the rows, a chart and an explanation of the query — on one
Cloudflare Worker, the SQL written by Workers AI and run as a read-only
database role against a Supabase project behind Hyperdrive; and the baseline
that makes a copy of it somebody else's product in one landing.**

| | |
|---|---|
| Status | In progress — NL0 on main |
| Upstream | [vercel-labs/natural-language-postgres](https://github.com/vercel-labs/natural-language-postgres) (MIT), Vercel's [Natural Language Postgres](https://vercel.com/templates/next.js/natural-language-postgres), at `f5af6a2` |
| Reference | [rag-chatbot](https://github.com/sourceplane/rag-chatbot) — an AI SDK app on Workers AI and Supabase through Hyperdrive, migrations, db-migrate, row-level security; [admin-dashboard](https://github.com/sourceplane/admin-dashboard) — the most recent Supabase port |
| Key | `NL` |

## Read in this order

1. [design.md](design.md) — the template, how each Vercel piece maps to
Cloudflare and Supabase, the read-only role the model's SQL runs as, the
repository and the build, and the alternatives rejected.
2. [implementation-plan.md](implementation-plan.md) — the milestones.
3. [risks-and-open-questions.md](risks-and-open-questions.md) — what is not
proven, and what was accepted.
4. [IMPLEMENTATION-STATUS.md](IMPLEMENTATION-STATUS.md) — what shipped, and
every departure from the upstream template.

## Milestones

| Milestone | What it lands | Task |
|---|---|---|
| NL0 — the spec | the repository, its intent, CI, tooling and spec index; this doc set | NL-1 |
| NL1 — the app on Workers and Supabase | the template in `apps/web`, the model on Workers AI, the read-only query path, the table, sample data and role as migrations, the Supabase and Hyperdrive roots, the tests | NL-2 |
| NL2 — a baseline | the console card, the build document, the context pack and the baseline's tests | NL-3 |
103 changes: 103 additions & 0 deletions specs/epics/nl-postgres/design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# nl-postgres — design

## The template

Vercel's Natural Language Postgres ([vercel-labs/natural-language-postgres](https://github.com/vercel-labs/natural-language-postgres))
is a Next.js 15 App Router app with one page, a client component, and four
server actions (`app/actions.ts`). A visitor asks a question about a table of
unicorn companies in plain English (or picks a suggested one);
`generateQuery` asks a model for the SQL — upstream's system prompt describes
the `unicorns` table and says "Only retrieval queries are allowed" — and
`runGenerateSQLQuery` runs it after a string check (it must start with
`select` and name none of drop, delete, insert, update, alter, truncate,
create, grant, revoke). The rows show as a table; `generateChartConfig` asks
the model for a Recharts configuration over them, and `explainQuery` for an
explanation of the query, clause by clause. All three model calls are
structured outputs (AI SDK 6, `Output.object` with zod schemas), the model
named as the string `"openai/gpt-5.4-mini"` — which AI SDK 6 sends through
Vercel's AI Gateway. The database is Vercel Postgres through
`@vercel/postgres`; its owner downloads CB Insights' list of unicorn
companies as a CSV and runs `lib/seed.ts`, which creates the table and loads
it.

## How it maps to Cloudflare and Supabase

| Vercel | Here | Why |
|---|---|---|
| Next.js hosting | One Worker (`.open-next/worker.js`) + Static Assets, built by `@opennextjs/cloudflare` on Next.js 16.3.8 | The adapter refuses Next.js 15.5 (out of the Next.js team's support window) |
| `"openai/gpt-5.4-mini"` through Vercel's AI Gateway | `lib/ai/models.ts`: Workers AI's `@cf/meta/llama-4-scout-17b-16e-instruct` through the Worker's `AI` binding by default (JSON mode answers the three structured outputs); OpenAI's `gpt-5.4-mini`, straight from OpenAI through `@ai-sdk/openai`, once `OPENAI_API_KEY` is a Worker secret | A product answers on its first deploy with no vendor key, and AI Gateway is not a composition this platform has; the optional key is the one upstream's own Vercel button asked for |
| Vercel Postgres, `sql.query(query)` from `@vercel/postgres` | A Supabase project's Postgres through the `HYPERDRIVE` binding: `getSql()` builds a `postgres` client per call | The Workers runtime refuses to reuse a socket across requests (rag-chatbot's decision) |
| The generated SQL run on the owner's connection | `runReadOnlyQuery()` sends it to `app_private.run_read_only(query)`, in a READ ONLY transaction with a 5 s statement timeout; the function runs it as `query_reader` (below). The template's string check stays in front | The check alone does not stop SQL a model can be talked into |
| `lib/seed.ts`: CREATE TABLE + the downloaded CSV, run by hand | `packages/db`'s `010_unicorns` (the same CREATE TABLE) and `020_sample_unicorns` (sixty fictional companies), applied by `infra/db-migrate` before the Worker deploys; `tooling/migrations/csv-to-sql.mjs` turns the owner's CB Insights CSV into a migration that replaces them | One schema, applied in order, recorded in a ledger; CB Insights' list is theirs and is not redistributed |
| A table the Data API would serve | `030_row_level_security` on every table in `public` | Supabase serves `public` to anyone with the anon key |
| A Postgres database created in the dashboard | `infra/terraform/supabase` (one project per environment) + `infra/terraform/cloudflare-hyperdrive` (one config per environment) | rag-chatbot's roots |
| "Deploy with Vercel" | The header's source link to the product's own repository; `orun new --blueprint repo-blueprint.yaml` | |

## The read-only role (040)

The template's own check is a string check, and it is not a boundary: a
model writes what it is asked to, and a visitor can ask. SQL that starts with
`select` and names no forbidden word can still read other schemas, call
functions that run SQL of their own (`query_to_xml` over a hex-decoded
`DELETE`), or set the session's role. So the database is the boundary:

- **`query_reader`** — `NOLOGIN NOINHERIT`, no superuser, no BYPASSRLS. It
holds `SELECT` on `unicorns` (through the one policy on it, since the table
has row-level security) and nothing else: no write, no DDL, no sequence, no
other schema (`_migrations`, `app_private`).
- **`app_private.run_read_only(query text) → jsonb`** — a `SECURITY DEFINER`
PL/pgSQL function OWNED by `query_reader`, so the query runs with its
privileges. It runs the query as a cursor (`FOR r IN EXECUTE`), so a second
statement is refused, and returns the rows in order as one JSON array.
Inside a security-definer function Postgres refuses `SET ROLE`, `RESET
ROLE` and `set_config('role', …)` — which is why the function, and not a
`SET LOCAL ROLE` in the app's own session, is the door: the session's user
is `postgres`, and `SET ROLE` checks the session user, so SQL run after a
`SET ROLE` could step straight back. Only `postgres` (the role the
migrations run as, and the app's) may execute it; `PUBLIC`, and so the Data
API's `anon` and `authenticated`, may not, and cannot see `app_private`.
- The app calls it inside `BEGIN READ ONLY` with `SET LOCAL
statement_timeout = '5s'`, the query a bound parameter of the call.

What `query_reader` can still see is the catalog Postgres shows every role:
table and column names, its own settings. The e2e tier and `tests/db` hold
every refusal above to the database, with the string check out of the way.

## The data

CB Insights' list of unicorn companies is CB Insights' data, which each
owner downloads; it is not in this repository. So that a fresh product has
rows to ask about, `020_sample_unicorns` writes sixty fictional companies in
the list's shape — the columns of the table, valuations in billions, the
countries and cities spelled out, the industries the prompt names, investors
as a comma-separated list — and says in its first line that they are
fictional; the page's info card says so too. Loading the real list is a
migration the owner adds (`csv-to-sql.mjs`), which db-migrate applies on the
next merge like any other.

## The repository

rag-chatbot's tree in the turso v8 shape: `apps/web` (the template),
`packages/db` (the migrations and Lumen's runner), `infra/terraform/supabase`,
`infra/terraform/cloudflare-hyperdrive`, `infra/db-migrate`, `tests/web`,
`tests/db`, `tooling/*`; the baseline's own `blueprint.yaml`,
`repo-blueprint.yaml`, `.baseline/`, `hooks/`, `docs/phases/`, `testing/`
and `ai/context/`. Per environment, on a push to main: supabase →
cloudflare-hyperdrive → db-migrate → web, every edge enforced.

## Alternatives rejected

- **`SET LOCAL ROLE query_reader` in the app's transaction.** One line, and
not a boundary: the session user is `postgres`, so the generated SQL could
`set_config('role', 'postgres', true)` its way back.
- **A second Hyperdrive config that logs in as a read-only user.** A real
boundary, but the role and its password would have to exist before
Hyperdrive can create a config over them, and the migrations run after
Hyperdrive; it would need a new Terraform root, a generated password
published as a secret and a reordered plan. The security-definer function
gives the same privileges with what the reference already has.
- **Keeping the AI Gateway model as the default.** It needs a gateway key
before anything answers, and AI Gateway is not a composition here.
- **Shipping CB Insights' CSV.** It is not ours to redistribute.
- **Next.js 15.5.28.** The adapter's peer range admits it, but its build
refuses a Next.js release the Next.js team no longer supports.
31 changes: 31 additions & 0 deletions specs/epics/nl-postgres/epic.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# The epic's declaration. metadata.name equals the directory name; metadata.key
# is the task-key prefix this epic reserves (NL → NL-1, NL-2, …). Owner, target
# date and health are the platform's — never written here.
apiVersion: orun.io/v1
kind: Epic
metadata:
name: nl-postgres
key: NL
spec:
title: "Vercel's Natural Language Postgres on Cloudflare Workers and Supabase"
summary: "Vercel's Natural Language Postgres — a question in plain English turned into SQL by a model, the SQL run against a table of unicorn companies, the rows charted and the query explained — run on Cloudflare Workers + Static Assets through @opennextjs/cloudflare, the SQL written by Workers AI through the Worker's AI binding and run as a read-only database role, its Postgres a Supabase project reached through Hyperdrive, both provisioned by Terraform; the table, sixty fictional sample companies and the read-only role applied by db-migrate; and become an Orun baseline that takes a new product from nothing to live on stage and prod in one landing."
state: started
milestones:
- name: "NL0 — the spec"
exitCriteria:
- "the repository is born with its intent, CI, tooling and spec index, and this doc set and the task contracts are on main"
tasks: [NL-1]
- name: "NL1 — the app on Workers and Supabase"
exitCriteria:
- "apps/web is the template on Next.js 16.3.8, built by OpenNext into one Worker, its Postgres the HYPERDRIVE binding with a client per call"
- "the model is Workers AI through the AI binding, or OpenAI's gpt-5.4-mini once OPENAI_API_KEY is set — never a gateway"
- "the model's SQL runs only through app_private.run_read_only, as query_reader, in a read-only transaction under a statement timeout, behind the template's own check"
- "the table, the sample companies, row-level security and the read-only role are packages/db migrations, applied by db-migrate; the Supabase and Hyperdrive roots provision stage and prod"
- "`pnpm typecheck`, `pnpm lint`, `pnpm test` and `pnpm build` are green"
tasks: [NL-2]
- name: "NL2 — a baseline"
exitCriteria:
- "blueprint.yaml (the console card) and repo-blueprint.yaml (the build) take a new product from nothing to live on stage and prod in one landing, then record it"
- "a product built from it carries the product only, renamed throughout to its own name, repository, Worker, Supabase project and Hyperdrive config"
- "Baseline CI is green: contract tests, generated component docs, the blueprint read by the pinned orun, the leak gate, the offline bootstrap and the end-to-end tier"
tasks: [NL-3]
49 changes: 49 additions & 0 deletions specs/epics/nl-postgres/implementation-plan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# nl-postgres — implementation plan

Three milestones, each one reviewed pull request (NL0 is the repository's
first commit and its spec), each green before it merges.

## NL0 — the spec (NL-1)

The repository is born: `intent.yaml` with the placeholder workspace
`ws_CHANGE_ME`, `ci.yml` (byte for byte rag-chatbot's, which is
turso-starter's with the comment lines its own copy changes), the shared
TypeScript and ESLint configuration, the wiring renderer and migration
helpers, the spec index, this doc set and the task contracts.

## NL1 — the app on Workers and Supabase (NL-2)

- The template in `apps/web` on Next.js 16.3.8: `app/actions.ts`'s four
actions with the model from `lib/ai/models.ts` and the SQL through
`lib/db.ts`'s `runReadOnlyQuery()`, the template's string check kept;
`lib/site.ts` (the name seam, the source link, the origin) read by the
layout and the header; the "Deploy with Vercel" button replaced by the
source link; `app/api/health/route.ts`; ESLint in eslint-config-next 16's
flat form.
- `wrangler.template.jsonc` + `wiring.fixture.json` (the `HYPERDRIVE` and
`AI` bindings), `component.yaml` (the smoke: the page's question box and
`/api/health`).
- `packages/db`: `010_unicorns`, `020_sample_unicorns`,
`030_row_level_security`, `040_read_only_queries`; the Supabase and
Hyperdrive roots; `infra/db-migrate`; `tooling/migrations/csv-to-sql.mjs`.
- `tests/web` (the actions and the string check, the model on Workers AI in
JSON mode and on OpenAI, the client and the read-only path, the health
check, the origin and the name) and `tests/db` (the manifest, the schema
and the sample rows, row-level security, every refusal of the read-only
path, the CSV loader), on PGlite.

## NL2 — a baseline (NL-3)

rag-chatbot's machinery on this tree: `blueprint.yaml` (Cloudflare and
Supabase, five brokered keys, the subdomain read from the connection, no AI
key), `repo-blueprint.yaml` (01-product, then 02-docs), `.baseline/`, the
rename engine, the bootstrap helpers, the deployment-record renderer probing
`/` and `/api/health` and reading which model writes the SQL, the phase
pages, the context pack, and the baseline's tests: manifest, phases,
coverage, rebrand, retouch, bootstrap-defer, the generated component docs,
the leak gate, the offline bootstrap with the product's own plan, and the
end-to-end tier — the migrations applied through a stand-in Supabase
Management API over a real Postgres, the built Worker served over it with
Workers AI stood in for, the page's four actions called as the page calls
them, and the SQL a model could be talked into refused by the template's
check or by the database.
13 changes: 13 additions & 0 deletions specs/epics/nl-postgres/risks-and-open-questions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# nl-postgres — risks and open questions

| ID | Risk | State | Notes |
|---|---|---|---|
| NL-A | `baseline-v1` is not yet proven live | OPEN | Proven offline in Baseline CI: the offline bootstrap with the blueprint's own hooks, the lanes' own steps in staged job trees (the migrations applied through a stand-in Supabase Management API over a real Postgres with Supabase's roles), and the built Worker served by `wrangler dev` over it. A live bootstrap needs a workspace with Cloudflare and Supabase connected and room for two Supabase projects (NL-E) |
| NL-B | The model is verified only against a stand-in | OPEN | The stand-in answers in Workers AI's JSON-mode shape, so the provider, the three structured outputs, the actions and the SQL path are real; what SQL a real Llama 4 Scout writes for a question — and how often it writes SQL the database must refuse — is not tested. A live build answers that; OpenAI's gpt-5.4-mini is one Worker secret away |
| NL-C | `040` on a real Supabase project | OPEN | The migration runs as `postgres` through the Management API: `CREATE ROLE`, `GRANT query_reader TO postgres WITH SET TRUE` (Postgres 16+), a function handed to `query_reader`. The e2e runs it as a non-superuser `postgres` with CREATEROLE on the runner's Postgres 16, and tests/db on PGlite (17); Supabase's own `postgres` role and supautils are not tested here |
| NL-D | Catalog metadata is visible to `query_reader` | ACCEPTED | Every role can read `pg_catalog` (table and column names, settings); `query_reader` can read no other table's rows and write nothing. The app has one table |
| NL-E | Two Supabase projects per product | ACCEPTED | Stage and prod are a project each; Supabase's free plan allows two active projects per organization. BOOTSTRAP.md lists it as a prerequisite |
| NL-F | The data is fictional until the owner loads CB Insights' list | ACCEPTED | CB Insights' list is not redistributed; the sample says it is fictional in the migration and on the page, and `csv-to-sql.mjs` turns the owner's download into a migration |
| NL-G | `workers-ai-provider` 3.x is deprecated | ACCEPTED | Its successor is built around AI Gateway; the 3.3.1 binding provider is what AI SDK 6 takes, rag-chatbot and nuxt-ai-chatbot use the same package, and tests/web runs the real provider against a fake binding in JSON mode |
| NL-H | `react-hooks/immutability` is off | ACCEPTED | `components/dynamic-chart.tsx` reassigns its prop, the template's code, kept as written; the rule is new in eslint-config-next 16 |
| NL-I | A query's `date` comes back as an ISO date string | ACCEPTED | The rows travel as JSON from `run_read_only`; upstream's `@vercel/postgres` gave the page `Date` objects, which `components/results.tsx` formats with `toLocaleDateString()`. Dates now show as `YYYY-MM-DD` |
15 changes: 15 additions & 0 deletions tasks/NL-1.TaskContract.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
apiVersion: orun.io/v1
kind: TaskContract
metadata:
name: NL-1
title: "The spec"
spec:
goal: The nl-postgres repository is born with its intent, CI, tooling and spec index, and the nl-postgres epic — declaration, doc set and task contracts — is on main
affects:
- specs/epics/nl-postgres
- specs/epics/README.md
- tasks
doneWhen:
- epic.yaml, README, design, implementation plan, risks and status are on main
- the three task contracts exist
gates: []
Loading
Loading