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 |
|------|---------|--------|------------|
| [`doc-search/`](./doc-search/) | **DQ** | In progress (DQ0) | Supabase's Next.js OpenAI Doc Search — a ⌘K dialog answering questions about the site's own MDX docs — on Cloudflare Workers with Workers AI and Supabase pgvector through Hyperdrive, the docs indexed by the deployed Worker on every deploy, and an Orun baseline that instantiates it in one landing (DQ2) |

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

| Milestone | State | Landed |
|---|---|---|
| DQ0 — the spec | ✅ | DQ-1 |
| DQ1 — the doc search on Workers and Supabase | planned | DQ-2 |
| DQ2 — a baseline | planned | DQ-3 |

## Departures from the upstream template

Recorded as they land, from DQ1 on.
35 changes: 35 additions & 0 deletions specs/epics/doc-search/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# doc-search — Supabase's Next.js OpenAI Doc Search on Cloudflare

**The template's app as it is — a ⌘K search dialog that answers a question
about the site's own MDX docs, streamed, from the sections closest to it by
vector similarity — on one Cloudflare Worker, the docs embedded and the
answer written by Workers AI, the vectors in a Supabase project's pgvector
behind Hyperdrive; the docs indexed by the deployed Worker, never by a build
holding a key; and the baseline that makes a copy of it somebody else's
product in one landing.**

| | |
|---|---|
| Status | In progress — DQ0 on main |
| Upstream | [supabase-community/nextjs-openai-doc-search](https://github.com/supabase-community/nextjs-openai-doc-search) (Apache-2.0), Vercel's [Next.js OpenAI Doc Search Starter](https://vercel.com/templates/next.js/nextjs-openai-doc-search-starter), at `50d6bb7` |
| Reference | [rag-chatbot](https://github.com/sourceplane/rag-chatbot) — an AI SDK app on Workers AI and Supabase pgvector through Hyperdrive, the 768-dimension migration, db-migrate, the e2e's Workers AI stand-in |
| Key | `DQ` |

## Read in this order

1. [design.md](design.md) — the template, how each piece maps to Cloudflare
and Supabase, where the docs are embedded and why there, the models and
the search, the repository, 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 |
|---|---|---|
| DQ0 — the spec | the repository, its intent, CI, tooling and spec index; this doc set | DQ-1 |
| DQ1 — the doc search on Workers and Supabase | the template in `apps/web`, the models on Workers AI, the docs index and the Worker's indexing, the migrations, the Supabase and Hyperdrive roots, the tests | DQ-2 |
| DQ2 — a baseline | the console card, the build document, the context pack and the baseline's tests | DQ-3 |
149 changes: 149 additions & 0 deletions specs/epics/doc-search/design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# doc-search — design

## 1. The template

Supabase's Next.js OpenAI Doc Search Starter
([supabase-community/nextjs-openai-doc-search](https://github.com/supabase-community/nextjs-openai-doc-search),
Apache-2.0) is a Next.js 13.2 Pages Router app with one page and one API
route. The page (`pages/index.tsx`) opens a ⌘K dialog
(`components/SearchDialog.tsx`) whose question goes to
`pages/api/vector-search.ts`, an edge-runtime route that, with `OPENAI_KEY`:

1. sends the question to OpenAI's moderation endpoint and refuses a flagged
one;
2. embeds it with `text-embedding-ada-002` (1536 dimensions);
3. calls `match_page_sections(embedding, 0.78, 10, 50)` over Supabase's Data
API with the **service-role key** — an inner-product match over every
section of every page;
4. fills a 1500-token context from the matches (counted with GPT-3's
tokenizer), builds its prompt — answer only from the docs, in markdown,
or say "Sorry, I don't know how to help with that." — and streams
`gpt-3.5-turbo`'s answer (`OpenAIStream` from `ai` 2.x).

The docs are the site's own MDX files under `pages/docs` (one sample page on
OpenAI embeddings). `pnpm build` runs `pnpm run embeddings && next build`:
`lib/generate-embeddings.ts` walks `pages`, splits each MDX file into
sections by heading, hashes the file, and — holding `OPENAI_KEY` and
`SUPABASE_SERVICE_ROLE_KEY` at build time — embeds and upserts every page
whose checksum changed (`--refresh` re-embeds all). Its schema is one
Supabase migration: `nods_page` and `nods_page_section` (a
`vector(1536)` column), row-level security with no policies, and the two
functions.

## 2. How it maps to Cloudflare and Supabase

| Upstream | Here | Why |
|---|---|---|
| Next.js 13.2 hosting, an edge-runtime API route | One Worker (`.open-next/worker.js`) + Static Assets, built by `@opennextjs/cloudflare` on Next.js 16.3.8. The page stays on the Pages Router; the search is an App Router route handler (`app/api/vector-search/route.ts`) | The adapter needs a supported Next.js; an edge-runtime route does not run under OpenNext, and a route handler keeps the route's Request/Response code as upstream wrote it |
| `OpenAIStream` / `StreamingTextResponse` (`ai` 2.x), `useCompletion` from `ai/react` | AI SDK 5: `streamText(...).toTextStreamResponse()`, `useCompletion` from `@ai-sdk/react` with `streamProtocol: 'text'` | The same plain-text stream to the same dialog; `ai` 2.x has no Workers AI provider |
| OpenAI for everything | Workers AI through the `AI` binding (§5); OpenAI optional, for the answer only | A product answers on its first deploy with no vendor key |
| supabase-js with the service-role key, `rpc('match_page_sections')` | SQL over the `HYPERDRIVE` binding, a `postgres` client per call (§3) | No service-role key exists for a product to hold |
| `supabase/migrations` applied with the Supabase CLI | `packages/db` + `infra/db-migrate` (§3) | One schema, applied in order before the Worker deploys, recorded in a ledger |
| The build embeds the docs | The build splits them; the deployed Worker embeds them (§4) | The build holds no credential |
| A Supabase project from the dashboard | `infra/terraform/supabase` (one project per environment) + `infra/terraform/cloudflare-hyperdrive` (one config per environment) | rag-chatbot's roots |
| "Deploy with Vercel" | `orun new --blueprint repo-blueprint.yaml` | |

## 3. The database

The app reaches the Supabase project's Postgres as `postgres` through a
Hyperdrive config, with SQL (`lib/db/index.ts`: `postgres` with
`prepare: false`, `fetch_types: false`, a client per call, ended in
`finally`). It never touches the Data API, so no service-role or anon key is
in the product.

- **`010_doc_search_init`** — upstream's migration byte for byte: the
`vector` extension, both tables with row-level security and no policies,
`get_page_parents()` and `match_page_sections()`.
- **`020_workers_ai_embeddings`** — refuses (and changes nothing) if the
column already holds vectors of another size; resizes
`nods_page_section.embedding` to `vector(768)`; recreates
`match_page_sections()` with cosine similarity (`1 - (embedding <=> q)`,
so the threshold reads as a similarity whatever the vectors' norms) and
returns each section's `token_count`, which the route counts the context
with instead of re-tokenising in the Worker.
- **`030_data_api_closed`** — revokes `EXECUTE` on both functions from
`PUBLIC`, `anon` and `authenticated`. Row-level security already hid every
row from those roles; the functions were still callable through the Data
API's RPC, and nothing needs them there.

## 4. Where the docs are embedded

Upstream embeds at build time with two credentials in the build's
environment. Here the build must hold none, and the CI runner has no
Workers AI binding anyway. The Worker does: it has `AI` and `HYPERDRIVE`.
So the work splits in two.

- **The build** (`scripts/build-docs-index.ts`, first step of `pnpm build`)
runs upstream's MDX processing (`lib/docs/process-mdx.ts`, upstream's code
moved, not rewritten) over `pages/docs`, counts each section's tokens with
upstream's tokenizer, and writes `lib/docs/index.generated.json`: every
page's path, meta, checksum and sections. It is committed, so a fresh
checkout typechecks and tests; `pnpm test` fails a stale one.
- **The Worker's `POST /api/embeddings`** (`lib/docs/sync.ts`) reads that
index and, page by page, in ONE transaction per page under
`pg_advisory_xact_lock(hashtext('nods_page:' || path))`: skips a page
whose stored checksum matches (upstream's rule); otherwise upserts the page
with a NULL checksum, deletes its old sections, embeds the new ones in one
Workers AI call, inserts them, and sets the checksum last — so a failure
rolls the page back whole and the next run retries it. `?refresh=1` is
upstream's `--refresh`. A page that failed is named in the response, which
is then a 500.
- **The deploy's smoke** POSTs it, then requires `/api/health` to report
more than zero sections. Every deploy indexes what changed and nothing
else; a redeploy with the same docs costs one SELECT per page.

The endpoint takes no credential: all it can do is embed the docs the Worker
was built with (risk DQ-E).

## 5. The models and the search

`lib/ai/models.ts`:

- **Embeddings — always Workers AI**, `@cf/baai/bge-base-en-v1.5`, 768
dimensions, the column's size. The docs and the question must come from
the same model, so no key switches this. BGE reads at most 512 tokens; a
longer section is embedded from its first 2000 characters and stored
whole.
- **The answer — Workers AI** `@cf/meta/llama-4-scout-17b-16e-instruct`,
streamed. With `OPENAI_API_KEY` (a Worker secret), upstream's own: OpenAI's
chat model (`OPENAI_MODEL`, default `gpt-3.5-turbo`) straight from OpenAI
through `@ai-sdk/openai`, and upstream's moderation call first, because it
is OpenAI's model the question reaches. No gateway.

`app/api/vector-search/route.ts` keeps upstream's steps, counts and prompt;
the threshold is `MATCH_THRESHOLD` (cosine, default 0.6 — upstream's 0.78
was ada-002's inner product, risk DQ-D). An index with no sections answers
200 with a sentence saying the docs are not indexed yet, never a 500. A
missing binding is a 503 naming it.

## 6. 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/`. `apps/web/wrangler.jsonc` is committed as the fixture's
render; the stage and prod lanes re-render it from the Hyperdrive wiring
document. Per environment, on a push to main: supabase →
cloudflare-hyperdrive → db-migrate → web, every edge enforced.

## Alternatives rejected

- **Embedding at `next build` in CI.** It needs a Workers AI credential and
a database URL in the build, which is exactly what upstream did with its
two keys and what this build must not do.
- **A separate indexing job in the pipeline** (a component that runs after
the deploy). It would need the same two credentials on the runner; the
deployed Worker already holds both bindings, and its smoke is the step
that runs after the deploy.
- **Embedding on the first search.** The first visitor would pay for the
whole doc set, and two visitors at once would race.
- **OpenAI embeddings when `OPENAI_API_KEY` is set.** ada-002's 1536
dimensions cannot share the 768 column, and switching would orphan every
stored vector.
- **Carrying upstream's `seed.sql`.** It holds ada-002 vectors.
- **Supabase's Data API with a service-role key.** A credential the product
would have to hold for what Hyperdrive does as the tables' owner.
- **Moving the page to the App Router.** The page has no server data, and
the template is a Pages Router app; only the route had to move.
31 changes: 31 additions & 0 deletions specs/epics/doc-search/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 (DQ → DQ-1, DQ-2, …). Owner, target
# date and health are the platform's — never written here.
apiVersion: orun.io/v1
kind: Epic
metadata:
name: doc-search
key: DQ
spec:
title: "Supabase's Next.js OpenAI Doc Search on Cloudflare Workers"
summary: "Supabase's Next.js OpenAI Doc Search Starter — a ⌘K dialog that answers a question about a site's MDX docs from the sections closest to it — run on Cloudflare Workers + Static Assets through @opennextjs/cloudflare, the docs embedded and the answer written by Workers AI through the Worker's AI binding (OpenAI for the answer optional), its Postgres a Supabase project with pgvector reached through Hyperdrive, both provisioned by Terraform; the schema applied by db-migrate, the docs indexed by the deployed Worker on every deploy, never by a build holding a credential; 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: "DQ0 — 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: [DQ-1]
- name: "DQ1 — the doc search on Workers and Supabase"
exitCriteria:
- "apps/web is the template on Next.js 16.3.8, the page on the Pages Router, the search and the indexing App Router route handlers, built by OpenNext into one Worker"
- "the embeddings are Workers AI's bge-base-en-v1.5 at 768 dimensions and the answer Llama 4 Scout, streamed, through the AI binding; OPENAI_API_KEY switches only the answer to OpenAI, straight from OpenAI, with upstream's moderation — never a gateway"
- "the build splits the docs into a committed index with no credential; the Worker's POST /api/embeddings embeds every page whose checksum the database does not hold, one transaction per page under an advisory lock"
- "an empty index answers 200 and says so; upstream's schema, the 768-dimension cosine resize and the Data API's revoke 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: [DQ-2]
- name: "DQ2 — 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, its docs indexed by the deploy's smoke, 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: [DQ-3]
57 changes: 57 additions & 0 deletions specs/epics/doc-search/implementation-plan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# doc-search — implementation plan

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

## DQ0 — the spec (DQ-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.

## DQ1 — the doc search on Workers and Supabase (DQ-2)

- The template in `apps/web` on Next.js 16.3.8, the page on the Pages
Router with upstream's UI pins: `pages/index.tsx` titled by `SITE_NAME`
and linking `SOURCE_URL` (`lib/site.ts`), the unused Google font dropped;
`components/SearchDialog.tsx` on `@ai-sdk/react`'s `useCompletion`, plain
text stream.
- `app/api/vector-search/route.ts` (upstream's steps and prompt, the model
from `lib/ai/models.ts`, the match over `lib/db`, the empty index
answered), `app/api/embeddings/route.ts` and `lib/docs/sync.ts` (the
Worker's indexing), `app/api/health/route.ts`.
- `lib/docs/process-mdx.ts` (upstream's MDX processing),
`scripts/build-docs-index.ts` → `lib/docs/index.generated.json`, run first
by `pnpm build`.
- `wrangler.template.jsonc` + `wiring.fixture.json` (the `HYPERDRIVE` and
`AI` bindings), `component.yaml` (the smoke: the page, the index, the
health check with sections).
- `packages/db`: `010_doc_search_init` (upstream's), `020_workers_ai_embeddings`,
`030_data_api_closed`; the Supabase and Hyperdrive roots;
`infra/db-migrate`.
- `tests/web` (the models on Workers AI and OpenAI, the sync's checksum
skip, refresh, roll-back and lock, the routes over PGlite with pgvector,
the docs index's freshness, the name seam, the Worker's config) and
`tests/db` (the manifest, the schema at 768 dimensions, the cosine match,
the revoke).

## DQ2 — a baseline (DQ-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 (upstream's repository and Vercel's template page masked: both
end in this baseline's slug), the bootstrap helpers, the deployment-record
renderer probing `/` and `/api/health` and recording how much of the docs is
indexed and which model answers, 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 with pgvector, the built Worker served over it with Workers AI
stood in for, the empty index asserted before the product's own smoke
indexes it, a second index embedding nothing, two at once embedding once, a
question answered from the matched section, and the Data API's roles shut
out of the rows and the functions.
Loading
Loading