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
40 changes: 39 additions & 1 deletion .baseline/product/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,45 @@ The embeddings stay on Workers AI (`@cf/baai/bge-base-en-v1.5`) either way:
the index's column is sized to that model's 768 dimensions, and a question
embedded by one model cannot be compared with docs embedded by another.
Changing the embedding model is a migration plus re-indexing every page
(`POST /api/embeddings?refresh=1`); `ai/context/operations.md` says how.
(`POST /api/embeddings?refresh=1`, below); `ai/context/operations.md` says
how.

## Re-embedding every page

`POST /api/embeddings` — what every deploy's smoke calls — needs nothing:
it embeds only the pages whose checksum the database does not hold, so a
call with unchanged docs embeds nothing, and two at once embed a page once.
Its `?refresh=1` (upstream's `--refresh`) embeds EVERY page again, billed
to your Workers AI, so it needs a bearer: the environment's
`REINDEX_TOKEN`. Without one stored, refresh answers 403 and embeds
nothing — which is how a new product starts.

1. **Store a token**, once per environment, as this repository's Orun
secret (stage and prod can each hold their own):

```bash
openssl rand -hex 32 # a token; keep it
orun secrets set REINDEX_TOKEN --env stage # prompts for the value
orun secrets set REINDEX_TOKEN --env prod
```

The build never sees it: the deploy hands it to the Worker as a Worker
secret (`wrangler secret bulk`), so it is in no bundle and no log.
2. **Redeploy the app** (storing a secret deploys nothing): Orunbase's
Deploy button, or `gh workflow run ci.yml --ref main -f environment=<env>
-f component=web`.
3. **Refresh**:

```bash
curl -X POST -H "Authorization: Bearer <token>" \
https://doc-search-web-<env>.<your-subdomain>.workers.dev/api/embeddings?refresh=1
```

A missing or wrong bearer gets 403 and embeds nothing.

To turn refresh off again, delete the Orun secret and the Worker secret
(`pnpm exec wrangler secret delete REINDEX_TOKEN --name doc-search-web-<env>`
from `apps/web`): a deploy pushes the secrets that exist and deletes none.

## Tuning the search

Expand Down
2 changes: 1 addition & 1 deletion BOOTSTRAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ at the tag and refuses the whole catalogue if it 404s.
| web smoke fails on `"sections":0` after the index answered ok | the index stored nothing: `pages/docs` holds no `.mdx`, or `lib/docs/index.generated.json` was committed empty. Run `pnpm --filter @app/web docs:index`, commit it, and re-run |
| web deploy refused over the `AI` binding (an authentication error naming Workers AI) | the brokered deploy token cannot attach a Workers AI binding in this account. Reconnect Cloudflare with the recipe's permission groups (adding Workers AI if the recipe lists it) and re-run the phase |
| the search says the documentation has not been indexed yet | no deploy has indexed this environment (its smoke step never ran), or the database was reset. `curl -X POST <url>/api/embeddings` indexes it now |
| the search answers "Sorry, I don't know how to help with that." to every question | nothing scores above `MATCH_THRESHOLD` (0.6 by default). Lower it with a Worker secret (the product's README, "Tuning the search"), or `POST /api/embeddings?refresh=1` if the sections were embedded by another model |
| the search answers "Sorry, I don't know how to help with that." to every question | nothing scores above `MATCH_THRESHOLD` (0.6 by default). Lower it with a Worker secret (the product's README, "Tuning the search"), or `POST /api/embeddings?refresh=1` with the `REINDEX_TOKEN` bearer if the sections were embedded by another model (the product's README, "Re-embedding every page") |
| `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 |
Expand Down
7 changes: 4 additions & 3 deletions ai/context/open-risks.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ what is still live, so it should be short.
| DQ-C | The deploy's smoke indexes the docs: a Workers AI or Hyperdrive outage at deploy time fails the smoke (and the lane), and a deploy with many changed pages makes one request do every page's embedding | OPEN | The first live deploys; split the indexing into batches if a real doc set needs it |
| DQ-D | `MATCH_THRESHOLD`'s default (0.6) is chosen for BGE base, not measured on these docs | OPEN | Measure real scores on the sample docs after the first live bootstrap |

Accepted, and worth knowing before you change them: DQ-E (`POST
/api/embeddings` takes no credential: it can only embed the docs the Worker
was built with, and an unchanged page costs one SELECT), DQ-F (two Supabase
Accepted, and worth knowing before you change them: DQ-E (the plain `POST
/api/embeddings` is open by design — it can only embed the docs the Worker
was built with, and an unchanged page costs one SELECT — while `?refresh=1`,
which re-embeds everything, needs the `REINDEX_TOKEN` bearer), DQ-F (two Supabase
projects per product — the organization needs room for both), DQ-G (the
e2e's Postgres stand-in creates pgvector as superuser; a real db-migrate
apply is the first time `postgres` runs that statement).
7 changes: 4 additions & 3 deletions ai/context/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ Caveats that matter:
`nods_page_section.embedding` is `vector(768)` because
`@cf/baai/bge-base-en-v1.5` is 768-dimensional. Changing the model means a
new migration that resizes the column and the function, AND re-indexing
every page (`POST /api/embeddings?refresh=1`): vectors from two models
every page (`POST /api/embeddings?refresh=1` with the environment's
`REINDEX_TOKEN` as a bearer — README, "Re-embedding every page"): vectors from two models
share no space, even at the same size. Changing the ANSWER model is a
one-line change in `lib/ai/models.ts`, with no migration.
- **How strict the search is** is `MATCH_THRESHOLD` (cosine similarity,
Expand Down Expand Up @@ -186,10 +187,10 @@ orun integrations list --org <ws> --json && orun cloud check --org <ws>
| deploy a change | merge to `main`; watch the run; failed lanes → `gh run rerun --failed` |
| deploy by hand | Orunbase's Deploy button, or `gh workflow run ci.yml --ref main -f environment=<env> [-f component=<a,b>]` — the named components (blank: every one) run in that environment as a merge runs them; started off `main` it is refused |
| change the docs | edit `apps/web/pages/docs/**/*.mdx`, `pnpm --filter @app/web docs:index`, commit both, merge — the deploy embeds the pages that changed |
| index now | `curl -X POST https://doc-search-web-<env>.…workers.dev/api/embeddings` (idempotent: unchanged pages embed nothing; `?refresh=1` embeds every page again) |
| index now | `curl -X POST https://doc-search-web-<env>.…workers.dev/api/embeddings` (open and idempotent: unchanged pages embed nothing). `?refresh=1` embeds every page again and needs `-H "Authorization: Bearer $REINDEX_TOKEN"`, the environment's Orun secret (README, "Re-embedding every page"); without it, 403 |
| change the schema | a new `packages/db/src/migrations/<nnn>_<name>/up.sql` and its manifest entry (`pnpm --filter @saas/db run manifest:fix` for its checksum), merge — db-migrate applies it before the app deploys. Keep row-level security on every table in `public` |
| change the answer model | `WORKERS_AI_CHAT_MODEL` in `apps/web/lib/ai/models.ts` |
| change the embedding model | a new migration resizing `nods_page_section.embedding` and `match_page_sections()`, `WORKERS_AI_EMBEDDING_MODEL` and `EMBEDDING_DIMENSIONS` in `lib/ai/models.ts`, then `POST /api/embeddings?refresh=1` per environment |
| change the embedding model | a new migration resizing `nods_page_section.embedding` and `match_page_sections()`, `WORKERS_AI_EMBEDDING_MODEL` and `EMBEDDING_DIMENSIONS` in `lib/ai/models.ts`, then `POST /api/embeddings?refresh=1` with the bearer, per environment |
| tune the search | `wrangler secret put MATCH_THRESHOLD --name doc-search-web-<env>` (cosine similarity; default 0.6) |
| redeploy without a change | edit the last line of the component's `component.yaml` (`# orun: redeploy <reason> <stamp>`) and merge — it is a deploy trigger, nothing reads it |
| use OpenAI for the answers | above |
Expand Down
6 changes: 6 additions & 0 deletions apps/web/.dev.vars.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
# OPENAI_API_KEY=
# OPENAI_MODEL=gpt-3.5-turbo
#
# The bearer `POST /api/embeddings?refresh=1` (re-embed every page) needs.
# Unset, refresh answers 403; the plain POST, which embeds only changed
# pages, needs nothing. In stage/prod it is the Orun secret REINDEX_TOKEN,
# which the deploy hands to the Worker (README, "Re-embedding every page").
# REINDEX_TOKEN=
#
# How similar a section must be to the question to reach the answer, as
# cosine similarity (lib/search.ts, default 0.6).
# MATCH_THRESHOLD=0.6
3 changes: 3 additions & 0 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@ DATABASE_URL=postgres://postgres:postgres@localhost:5432/docs
# ANSWERS are OpenAI's; `next dev` reads it from here, `wrangler dev` from
# .dev.vars.
# OPENAI_API_KEY=
# Optional. The bearer POST /api/embeddings?refresh=1 needs; unset, refresh
# answers 403 (the plain POST needs nothing).
# REINDEX_TOKEN=
4 changes: 3 additions & 1 deletion apps/web/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ Vercel lists it at https://vercel.com/templates/next.js/nextjs-openai-doc-search
`lib/docs/index.generated.json`, with upstream's MDX processing in
`lib/docs/process-mdx.ts`); the deploy's smoke step POSTs here, and the
Worker embeds every page whose checksum the database does not hold
(`lib/docs/sync.ts`).
(`lib/docs/sync.ts`). `?refresh=1` re-embeds every page and needs the
environment's `REINDEX_TOKEN` as a bearer (`lib/reindex.ts`); unset, it
answers 403.
- `/api/health`: 200 only when the database is reachable through Hyperdrive
and migrated; it says how much of the docs is indexed and calls no model.

Expand Down
15 changes: 14 additions & 1 deletion apps/web/app/api/embeddings/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { DocsIndex } from '@/lib/docs/index-types'
import { syncDocs } from '@/lib/docs/sync'
import { DatabaseNotConfiguredError, getSql } from '@/lib/db'
import { AiNotConfiguredError, embeddingModel } from '@/lib/ai/models'
import { refreshRefusal } from '@/lib/reindex'

// Not upstream's route — upstream's step, moved. Upstream embedded the docs
// at `pnpm build` (`pnpm run embeddings`), with OpenAI's key and Supabase's
Expand All @@ -18,11 +19,23 @@ import { AiNotConfiguredError, embeddingModel } from '@/lib/ai/models'
// and only the pages whose checksum the database does not already hold, so
// calling it again — by the next deploy, a retry, or anybody — does one SELECT
// per page and embeds nothing. `?refresh=1` is upstream's `--refresh`: embed
// every page again, which only a change of embedding model calls for.
// every page again, which only a change of embedding model calls for. That
// one costs Workers AI on every call, so it needs the environment's
// REINDEX_TOKEN as a bearer (lib/reindex.ts) — refused with a 403, before the
// database or the model is reached, when it is missing, wrong, or unset.
export const dynamic = 'force-dynamic'

export async function POST(req: Request) {
const refresh = new URL(req.url).searchParams.get('refresh') === '1'
if (refresh) {
const refusal = await refreshRefusal(req)
if (refusal) {
return Response.json(
{ ok: false, error: refusal },
{ status: 403, headers: { 'cache-control': 'no-store' } }
)
}
}
let sql: Awaited<ReturnType<typeof getSql>> | undefined
try {
sql = await getSql()
Expand Down
3 changes: 3 additions & 0 deletions apps/web/cloudflare-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ interface CloudflareEnv {
ASSETS: Fetcher;
// Optional Worker secret (lib/ai/models.ts): upstream's OpenAI answer model.
OPENAI_API_KEY?: string;
// Optional Worker secret (lib/reindex.ts): the bearer POST
// /api/embeddings?refresh=1 needs. Unset, refresh is off.
REINDEX_TOKEN?: string;
// Optional Worker vars: which OpenAI chat model (default upstream's), and
// how similar a section must be to reach the answer (lib/search.ts).
OPENAI_MODEL?: string;
Expand Down
19 changes: 18 additions & 1 deletion apps/web/component.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ spec:
secretEnv:
WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://doc-search/doc-search/stage/WIRING_CLOUDFLARE_HYPERDRIVE"
WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://doc-search/doc-search/prod/WIRING_CLOUDFLARE_HYPERDRIVE"
# REINDEX_TOKEN: the bearer `POST /api/embeddings?refresh=1` (re-embed every
# page) needs (lib/reindex.ts). The owner stores it as an Orun secret per
# environment (README → Re-embedding every page); the build runs without it
# and then hands it to the Worker as a SECRET (buildCommand below).
# BEST-EFFORT, wire-now-seed-later: a key nobody has stored is skipped when
# the job resolves its secrets (no env var, no failure), and the Worker
# without it refuses refresh — so a fresh product deploys and indexes
# before anyone has chosen a token.
optionalSecretEnv:
REINDEX_TOKEN: "secret://doc-search/doc-search/{{ .environment }}/REINDEX_TOKEN"
subscribe:
environments:
- name: dev
Expand Down Expand Up @@ -104,7 +114,14 @@ spec:
# No public origin is baked in: the page renders no absolute URL (no Open
# Graph image, no canonical link), and every request it makes is to its
# own origin. ${ORUN_ENVIRONMENT} the runner sets for every step.
buildCommand: if [ "${ORUN_ENVIRONMENT}" != dev ]; then node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-hyperdrive --env "${ORUN_ENVIRONMENT}"; fi && pnpm exec turbo run build --filter=@app/web
#
# REINDEX_TOKEN never reaches the build (`env -u`), so neither a bundle
# nor the bundler's cache holds it. Then, if the environment has one, it
# goes to the Worker as a SECRET (tooling/wire/worker-secrets.mjs:
# `wrangler secret bulk`, the value over stdin) before the composition
# deploys it. Only the deploy lane holds a Cloudflare credential, so a
# verify lane builds the same and pushes nothing.
buildCommand: if [ "${ORUN_ENVIRONMENT}" != dev ]; then node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-hyperdrive --env "${ORUN_ENVIRONMENT}"; fi && env -u REINDEX_TOKEN pnpm exec turbo run build --filter=@app/web && node ../../tooling/wire/worker-secrets.mjs --secret REINDEX_TOKEN --worker "doc-search-web-${ORUN_ENVIRONMENT}" --config wrangler.jsonc

# Smoke — and the docs' indexing, which is the step upstream ran at build
# time (`pnpm run embeddings`). After `wrangler deploy`:
Expand Down
4 changes: 4 additions & 0 deletions apps/web/docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,7 @@ Resolved at deploy time from secrets the infrastructure lanes publish (names onl

- `WIRING_CLOUDFLARE_HYPERDRIVE_PROD`
- `WIRING_CLOUDFLARE_HYPERDRIVE_STAGE`

## Secrets resolved by the lane (names only)

- `REINDEX_TOKEN` (optional)
48 changes: 48 additions & 0 deletions apps/web/lib/reindex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { getCloudflareContext } from '@opennextjs/cloudflare'

// Not upstream's. `POST /api/embeddings` is open: it embeds only the pages
// whose checksum the database does not hold, so anybody calling it costs one
// SELECT per page, and the deploy's smoke calls it with no credential. Its
// `?refresh=1` — upstream's `--refresh` — is not: it embeds EVERY page again,
// billed to the owner's Workers AI, so it needs the environment's
// REINDEX_TOKEN as a bearer. The token is an optional Worker secret (an Orun
// secret the deploy hands to the Worker, README "Re-embedding every page").
// Unset, refresh is off.
export const REFRESH_DISABLED =
'refresh=1 re-embeds every page and is off here: this environment has no REINDEX_TOKEN (README, "Re-embedding every page")'
export const REFRESH_NEEDS_BEARER = 'refresh=1 needs Authorization: Bearer <REINDEX_TOKEN>'

async function configuredToken(): Promise<string | undefined> {
let env: Partial<CloudflareEnv> = {}
try {
env = (await getCloudflareContext({ async: true })).env
} catch {
// Not running under OpenNext (a script, a test): no bindings.
}
return env.REINDEX_TOKEN || process.env.REINDEX_TOKEN || undefined
}

async function digest(value: string): Promise<Uint8Array> {
return new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)))
}

/**
* Whether two secrets are equal, in time that depends on neither: both are
* hashed to 32 bytes first (so their lengths are not compared), and every byte
* of the digests is compared, whatever the first difference.
*/
export async function sameSecret(a: string, b: string): Promise<boolean> {
const [x, y] = await Promise.all([digest(a), digest(b)])
let difference = 0
for (let i = 0; i < x.length; i++) difference |= x[i] ^ y[i]
return difference === 0
}

/** Null when the request may re-embed everything, else why it may not. */
export async function refreshRefusal(req: Request): Promise<string | null> {
const token = await configuredToken()
if (!token) return REFRESH_DISABLED
const bearer = /^Bearer\s+(\S+)\s*$/i.exec(req.headers.get('authorization') ?? '')?.[1]
if (!bearer) return REFRESH_NEEDS_BEARER
return (await sameSecret(bearer, token)) ? null : REFRESH_NEEDS_BEARER
}
1 change: 1 addition & 0 deletions hooks/render-deployment-docs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ for the answers is a Worker secret the owner adds per environment (README,
| \`SUPABASE_ORG_ID\` | the workspace | the Supabase connection's organization id — a fact, not a credential |
| \`SUPABASE_PROJECT_REF\`, \`SUPABASE_DB_PASSWORD\`, \`SUPABASE_DB_URL\` | \`${repo}\` on stage and on prod | written by the Supabase root's apply: the project's ref, its database password and its connection URL, read by Hyperdrive and the migrations |
| \`WIRING_CLOUDFLARE_HYPERDRIVE\` | \`${repo}\` on stage and on prod | written by the Hyperdrive root's apply: the config's id and name, not a credential |
| \`REINDEX_TOKEN\` (optional) | \`${repo}\` on stage and on prod, if the owner stores it | the bearer \`POST /api/embeddings?refresh=1\` (re-embed every page) needs; each deploy hands it to the Worker as a Worker secret. Unset, refresh is refused (README, "Re-embedding every page") |

Brokered secrets are minted per run, so no long-lived value is at rest. No
AI vendor key is a workspace secret: OpenAI's key, if the owner adds it, is
Expand Down
2 changes: 1 addition & 1 deletion specs/epics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +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** | ✅ Shipped (`baseline-v1`); live bootstrap pending | 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) |
| [`doc-search/`](./doc-search/) | **DQ** | ✅ Shipped (`baseline-v2`); live bootstrap pending | 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`.
Loading
Loading