Joel Stevick

Running it · What is kept, and who reads it · stage 8 of 10

Consent and the archive

X-Demo-Keep carries the site's consent decision and decides what outlives the idle purge. X-Demo-Via only records which route a question came through, in questions.via. With consent, an upload archives each page's text and each question is stored with keep = 1, and both are retained for 25 months (KEEP_MONTHS). Three internal GET routes read this data back for the site's /admin: a list of demo accounts (visitors' rows in the demos table), one account in full, and an export of kept questions as JSONL for building a golden set.

Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
demo/src/app.ts149 / 149 lines on this page explainedlines 85-95,926-1063 of 1124; the rest are on other stage pages
In the browser
runs in the visitor's browser, on the demo page
Ingestion
runs when a PDF's text is uploaded
Query time
runs when the Worker answers a question or a search_documents call from the MCP server, and in the request handling every route shares, in the Worker and in the site's functions, which uploads and removals pass through too
MCP request
runs on a request to the MCP server or its OAuth endpoints
Site request
runs on a site request that is not a question, an upload, an MCP call or the cron: a page load, a session read, the demo page's /api/grants calls, an admin read, a file's removal
Scheduled
runs in the Worker's daily cron job
Eval run
runs when the eval harness runs on a developer's machine
MCP host
runs in an MCP host outside the Worker: the search loop example, on a developer's machine (npm run search) or in its test
Module load
runs once, when the module is loaded
Type only
erased by the TypeScript compiler; never runs
Never runs
a comment, a licence or markup with no behaviour of its own

Pinned to joelstevick-demo-rag-pipeline at 6a9c6c7.

demo/src/app.ts The demo Worker.

keeps()

function · lines 85–86View on GitHub

Whether the site says this visitor may be recorded.

Called by answering(): the generator's contract, timer and record() Worker router upload(): INGEST 5 Store the chunks

/** Whether the site says this visitor may be recorded, so their questions are kept and their pages archived. */const keeps = (request: Request) => request.headers.get('X-Demo-Keep') === '1'

Consent, as one header Query time

WhatAn arrow function that returns true only when X-Demo-Keep is exactly '1'. INGEST 5 calls it on an upload to decide whether to archive each page's text, and answering()'s record() calls it on a question to set the question's keep column on every outcome, fallbacks included. It is assigned at module load and does its work when called, on uploads and questions alike, so it is marked Query time, the value for code that runs on both.

WhyThe site decides consent, and the Worker only reads the decision. The site uses mayRecord, which in the EEA, the UK and Switzerland allows recording only after the cookie banner is accepted. Both site proxies set the header to '1' or '0' themselves: the page's proxy builds fresh headers, and the MCP proxy (functions/_lib/demo-mcp.ts) deletes every X-Demo-* header the caller sent before setting it. A visitor therefore cannot set it. Any value other than '1', including no header, means do not keep. In this repository's stand-in (functions/_lib/track.ts), mayRecord always returns false.

header: X-Demo-Keep

via()

function · lines 87–95View on GitHub

Which route a question came through, stored in questions.via.

Called by answering(): the generator's contract, timer and record() Worker router

/** * Which door a question came through, for `questions.via`: 'mcp' from the MCP server, 'canary' from the daily * canary (both set X-Demo-Via themselves, in process; the page's proxy never forwards the header), else NULL, the page. */

Three values: 'mcp', 'canary', NULL Never runs

WhatThe doc comment: 'mcp' for the MCP server's ask_documents, 'canary' for the daily canary, and NULL for the page.

WhyThe two callers other than the page build their Request in process and set the header themselves. The page's proxy builds fresh headers and never copies X-Demo-Via, so a browser cannot label its own question.

header: X-Demo-Via

const via = (request: Request) => {  const said = request.headers.get('X-Demo-Via')  return said === 'mcp' || said === 'canary' ? said : null}

An allow-list Query time

WhatReturns the header only if it is 'mcp' or 'canary', and null otherwise. It is assigned at module load and does its work when answering()'s record() calls it, each time a question is stored.

WhyThe allow-list lets only known values reach the column. The daily health roll-up (rollUp in demo/src/health.ts, run by dailyHealth) splits counts by via and leaves canary questions out, and adminDemo returns each question's via.

'mcp', 'canary' or null

DemoRow

interface · lines 926–939View on GitHub

One demo account as /admin reads it.

interface DemoRow {  id: string  engagement_id: string | null  company: string | null  contact: string | null  created_at: string  used_at: string | null  cleared_at: string | null  purged_at: string | null  files: number  pages: number  asks_used: number  questions: number}

The admin's view of a demo account Type only

WhatThe account's id, engagement, company and contact, its four timestamps (created, last used, cleared, purged), its files, pages and asks_used, and questions, a count computed by a subquery.

WhyIt is the row type both admin queries pass to .all<DemoRow>() and .first<DemoRow>(). It omits key_hash and card_fingerprint, so no secret or identity hash leaves the Worker on these routes.

adminDemos()

async function · lines 940–954View on GitHub

GET /internal/admin/demos: every visitor's demo account, newest first, optionally filtered by email.

Called by route(): the site's calls and MCP Worker routerCalls json() Shared helpers

/** Every demo, newest first, or those whose contact is `email`: for /admin. The canary (health.ts) is not a visitor's demo and is left out. */async function adminDemos(url: URL, env: Env): Promise<Response> {  const email = (url.searchParams.get('email') ?? '').trim().toLowerCase()

Signature and the email filter Site request

WhatReads the email query parameter, trimmed and lower-cased. An empty value means no filter.

WhyLower-casing here and lower(d.contact) in SQL make the match case-insensitive. The route is reachable only through the DEMO service binding, because the Worker has no public URL and the proxy never forwards /internal. The site's own admin check is therefore what guards it.

  // Matched as the whole contact or as the address in its angle brackets; an empty email lists every demo.  const rows = await env.DB.prepare(    `SELECT d.id, d.engagement_id, d.company, d.contact, d.created_at, d.used_at, d.cleared_at, d.purged_at, d.files, d.pages, d.asks_used,       (SELECT COUNT(*) FROM questions q WHERE q.demo_id = d.id) AS questions     FROM demos d WHERE d.card_fingerprint IS NOT 'canary:v1' AND (?1 = '' OR lower(d.contact) = ?1 OR substr(lower(d.contact), -(length(?1) + 2)) = '<' || ?1 || '>')     ORDER BY d.created_at DESC, d.rowid DESC LIMIT 500`,  ).bind(email).all<DemoRow>()

Match the contact, leave out the canary Site request

WhatSelects DemoRow's columns with a question count per account. An account matches when ?1 is empty, when the whole contact equals the email, or when the last length(email) + 2 characters of the contact are exactly '<email>', the address in angle brackets. The canary's demo account (card_fingerprint 'canary:v1') is excluded. Rows come newest first, at most 500.

WhyContacts are stored as "Name <address>", so the suffix test finds an address without a LIKE pattern, which an address containing % or _ could subvert. IS NOT is SQLite's null-safe inequality. The canary is excluded because it is a fixed test account with no visitor behind it.

LIMIT 500excluded: card_fingerprint 'canary:v1'

  return json(200, { demos: rows.results })}

The JSON reply Site request

WhatReturns 200 with { demos: [...] }.

WhyThe rows are returned as read, and the site's admin page renders them.

adminDemo()

async function · lines 955–1014View on GitHub

GET /internal/admin/demos/<id>: one demo account with each file's text, every question and its connected apps.

Called by route(): the site's calls and MCP Worker routerCalls appsOf() Listing and disconnecting apps json() Shared helpers

/** One demo for /admin: its files with each page's text (live, else archived) and every question. */async function adminDemo(id: string, env: Env): Promise<Response> {  // The demo's row with its question count; an unknown id is a 404.  const demo = await env.DB.prepare(    `SELECT d.id, d.engagement_id, d.company, d.contact, d.created_at, d.used_at, d.cleared_at, d.purged_at, d.files, d.pages, d.asks_used,       (SELECT COUNT(*) FROM questions q WHERE q.demo_id = d.id) AS questions FROM demos d WHERE d.id = ?`,  ).bind(id).first<DemoRow>()  if (demo === null) return json(404, { error: 'no demo' })

The account's row, or 404 Site request

WhatReads the same DemoRow columns for the id the router decoded from the path. An unknown id returns 404.

WhyThe query has no purged_at filter, so an admin can open any account, including one whose documents were purged, to read what was archived.

  // Its files, live chunks, archived pages and questions, read in one batch.  const [files, chunks, archived, questions] = await env.DB.batch([    env.DB.prepare('SELECT name, pages, skipped FROM files WHERE demo_id = ? ORDER BY rowid').bind(id),    env.DB.prepare('SELECT file, page, text FROM chunks WHERE demo_id = ? ORDER BY file, page, seq, rowid').bind(id),    env.DB.prepare('SELECT file, page, text, archived_at FROM archived_pages WHERE demo_id = ? ORDER BY file, page').bind(id),    env.DB.prepare('SELECT id, asked_at, question, answer, sources, checked, fallback, ms, keep, via FROM questions WHERE demo_id = ? ORDER BY asked_at, rowid').bind(id),  ])

Four reads in one batch Site request

WhatOne D1 batch reads the account's files rows, every live chunk (ordered by file, page, seq, rowid), every archived page, and every question with its keep, via, fallback and ms columns, oldest first.

WhyA batch is one round trip to D1 and runs as one transaction, so the files and the chunks cannot disagree because an upload landed between two reads. The chunk order lets the next block rebuild each page in reading order.

  // One page of text: its number and what it says.  type Page = { page: number; text: string }

The Page type Type only

WhatA local type: a page number and its text.

WhyBoth the archived pages and the rebuilt live pages are returned in this shape.

  // Live text: each file's chunks regrouped by page, so a page reads as its chunks joined in order.  const live = new Map<string, Map<number, string[]>>()  for (const c of chunks.results as { file: string; page: number; text: string }[]) {    const pages = live.get(c.file) ?? new Map<number, string[]>()    pages.set(c.page, [...(pages.get(c.page) ?? []), c.text])    live.set(c.file, pages)  }

Live text, regrouped by page Site request

WhatBuilds a map from each file to a map from page number to chunk texts, appending each chunk in the order read.

WhyChunks never cross a page and are verbatim, non-overlapping slices of it (chunks.ts), so joining a page's chunks reproduces the extracted page text. The one difference is at each cut, where the whitespace becomes a single newline; a word cut at the 900-character limit (CHUNK_CHARS) gets a newline inside it.

  // Archived text: each file's pages as uploaded, kept with consent after the chunks are purged.  const kept = new Map<string, Page[]>()  for (const a of archived.results as { file: string; page: number; text: string }[]) kept.set(a.file, [...(kept.get(a.file) ?? []), { page: a.page, text: a.text }])

Archived text, by file Site request

WhatBuilds a map from each file to its archived pages, in page order.

WhyThe archive exists only for uploads made with consent, and it outlives the idle purge. For a purged account it is the only text left.

  // Every file name, whether it is still uploaded or only archived.  const names = [...new Set([...(files.results as { name: string }[]).map((f) => f.name), ...kept.keys()])]  // Each still-uploaded file's row, by name, for its page count.  const listed = new Map((files.results as { name: string; pages: number; skipped: string }[]).map((f) => [f.name, f]))

Every file name Site request

Whatnames is the union of the files still uploaded and the files only archived, de-duplicated by a Set. listed maps each uploaded file's name to its row.

WhyA purge deletes the files rows and leaves the archive, so without the union an admin would not see archived files at all.

  // The demo, each file with its text, every question with its sources parsed, and the connected apps.  return json(200, {    demo,    files: names.map((name) => {      // The file's live pages, if it is still in the index.      const index = live.get(name)      return {        name,        pages: listed.get(name)?.pages ?? kept.get(name)?.length ?? 0,        in_index: index !== undefined,        archived: kept.has(name),

Each file: pages, in_index, archived Site request

WhatFor each name: pages is the files row's page count, else the number of archived pages, else 0; in_index says whether the file still has live chunks; archived says whether it has archived pages.

WhyFor an archived-only file the count covers only pages with text, because empty pages were never archived, so it can be lower than the PDF's page count.

        // The live text while the file is still indexed, else the archived pages.        text: index !== undefined          ? [...index.entries()].sort(([a], [b]) => a - b).map(([page, parts]) => ({ page, text: parts.join('\n') }))          : kept.get(name) ?? [],      }    }),

The text: live if indexed, else archived Site request

WhatLive pages are sorted by page number, and each page's chunks are joined with newlines. A file with no live chunks gets its archived pages, or an empty list.

WhyThe live text is exactly what retrieval searches now, so it is preferred while it exists.

    questions: (questions.results as Record<string, unknown>[]).map((q) => ({ ...q, sources: JSON.parse(String(q.sources ?? '[]')) })),

Every question Site request

WhatEach question row as stored, with sources parsed from its JSON text (a missing value reads as []).

WhyThe admin sees refusals, fallbacks and failures as well as the answers shown, which is what diagnosing the pipeline needs.

    // The apps connected to this demo through its MCP server (demo/src/oauth.ts); none when it has no store.    apps: await appsOf(env, id).catch(() => []),  })}

Connected apps Site request

WhatappsOf lists the OAuth grants (one per app the visitor let connect) the MCP server holds for this account. Any error from the store becomes an empty list.

WhyA failure of the OAuth KV store should not hide the rest of the account from the admin.

golden()

async function · lines 1015–1063View on GitHub

GET /internal/admin/golden: kept questions as JSONL, each with its cited archived pages, for building a golden set.

Called by route(): the site's calls and MCP Worker router

/** * Kept questions as JSONL for a golden set: each with its sources and the archived text of * every cited page and the pages either side. The answer is the model's, never checked by a * person, and is labelled so: build-evals takes required facts from the source text only. */

Unverified by design Never runs

WhatThe doc comment: one line per kept question, with its sources and the archived text of each cited page and its neighbours. The answer is the model's, and no person checked it.

WhyA golden set's expected facts must come from the source text, never from the model under test. Labelling the answer unverified stops it from being copied in as ground truth.

async function golden(url: URL, env: Env): Promise<Response> {  // The date range and the demo are optional filters; the defaults take every kept question.  const from = url.searchParams.get('from') || '0000'  const to = url.searchParams.get('to') || '9999'  const demoId = url.searchParams.get('demo') ?? ''

Optional filters Site request

Whatfrom defaults to '0000', to defaults to '9999', and the demo parameter (an account id) defaults to empty (every account).

WhyThe defaults sort below and above every stored 'YYYY-MM-DD HH:MM:SS' value, so with no filters every kept question is exported.

  // The kept questions in range, oldest first, with each demo's company.  const rows = await env.DB.prepare(    `SELECT q.id, q.demo_id, d.company, q.asked_at, q.question, q.answer, q.fallback, q.checked, q.sources     FROM questions q JOIN demos d ON d.id = q.demo_id     WHERE q.keep = 1 AND q.asked_at >= ?1 AND q.asked_at < ?2 || 'z' AND (?3 = '' OR q.demo_id = ?3)     ORDER BY q.asked_at, q.rowid`,  ).bind(from, to, demoId).all<{ id: string; demo_id: string; company: string | null; asked_at: string; question: string; answer: string | null; fallback: string | null; checked: number; sources: string }>()

Kept questions in range Site request

WhatJoins questions to the demos table for the company and keeps only rows with keep = 1, asked_at >= from and asked_at < to || 'z', optionally for one account, oldest first.

WhyOnly questions asked with consent may be exported. Appending 'z' makes to include the whole day: '2026-11-28 23:59:59' sorts before '2026-11-28z' because a space sorts before 'z'.

  // One JSON line per question.  const lines: string[] = []  for (const q of rows.results) {    // Each source keeps only its file and pages; the text comes from the archived pages read below.    const sources = (JSON.parse(q.sources) as { file: string; page: number; last_page?: number }[]).map((s) => ({ file: s.file, page: s.page, ...(s.last_page ? { last_page: s.last_page } : {}) }))

Sources without passages Site request

WhatEach recorded source is reduced to file, page and, when present, last_page.

WhyThe passage text stored with the question is dropped. The export takes its text from the archived pages instead, which hold the whole pages as uploaded.

    const wanted = new Set<string>()    // The cited pages and one either side, as (file, page) pairs; keyed by their JSON, since a Set compares arrays by identity.    for (const s of sources) for (let p = s.page - 1; p <= (s.last_page ?? s.page) + 1; p++) if (p >= 1) wanted.add(JSON.stringify([s.file, p]))

The cited pages and one either side Site request

WhatFor each source, every page from page − 1 to (last_page or page) + 1, never below 1, is added to a Set as the JSON text of [file, page].

WhyAn answer often depends on text that runs over a page break, so the neighbouring pages are included for whoever writes the case. A Set compares arrays by identity, so the pairs are keyed by their JSON to remove duplicates.

    // One query per question (D1 caps the queries a request may make), at most 45 pages (90 bound values) each.    const pairs = [...wanted].slice(0, 45).map((key) => JSON.parse(key) as [string, number])    const pages: { file: string; page: number; text: string }[] = pairs.length === 0 ? [] : (await env.DB.prepare(      `SELECT file, page, text FROM archived_pages WHERE demo_id = ? AND (file, page) IN (VALUES ${pairs.map(() => '(?, ?)').join(', ')})`,    ).bind(q.demo_id, ...pairs.flat()).all<{ file: string; page: number; text: string }>()).results

One query per question Site request

WhatReads at most 45 pairs in one statement: WHERE demo_id = ? AND (file, page) IN (VALUES (?, ?), ...), a SQLite row-value comparison.

WhyOne statement per question, instead of one per page, keeps the number of D1 queries in the request low, since D1 limits queries per Worker invocation. The 45-pair cap keeps the statement at 91 bound values (90 plus the account id), under D1's per-statement limit on bound parameters. Pages come only from archived_pages, so a question whose upload was made without consent, or whose file was removed, exports no pages.

max 45 pages per question45 pairs × 2 + the account id = 91 bound values

    // In file and page order, so the pages read in sequence.    pages.sort((a, b) => a.file.localeCompare(b.file) || a.page - b.page)

Reading order Site request

WhatSorts the pages by file name (localeCompare), then by page number.

WhyThe IN query returns rows in no guaranteed order. Sorting makes consecutive pages read in sequence.

    // The line: the question, the model's unchecked answer, its sources and the archived pages.    lines.push(JSON.stringify({      demo: q.demo_id, company: q.company, asked_at: q.asked_at, question: q.question,      model_answer_unverified: q.answer, fallback: q.fallback, checked: q.checked === 1, sources, pages,    }))

One JSON object per question Site request

WhatOne JSON object: demo (the account id), company, asked_at, question, model_answer_unverified, fallback, checked as a boolean, the sources and the pages.

Whychecked and fallback tell a case writer whether the answer passed the citation check or fell back. That separates candidate positive cases from questions the documents may not answer.

  }  // Each line ends with a newline, as JSONL expects.  return new Response(lines.map((line) => `${line}\n`).join(''), { headers: { 'Content-Type': 'application/x-ndjson; charset=utf-8' } })}

Newline-terminated, served as NDJSON Site request

WhatEnds every line with a newline and serves the body as application/x-ndjson in UTF-8.

WhyNewline-delimited JSON can be appended to, streamed and read line by line, and eval case files use the same format (evals/cases.jsonl).