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.
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
/** Whether the site says this visitor may be recorded, so their questions are kept and their pages archived. */constkeeps = (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.
/** * 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.
constvia = (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.
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.
/** 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. */asyncfunctionadminDemos(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.
/** One demo for /admin: its files with each page's text (live, else archived) and every question. */asyncfunctionadminDemo(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) returnjson(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.
// Live text: each file's chunks regrouped by page, so a page reads as its chunks joined in order.const live = newMap<string, Map<number, string[]>>()for (const c of chunks.resultsas { file: string; page: number; text: string }[]) {const pages = live.get(c.file) ?? newMap<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.
// Every file name, whether it is still uploaded or only archived.const names = [...newSet([...(files.resultsas { name: string }[]).map((f) => f.name), ...kept.keys()])]// Each still-uploaded file's row, by name, for its page count.const listed = newMap((files.resultsas { 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.returnjson(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.
// The apps connected to this demo through its MCP server (demo/src/oauth.ts); none when it has no store.apps: awaitappsOf(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.
/** * 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.
asyncfunctiongolden(url: URL, env: Env): Promise<Response> {// The date range and the demo are optional filters; the defaults take every kept question.constfrom = 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.constlines: 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 = newSet<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])constpages: { 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
// 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.returnnewResponse(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).