Joel Stevick

The ask · ASK 6–7 · stage 6 of 7

Answer and check

After rerank and widening, Claude Sonnet writes the answer as plain text and ends each sentence with the ids of its chunks in square brackets. The reply streams in a few characters at a time. After every piece, units() cuts the text so far into the sentences and list lines that are complete, and checkUnits() checks each one before it is released. A unit passes when every id it cites is a passage the model was given and every figure it states is in one of the passages it cites or in the question. The released units go on to ASK 8 as the answer with its sources.

Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
demo/src/app.ts128 / 128 lines on this page explainedlines 49-51,535-537,715-836 of 1124; the rest are on other stage pages
demo/src/models.ts56 / 56 lines on this page explainedlines 300-355 of 355; the rest are on other stage pages
demo/src/check.ts422 / 422 lines on this page explainedevery line of the file
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: its TROUBLE and STOPPED constants and answering()'s ASK 6–7 segment, which reads the stream and releases checked units.

TROUBLE

constant · lines 49–51View on GitHub

The message the visitor reads when the answer model fails before anything was shown.

/** Said when the answer model fails; the question is given back. */export const TROUBLE = 'The demo is having trouble right now. Please try that question again in a minute.'

The model-failure message Module load

WhatThe error event's text when the model call throws before any unit was released.

WhyIt asks the visitor to retry instead of saying the documents lack the answer, because nothing was checked. The failure is the service's, so the question is given back (line 805).

TROUBLE = 'The demo is having trouble right now. Please try that question again in a minute.'

STOPPED

constant · lines 535–537View on GitHub

The Worker's wording of the stop line under an answer that ended partway.

/** The line shown under an answer that stopped partway. */export const STOPPED = "The answer stopped here: its next sentence didn't check out against your documents."

The stop line Module load

WhatThe sentence drawn under an answer whose next unit failed its check.

WhyNothing in the Worker sends it, because the stopped event carries only a reason. demo.html keeps its own copy of this text (line 389) and a second line for reason trouble (TROUBLE_STOP). No file in the repository imports this export; it records the wording the page should match.

STOPPED = "The answer stopped here: its next sentence didn't check out against your documents."

answering(): ASK 6–7

segment · lines 715–836View on GitHub

Streams the answer, releases each checked unit as a unit event, and continues to ASK 8.

Calls answer() checkUnits() uncited units() answering(): the generator's contract, timer and record() Worker router

  // ASK 6-7 · answer (Claude writes it from the given passages only), each unit checked in code  // as it completes and released only when it passes; the first that fails ends the answer.  //  // The model's reply arrives as text, a few characters at a time (`answer` in models.ts yields  // each `text_delta` of the Messages API stream). `text` accumulates it. After every piece,  // `units` (check.ts) cuts the text so far into the sentences and list lines that are complete,  // and each one not yet dealt with is checked and either released, held, or ends the answer.

What ASK 6–7 does Never runs

WhatThe comment describes the design. The reply arrives as text_delta pieces, text accumulates them, and after every piece units() cuts out the complete sentences and list lines. Each new unit is released, held, or ends the answer.

WhyChecking each unit instead of the whole reply lets the first sentence reach the page while the model is still writing the rest, and no unchecked word is ever shown.

Explained in Ep 1: Generation and the code check: every sentence cites the context From RAG deep dive, Ep 1: RAG Debugging: Retrieval, Reranking or Generation?
  yield { type: 'stage', stage: 'writing' }

The writing stage event Query time

WhatYields a stage event with stage 'writing', which the page shows as "Writing…".

WhyThe first unit can follow only after the model has thought, written its first sentence and started its second (or ended the reply). Until then, this line tells the visitor the ask has moved past rerank.

The question form with "Writing…" on the status line under it.
The status line after the writing stage event arrives. It reads "Writing…" until the first checked unit of the answer arrives and the page clears it. 2026-11-29, the live demo at joelstevick.com/demo in Chrome. The live page is newer than the pinned commit, so its file selector, trash icons and indexing note are not in the code shown here.
  // Every unit released so far, with the chunks it cited: the sources and the recorded answer are built from these.  const shown: { kind: UnitKind; text: string; cited: Chunk[] }[] = []

shown: released units Query time

WhatEach released unit's kind, its display text and the chunks its group cited.

WhyASK 8 builds the sources and the recorded answer from this array alone, so a passage the model was given but no released unit cited never appears under the answer. release() also uses its length to find the new units.

  // How many prose units (sentences, lead-ins) and list items have been released: the caps (four, twelve) are checked against these.  const counts: Counts = { prose: 0, items: 0 }

counts: the caps' running totals Query time

WhatHow many prose units (sentences and lead-ins) and list items have been released.

WhycheckUnits() is a pure function of one group, so release() passes in the totals from before the group. With them, checkUnits() can refuse the fifth prose unit or the thirteenth item.

  // Milliseconds from the start of answering() to the first unit released: the number this design is for.  let firstMs: number | null = null

firstMs: time to the first unit Query time

WhatMilliseconds from the start of answering() to the first released unit. It stays null until then, and for good if nothing is released.

WhyTime to the first checked sentence is the latency the visitor feels. It is recorded per question (questions.first_ms), and the eval harness reports its median next to the median time for the whole answer.

evals/runs/2026-10-30T13-49-56-stream-final: median first sentence 4,614 ms, whole answer 5,426 ms

  // The model's reply so far, markers and all.  let text = ''

text: the reply so far Query time

WhatThe model's raw output so far, citation markers included.

Whyunits() always runs on the whole text so far, because a single piece can end mid-word, mid-marker or mid-sentence.

  // Why the answer ended early, once it has: a check's reason, or `trouble` when the model failed partway.  let failed: 'empty' | 'uncited' | 'ungrounded' | 'overlong' | 'trouble' | null = null

failed: why the answer ended early Query time

Whatnull while every unit has passed. Otherwise it holds one of checkUnits()'s reasons, 'uncited' for a trailing unit with no ids, or 'trouble' when the model failed after something was shown.

WhyThis one variable decides how the answer ends. With nothing shown, it becomes the fallback event's refused reason. With something shown, it becomes the stopped event's reason, and ASK 8 records the answer with fallback 'stopped'.

  // Units the model wrote without ids ("No, it is a small loss."), waiting to be released with  // the next unit that has them and checked against that unit's passages (Joel, 2026-10-30).  const held: RawUnit[] = []

held: units waiting for a citation Query time

WhatUnits the model wrote without any chunk id, kept until the next unit that has ids.

WhyA short opening such as "No." or a sentence that continues the previous one often carries no citation, even though the prompt asks for one. Refusing it would end a correct answer, and showing it would show an unchecked sentence. So it is checked together with the next cited unit, against that unit's passages.

  // Checks and releases every complete unit in `text` that is not yet shown or held. A sync  // generator rather than a function, because each released unit must be yielded to the caller  // as a `unit` event in the middle of the work: `yield*` below hands each one up, and the  // generator's return value (true to carry on, false once a unit has failed) comes back as the  // value of the `yield*` expression. `units` returns the same leading units for every longer  // text, so slicing past what is shown or held gives exactly the new ones.

Why release() is a generator Never runs

Whatrelease() checks and releases every new complete unit. It is a synchronous generator: it yields each released unit as a unit event, and its return value (true to continue, false after a failure) becomes the value of the yield* expression in the caller.

WhyA plain function would have to collect the events and return them together, so each unit would wait until the whole piece was processed. yield* passes each event out of the async generator answering() as soon as it is made. The slicing relies on units() being stable: skipping as many units as are shown or held leaves exactly the new ones.

  function* release(final: boolean): Generator<AskEvent, boolean> {    for (const unit of units(text, final).slice(shown.length + held.length)) {

Only the new units Query time

WhatRecomputes units(text, final) and skips the first shown.length + held.length units, which are already released or waiting.

WhyRecomputing from the whole text keeps units() stateless. The slice is correct only because units() never revises a unit it has returned once more text arrives. A test in demo.test.ts ('units of a streamed reply') checks that property at every prefix of a sample reply.

      // No ids of its own: it waits for a cited unit to vouch for it.      if (uncited(unit)) {        held.push(unit)        continue      }

No ids: hold it Query time

WhatA unit with no citation marker (uncited() is true when idsIn() finds none) is appended to held, and the loop moves on.

WhyNothing is checked or shown yet. The unit is shown only if a later cited unit passes with it. A unit whose only brackets hold a word that is not an id, such as "[sic]", counts as uncited too.

      // The held units and this one are checked together as one group, against this one's ids.      const checked = checkUnits([...held.splice(0), unit], given, question, counts)

Check the group Query time

Whatheld.splice(0) empties held and returns its units. They and this unit go to checkUnits() as one group, with the given passages, the question and the counts so far.

WhyHeld units have no ids, so the group's citations are this unit's alone. Every figure in a held sentence must therefore be stated by a passage the next sentence cites, and that condition is what makes holding safe.

      if (!checked.ok) {        failed = checked.reason        return false      }

First failure ends the answer Query time

WhatA failed group sets failed to its reason and returns false, and none of the group's units is released.

WhyA later sentence may depend on the one that failed ("That fee is waived…"), so showing sentences after a gap could misstate the documents. The units already shown stay, since each of them passed its check.

      // Each unit of the group is released in order; the first ever released sets `first_ms`.      for (const one of checked.units) {        shown.push({ ...one, cited: checked.cited })        if (one.kind === 'item') counts.items++        else counts.prose++        firstMs ??= Date.now() - started        yield { type: 'unit', kind: one.kind, text: one.text, sources: checked.cited.map((chunk) => chunk.id) }      }    }

Release each unit of the group Query time

WhatEach unit of a passing group is pushed to shown with the group's cited chunks and counted as an item or as prose. The first one sets firstMs (??= assigns only while it is null). Each is yielded as a unit event with its kind, its text without markers and the cited chunk ids.

WhyIn the server-sent-events rendering, ask() writes each yielded event to the response at once, so the page draws this unit while the model is still writing. A held unit is released with the same sources as the cited unit it was checked with.

    // The reply ended on a sentence with no ids: nothing came to vouch for it, so it is never shown.    if (final && held.length > 0) {      failed = 'uncited'      return false    }    return true  }

A trailing uncited unit Query time

WhatOn the final call, if units are still held, failed becomes 'uncited' and release() returns false. Otherwise it returns true.

WhyAt the end of the reply no later unit can be checked with a held one, so it is never shown. This is the one rule app.ts adds to the checks in check.ts. A reply made only of uncited text, such as "The passages do not mention it.", ends here and becomes the fallback with reason uncited.

  // Read the model's reply as it streams, releasing units as they complete.  try {    // A labelled block, so a failed check can leave the loop *and* skip the final release: once a    // unit has failed, nothing later in the reply is read or shown. Leaving the `for await` early    // returns the model's stream, which cancels the HTTP body (`serverEvents`, models.ts), so a    // refused answer is not read, or paid for, to its end.

Why a labelled block Query time

WhatOpens the try that catches a model failure. The comment explains the label: break reading leaves both the for await loop and the final release.

WhyLeaving a for await loop early calls return() on the model's async iterator. The finally block in serverEvents then cancels the reader, which cancels the HTTP response body, so the rest of a refused answer is not read. The source comment adds that it is not paid for either.

    reading: {      for await (const piece of answer(models.stream, question, given)) {        text += piece        // Any units this piece completed are checked and released now, while the model writes on.        if (!(yield* release(false))) break reading      }

Read the stream Query time

Whatanswer() returns the model stream, and the request to the Messages API starts at the loop's first iteration. Each piece is appended to text and release(false) runs; if it returns false, break reading leaves the labelled block, skipping the final release.

WhyChecking after every piece releases a sentence as soon as the next one has begun, instead of at the end of the reply. Running units() on the whole text each time is cheap because the reply is capped at 2,000 tokens (maxTokens, models.ts:352).

      // The stream has ended: what is left is the last unit, full stop or not.      yield* release(true)    }

The end of the stream Query time

WhatWhen the model's stream ends normally, release(true) runs once more with final set, so the last unit counts as complete with or without a full stop.

WhyBefore the end, a sentence is complete only when the next one has begun, so only this final call releases the last sentence and the last list line. Its return value is ignored because failed is already set if a unit failed.

  } catch (error) {    // The model failed (a timeout, an error event, a dropped connection). What that means    // depends on whether anything has been shown yet.

The model failed Query time

WhatCatches anything thrown inside the try: the 30-second timeout aborting the body, an error event in the API's stream, a dropped connection, a missing API key, or an error reply.

WhyAn exception thrown by release() or by checkUnits() would also land here and be treated as a model failure. What happens next depends on whether anything was shown.

    if (shown.length === 0) {      console.error('demo ask: the answer model failed; the question is given back', error)      // The reservation at ASK 2 is undone: the failure costs the visitor no question.      await env.DB.prepare('UPDATE demos SET asks_used = asks_used - 1 WHERE id = ? AND asks_used > 0').bind(demo.id).run()

Nothing shown: give the question back Query time

WhatLogs the error, then one UPDATE decrements asks_used for this demo account, guarded by asks_used > 0.

WhyASK 2 reserved the question before anything was known, and a failure of the service should not cost the visitor one of the ten questions. The guard keeps the count from going negative. used_at, which the reservation set, is not reset.

SQL: UPDATE demos SET asks_used = asks_used - 1 WHERE id = ? AND asks_used > 0

      const ok = await record({ answer: null, fallback: 'trouble' })      yield { type: 'error', error: TROUBLE, left: left + 1 }      yield { type: 'recorded', ok }      return    }

Record trouble, end with error Query time

WhatRecords the question with no answer and fallback 'trouble', yields an error event with TROUBLE and left + 1, then the recorded sentinel, and returns.

Whyleft + 1 counts the question that was given back. The JSON rendering answers this event with status 503. The stream sends it as the error event, and the page shows TROUBLE and leaves the question in its box to send again.

    // An answer was already shown: the failure stops it there, and the question is not given back.    console.error('demo ask: the answer model failed partway; the answer stops', error)    failed = 'trouble'  }

Something shown: stop there Query time

WhatIf at least one unit was released, the error is logged, failed becomes 'trouble', and execution continues to the answer's ending.

WhyThe visitor already has checked sentences, so the answer is kept and recorded. It ends with a stopped event whose reason lets the page say the demo app had trouble, instead of saying a sentence failed its check. The question is not given back.

  // A reply that ends with no unit says nothing: the model's own "no passage answers it".  if (shown.length === 0 && failed === null) failed = 'empty'

No unit at all: empty Query time

WhatIf the stream ended without a failure and nothing was released, failed becomes 'empty'.

WhyANSWER_RULES tells the model to write nothing when no passage answers, so an empty or whitespace-only reply is the model's own "not found".

  if (shown.length === 0) {    // Nothing was shown: the fallback, exactly as before streaming. The model's words (its    // markers included, as it wrote them) are recorded with the reason, for the evals and /admin,    // and never reach the visitor.    const words = text.trim()    const ok = await record({ answer: words === '' ? null : words, fallback: 'refused' })    yield { type: 'fallback', answer: missing, found: false, refused: failed ?? 'empty', left }    yield { type: 'recorded', ok }    return  }

Nothing shown: the fallback Query time

WhatRecords the model's raw words (markers included, null when empty) with fallback 'refused', then yields a fallback event with the not-found line, found false, the reason and the questions left, then the recorded sentinel.

Whymissing is NOT_FOUND when every chunk was read and NOT_IN_PASSAGES otherwise, so the line never claims the documents lack something when only part of them was read. The refused words are kept for the evals and the admin view and are never sent to the visitor. The question still counts, because the model ran.

refused: empty | uncited | ungrounded | overlongrecorded fallback: 'refused'

  // Something was shown and then a later unit failed: the page is told to draw its stop line  // under what it has; the answer is recorded as checked and `stopped`, and the question counts.  if (failed !== null) yield { type: 'stopped', reason: failed }

Something shown, then a failure Query time

WhatWhen units were released and failed is set, a stopped event with the reason is yielded, and the ask continues to ASK 8 with the units shown.

WhyThe page keeps what it drew and adds the stop line under it. ASK 8 records the shown answer as checked with fallback 'stopped', so partial answers can be counted apart from complete ones.

demo/src/models.ts The model clients: the answer model's system prompt (ANSWER_RULES) and answer(), which builds the request and returns the unstarted stream.

ANSWER_RULES

constant · lines 300–331View on GitHub

The answer model's system prompt, written so that every answer it asks for can pass the per-unit check.

/** * The answer model's instructions. The shape and length rules here and the check in check.ts * (`checkUnits`) must agree: an answer these rules ask for must pass the check, or the visitor * is shown "couldn't find that" for an answer that was right. So: * *   - an ordinary answer is prose, two to four sentences (check.ts MAX_SENTENCES, 4), each ending *     with the ids it rests on (one without ids is checked with the next cited one, against its ids); *   - an answer that names several things of one kind (every job, every fee, every chapter), or *     one the question asks to have a sentence or a line each, is a list: one "- " line per thing, *     at most 12 (check.ts MAX_ITEMS), each a phrase or one sentence (the check allows two, *     MAX_ITEM_SENTENCES), after at most a one-sentence lead-in. The page draws the lines as *     bullets. *

Prompt and check must agree Never runs

WhatThe comment states the contract: an answer these rules ask for must pass the check. Prose is two to four sentences, each ending with its ids. A list is one "- " line per thing, at most 12, after at most a one-sentence lead-in.

WhyA correct answer in a shape the check refuses reaches the visitor as "couldn't find that", so the comment restates the limits from check.ts. It also notes that a sentence written without ids is checked with the next cited one, against that one's ids.

MAX_SENTENCES = 4MAX_ITEMS = 12MAX_ITEM_SENTENCES = 2

The same idea, shown in the course's code: Prompts are code: reviewed, tested and paid for on every call From From engineer to AI engineer, Ep 3: Prompts are code
 * A list asked for implicitly counts: "what jobs have I held" is a list as much as "list my jobs". * Before lists, such an answer was one sentence with semicolons between the items, which read as * a run-on paragraph. * * When there are more than 12, the model lists the first 12 and its lead-in says the list is * not complete, so the visitor is never shown a shortened list as if it were the whole. The * lead-in says so without a count ("These are the first jobs listed; the list is not complete."): * the figure check reads "12" or "twelve" as a figure, and refuses an answer stating one that no * cited passage states, so "the first 12" would turn a right answer into "couldn't find that". */

Lists, and more than 12 Never runs

WhatA list asked for implicitly ("what jobs have I held") is still a list. With more than 12 things, the model lists the first 12, and its lead-in says in words, without a count, that the list is incomplete.

WhyThe figure check reads "12" and "twelve" as figures. A lead-in saying "the first 12" would state a number no cited passage states, and a correct answer would be refused.

const ANSWER_RULES = `You answer a question from passages of the asker's own documents, and from nothing else.Write in plain words, with figures in digits exactly as the passages state them.

Only the passages; figures as written Module load

WhatThe model answers from the passages alone and writes figures in digits exactly as the passages state them.

WhyThe figure check compares digit strings. A figure copied as written ("4,200", not "4.2 thousand") is found in its passage. A spelled-out figure produces extra figures ("twenty-five" yields 5, 20 and 25), and each of them must be grounded.

End every sentence with the ids of the passages it rests on, in square brackets, for example "Refunds are paid within 30 days [a1b2c3-4]." or "[a1b2c3-4, d5e6f7-8]" for two. Every sentence, without exception: a short opening sentence, a sentence that continues the one before it, and the sentence introducing a list end with their ids too, as in "No [a1b2c3-4]. Writing to the cache costs more than reading it [a1b2c3-4]." or "He has held these jobs [a1b2c3-4, d5e6f7-8]:". Before it is shown, each sentence is checked against the passages its ids name; a sentence with no ids of its own is checked against the passages of the next sentence that has them, and is not shown if none follows.Do not write file names or page numbers: they are shown under your answer.

Every sentence ends with its ids Module load

WhatEach sentence ends with the ids of its passages in square brackets, one id or several separated by commas. That includes short openings, continuations and a list's lead-in. File names and page numbers are left out.

WhyMARKER parses these markers, and checkUnits() matches their ids against the given chunks. The prompt tells the model that each sentence is checked against the passages its ids name, and that a sentence without ids is checked against the passages of the next sentence that has them and is not shown if none follows. The check itself requires each id to be a passage the model was given and each figure to be in a cited passage or in the question; it does not check meaning. A held sentence is also dropped when its group fails the check (release() in app.ts). The page shows the file and page from the stored chunks, so the model has no reason to write them.

When the answer names several things of one kind (every job, every fee, every chapter), or the question asks for a sentence or a line for each one, answer with a list: at most one short sentence introducing it, ending with its ids, or nothing, then one line per thing starting with "- ", each a short phrase or one sentence ending with its ids, with no blank line before the list. Name every one the passages give. If there are more than 12, list the first 12 and say in the introduction that the list is not complete, in words and without a count.

When to answer with a list Module load

WhatWhen the answer names several things of one kind, or the question asks for a sentence or line for each, the model writes an optional one-sentence lead-in and then one "- " line per thing, each ending with its ids, with no blank line before the list. It names every one the passages give, at most 12.

Whyunits() recognises an item only as a line that starts with "- ", so the prompt fixes that exact syntax. Lists were added because a résumé's seven jobs came back as one run-on sentence joined by semicolons (check.ts, MAX_ITEMS).

Otherwise answer in two to four short sentences.Write nothing else: no heading, no closing remark.If no passage answers the question, write nothing at all.Never write that the passages or the documents do not say something: you see only some of them, so write nothing instead.`

Length, nothing extra, or nothing at all Module load

WhatOtherwise the answer is two to four short sentences, with no heading or closing remark. If no passage answers, the model writes nothing, and it never writes that the documents do not say something.

WhyAn empty reply becomes the fallback with reason empty, and the Worker words the page's not-found line from how much of the documents was read. A model that writes "the documents don't say" after seeing a few passages misstates documents it has not seen (evals/JOURNAL.md, "The failure": given 5 chunks of a résumé, it said the passages did not list his job history).

answer()

function · lines 332–355View on GitHub

Builds the answer prompt from the given passages and returns the model's text stream without starting it.

Called by answering(): ASK 6–7

/** * Sonnet's answer as it is written, unchecked: text with inline citations, a piece at a time. * Nothing is read here: the stream is returned for app.ts to iterate, and the call to the model * only starts when it does. Throws (out of the caller's `for await`) when the model fails. */

Returns an unstarted stream Never runs

Whatanswer() reads nothing. It returns an AsyncIterable of text pieces, and the request to the model starts only when app.ts begins iterating it.

WhyclaudeStreamFor returns an async generator function (models.stream). Calling it, as answer() does, creates the generator without running any of its body, so the fetch happens on the first next(). Errors are thrown out of the caller's for await loop, where ASK 6–7's catch gives the question back if nothing was shown, and otherwise stops the answer.

export function answer(stream: ClaudeStream, question: string, given: Chunk[]): AsyncIterable<string> {  // A widened passage that runs past its first page is labelled with the range of pages.  const pages = (chunk: Chunk) => (chunk.lastPage !== undefined && chunk.lastPage > chunk.page ? `pages ${chunk.page}–${chunk.lastPage}` : `page ${chunk.page}`)

Signature and page labels Query time

WhatTakes the stream client, the question and the given chunks. pages() labels a chunk "page N", or "pages N–M" for a widened passage whose lastPage is after its first page.

WhyThe label tells the model where a passage is in its file. ANSWER_RULES tells it not to repeat that in the answer.

  // Each passage goes in under its id and its place in the file; the answer's citations must copy those ids.  const listed = given.map((chunk) => `[${chunk.id}] (${chunk.file}, ${pages(chunk)})\n${chunk.text}`).join('\n\n')

Passages under their ids Query time

WhatEach given chunk becomes a line "[id] (file, page N)" followed by its text, with a blank line between passages.

WhyThe bracketed id is the exact string the model must copy into its markers, and checkUnits() matches ids exactly. The reranker sees positions ([0], [1]…), but the answer model sees chunk ids, because its citations must survive to ASK 8.

id: <account id>-<upload>-<n>

  // Hand back the stream; nothing is sent until the caller starts reading it.  return stream({    model: ANSWER_MODEL,    system: ANSWER_RULES,    user: `Question: ${question}\n\nPassages:\n\n${listed}`,

The request Query time

WhatCalls the stream client with claude-sonnet-5-5, ANSWER_RULES as the system prompt, and one user message holding the question and then the passages.

WhyThere is no output schema. The answer is plain text with inline markers so that it can be checked and shown sentence by sentence; a JSON reply could not be released until it was complete.

ANSWER_MODEL = 'claude-sonnet-5-5'

The answer request, as sent to Claude Sonnet The request holds the answer rules, then the passages. Each passage goes in under the id of a chunk the reranker chose, widened with the chunks on either side, and is labelled with its file and page range. The answer must cite those ids. The response is a stream of server-sent events; joined, its text deltas show each sentence ending in the ids of the passages it rests on. The passages are abridged. Captured 2026-11-29 from the eval harness's Worker under wrangler dev (evals/worker.ts), case book-01 of evals/cases.jsonl, with book.pdf, claude-sonnet-5-5, at b244e6a.

Request body

{
  "model": "claude-sonnet-5-5",
  "max_tokens": 2000,
  "system": "You answer a question from passages of the asker's own documents, and from nothing else.\n
Write in plain words, with figures in digits exactly as the passages state them.\n
End every sentence with the ids of the passages it rests on, in square brackets, for example \"Refunds are paid within 30 days [a1b2c3-4].\" or \"[a1b2c3-4, d5e6f7-8]\" for two. Every sentence, without exception: a short opening sentence, a sentence that continues the one before it, and the sentence introducing a list end with their ids too, as in \"No [a1b2c3-4]. Writing to the cache costs more than reading it [a1b2c3-4].\" or \"He has held these jobs [a1b2c3-4, d5e6f7-8]:\". Before it is shown, each sentence is checked against the passages its ids name; a sentence with no ids of its own is checked against the passages of the next sentence that has them, and is not shown if none follows.\n
Do not write file names or page numbers: they are shown under your answer.\n
When the answer names several things of one kind (every job, every fee, every chapter), or the question asks for a sentence or a line for each one, answer with a list: at most one short sentence introducing it, ending with its ids, or nothing, then one line per thing starting with \"- \", each a short phrase or one sentence ending with its ids, with no blank line before the list. Name every one the passages give. If there are more than 12, list the first 12 and say in the introduction that the list is not complete, in words and without a count.\n
Otherwise answer in two to four short sentences.\n
Write nothing else: no heading, no closing remark.\n
If no passage answers the question, write nothing at all.\n
Never write that the passages or the documents do not say something: you see only some of them, so write nothing instead.",
  "messages": [
    {
      "role": "user",
      "content": "Question: What version of Node do I need before starting the book's examples?\n
\n
Passages:\n
\n
[3mndgu1a2d9kcgmb-lhub85vy-19] (book.pdf, pages 12–16)\n
Typing it yourself\n
Chapters 1 through 11 have you write every line. Chapter 12 hands the\n
finished pipeline over to a packaged version, and Chapter 13 …[4719 characters]…her rate reaches zero, and the wrong answers that remain\n
read exactly as well as the right ones.\n
Chapter 1 is about thirty lines of TypeScript, starting on the next page.\n
\n
[3mndgu1a2d9kcgmb-lhub85vy-493] (book.pdf, pages 262–264)\n
256 Appendix B: The Finished Workflow\n
}\n
try {\n
main();\n
} catch (error) {\n
console.error(error instanceof Error ? error.message : String(error));\n
process…[1745 characters]…agent, in its own context. Give it\n
the slug and nothing else: not what was built, not why, not what you expect\n
it to find. It has not seen this conversation and must not.\n
\n
[3mndgu1a2d9kcgmb-lhub85vy-132] (book.pdf, pages 74–75)\n
68 What It Knows and Forgets\n
Example: Ask the agent “what does slugify do with accents?”\n
in a fresh run, and then ask the identical question at the en…[2221 characters]…r a fact that has\n
a source of truth. Versions, identifiers, prices, schemas, flags: look\n
them up. The model is excellent at applying facts and unreliable at\n
storing them.\n
\n
[3mndgu1a2d9kcgmb-lhub85vy-9] (book.pdf, pages 8–9)\n
2 Introduction\n
The picture above is an agent : a program that calls a model in a loop,\n
runs whatever tool the model asks for, and stops when the model…[2234 characters]…it asked for, append the\n
result, call again, until it stops asking. The loop needs a way to stop,\n
because a model that keeps requesting tools will keep being handed them.\n
\n
[3mndgu1a2d9kcgmb-lhub85vy-452] (book.pdf, pages 241–242)\n
Appendix B: The Finished Workflow 235\n
\"Another reviewer looked at the same code and reached the opposite\",\n
\"conclusion. They did not explain why.\",\n
\"\"…[2178 characters]…slug, ...rest] = process.argv.slice(2);\n
const request = rest.join(\" \");\n
if (slug === undefined || request.length === 0) {\n
console.error('usage: tsx agentic/plan.ts <slug>\n
\n
[3mndgu1a2d9kcgmb-lhub85vy-456] (book.pdf, pages 243–244)\n
Appendix B: The Finished Workflow 237\n
if (fs.existsSync(file)) {\n
console.error(`${file} already exists. Choose another slug or delete it.`);\n
process.e…[1426 characters]…uilt anyway? A criterion met only for the literal example in the \" +\n
\"plan is not met.\",\n
},\n
{\n
name: \"security\",\n
question:\n
\"What does this do with input it did not expect?\n
\n
[3mndgu1a2d9kcgmb-lhub85vy-50] (book.pdf, pages 28–29)\n
22 Talking to a Model\n
temperature: 0 does not make the model deterministic. It makes\n
only the selection rule deterministic, and identical requests at …[1958 characters]…or.status}: ${error.message}`);\n
} else {\n
throw error;\n
}\n
}\n
• AuthenticationError (401): the key is wrong, revoked, or has a\n
stray newline in it from however you copied it.\n
\n
[3mndgu1a2d9kcgmb-lhub85vy-61] (book.pdf, page 34)\n
Listing: agentic/tool.ts\n
import fs from \"node:fs\";\n
import path from \"node:path\";\n
import Anthropic from \"@anthropic-ai/sdk\";\n
import { MODEL, requireApiKey } from \"./setup.js\";\n
requireApiKey();\n
const client = new Anthropic();"
    }
  ],
  "stream": true
}

Response: the stream, its text deltas joined

{
  "text": "You need Node.js 20 or newer, along with npm [3mndgu1a2d9kcgmb-lhub85vy-19]. To check, run `node --version`; if it prints something starting with v20. or higher, you have what the examples need [3mndgu1a2d9kcgmb-lhub85vy-19]. The book's own build job also uses Node 20 [3mndgu1a2d9kcgmb-lhub85vy-493].",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 7864,
    "output_tokens": 145
  }
}
    // Sonnet 5.5 thinks before answering, inside this limit: 600 left answers within a few    // tokens of being cut off (eval questions book-14, book-15).    maxTokens: 2000,    timeoutMs: 30_000,  })}

Token and time limits Query time

Whatmax_tokens is 2,000 and covers both the model's thinking and its text. A 30-second timeout covers the whole streamed response.

WhyThe limit was raised from 600 after answers came within a few tokens of being cut off. The timeout aborts a model that stalls mid-answer, and the abort throws out of the for await loop in app.ts.

maxTokens = 2000timeoutMs = 30_000evals/JOURNAL.md, baseline: 587 and 588 of 600 output tokens on two answersevals/JOURNAL.md, "What the verifier caught": round 1 answers reached 616 and 607 tokens

demo/src/check.ts The whole file: figure extraction, sentence counting, the unit cutter, the citation markers and both checks. Its only import is the Chunk type.

Module scope

module scope · lines 1–14View on GitHub

The licence, the module's purpose, and its one import.

// Copyright (c) 2026 Joel Stevick// SPDX-License-Identifier: MIT// Licensed under the MIT License: https://opensource.org/licenses/MIT

Licence Never runs

WhatThe copyright notice and the MIT licence, with an SPDX identifier.

WhyThe repository is public under MIT, and the SPDX line lets tools read the licence.

/** * Whether an answer may be shown, decided here (app.ts release() adds one rule: a trailing uncited sentence is never shown). * * Ported from Howard's Lantern's worker/src/learner-ask.ts * (`numbersIn`, `figuresIn`, `compounds`, `checkLawAnswer`), English only: every * id the answer cites must be a chunk it was given, and every figure it states * must be in a chunk it cites (or in the question). */

The two rules Never runs

WhatEvery id the answer cites must be a chunk it was given, and every figure it states must be in a chunk it cites or in the question. The code is an English-only port of Howard's Lantern's learner-ask.ts.

WhyThe check is deterministic code instead of a second model call, so it cannot be talked out of a refusal and costs no tokens. It verifies citations and figures; it does not check what a sentence means. The comment names the one rule decided elsewhere: release() in app.ts never shows a trailing uncited sentence.

import type { Chunk } from './retrieval'

One import Type only

WhatOnly the Chunk type, which is erased at compile time.

WhyThe file that decides what may be shown depends on no service and on no other module's values, so it can be tested with plain strings.

MAX_SENTENCES

constant · lines 15–19View on GitHub

The most prose units an answer may release.

/** * The longest ordinary answer, in sentences. The demo page promises "two to four sentences", * and a reply longer than this is refused rather than trimmed (see `checkAnswer`). */export const MAX_SENTENCES = 4

Four sentences Module load

WhatAn answer may have at most four prose sentences; the demo page promises two to four.

WhycheckAnswer() refuses a longer reply whole. In the streamed check, the fifth prose unit fails as overlong after four were shown, so the visitor keeps four sentences and sees the stop line. A list's lead-in counts as prose.

MAX_SENTENCES = 4

MAX_ITEMS

constant · lines 20–38View on GitHub

The most items a list answer may have.

/** * The most items a list answer may have. * * Why lists exist: a visitor asked "what jobs have i held - 1 sentence each" of a two-page * résumé. The answer was right, but it came back as one long run-on sentence with the seven jobs * separated by semicolons, because a prose answer is held to MAX_SENTENCES and the page showed * it as a single paragraph. An answer that names several things of one kind (every job, every * fee, every chapter) now comes back as a list instead: a short lead-in in `answer` and one * entry per thing in `items`, which the page draws as bullets. * * Why 12: it matches ANSWER_CHUNKS (12, models.ts), the number of passages the reranker chooses, * and it is room for a two-page résumé's jobs or a document's chapters with space to spare. It * is a ceiling, not a target: a list longer than this is refused, not cut, so a runaway reply is * never shown and a list is never silently shortened by the check. * (The number is repeated here rather than imported from models.ts so that this file, the one * that decides what may be shown, depends on nothing but the chunk type.) */export const MAX_ITEMS = 12

Twelve items, and why lists exist Module load

WhatA list answer may have at most 12 items. The comment records why lists were added (a résumé's seven jobs came back as one sentence joined by semicolons) and why the number is 12.

Why12 matches ANSWER_CHUNKS, the number of passages the reranker chooses, so a list with one thing per passage fits. The number is repeated instead of imported from models.ts so that check.ts depends on nothing but the Chunk type. A longer list fails at the thirteenth item and is never cut silently.

MAX_ITEMS = 12ANSWER_CHUNKS = 12 (models.ts)

MAX_ITEM_SENTENCES

constant · lines 39–47View on GitHub

The most sentences one list item, or a list's lead-in, may have.

/** * The most sentences a list's lead-in, or any one of its items, may have. * * An item is meant to be one sentence or a phrase ("Team Lead, Zonar Systems, 2021 to 2026"). * Two leaves room for a short second sentence the model adds for clarity, without letting one * item grow into a paragraph that hides the list's shape. The lead-in gets the same allowance. */export const MAX_ITEM_SENTENCES = 2

Two sentences an item Module load

WhatAn item may have at most two sentences, as counted by sentences().

WhyThat leaves room for a clarifying second sentence without letting a bullet grow into a paragraph. checkAnswer() also applies the limit to the lead-in. checkUnits() applies it to items only, since a streamed lead-in is a single prose unit.

MAX_ITEM_SENTENCES = 2

Number words

constant · lines 48–66View on GitHub

The tables figuresIn() and compounds() use to read spelled-out numbers.

/** The numbers spelled as one word up to twelve, indexed by value: NUMBER_WORDS[5] is 'five'. */const NUMBER_WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']

NUMBER_WORDS: zero to twelve Module load

WhatThe words zero to twelve, indexed by value.

WhyAn answer that says "seven jobs" states the figure 7 as surely as one that writes 7, so spelled-out numbers are checked too.

/** The larger spelled numbers, each a figure on its own: "thirty" states 30 even outside a compound. */const LARGER_WORDS: Record<string, number> = {  thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19,  twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90,  hundred: 100, thousand: 1000,}

LARGER_WORDS: thirteen to thousand Module load

Whatthirteen to nineteen, the tens from twenty to ninety, hundred and thousand, each with its value.

WhyfiguresIn() counts each as a figure on its own wherever it appears, even inside a compound: "thirty-two" yields 30 from this table as well as 32 from compounds().

/** One to nineteen: the words a compound adds as they are ("twenty-five" is 20 + 5). */const UNITS: Record<string, number> = Object.fromEntries(  [...NUMBER_WORDS.slice(1), 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']    .map((word, index) => [word, index + 1]),)

UNITS: one to nineteen Module load

WhatBuilt from NUMBER_WORDS without zero, plus thirteen to nineteen; each word maps to its position plus one.

WhyThese are the words compounds() adds at face value. Zero is left out, so it never joins a compound.

/** The tens a compound adds before its unit. */const TENS: Record<string, number> = { twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90 }

TENS: twenty to ninety Module load

Whattwenty to ninety with their values.

Whycompounds() adds a tens word to the run exactly as it adds a unit; the separate table is only for readability.

compounds()

function · lines 67–106View on GitHub

Reads each run of number words in a text as one value.

Called by figuresIn()

/** Spelled compounds as the numbers they are: "five hundred" is 500, "twenty-five" 25. */function compounds(text: string): number[] {  // The value of each run of number words, in the order they appear.  const out: number[] = []

Signature and output Query time

WhatTakes a text and returns the value of each run of consecutive number words, in order.

Why"five hundred" states 500, which neither word states alone, so the run's value is what must be grounded.

  // total: what the run reached at its last "thousand"; chunk: the part since then, still open to "hundred";  // open: whether a run of number words is under way.  let total = 0  let chunk = 0  let open = false

Running state Query time

Whattotal holds what the run had reached at its last "thousand", chunk holds the part since then, and open says whether a run is under way.

WhyTwo accumulators are the standard way to parse spelled-out numbers, because hundred multiplies only the part after the last thousand ("two thousand three hundred" is 2,000 + 300).

  // A run of number words has ended: emit what it added up to, and start fresh.  const close = () => {    if (open) out.push(total + chunk)    total = 0    chunk = 0    open = false  }

close(): end a run Query time

WhatIf a run is open, pushes total + chunk, then resets all three variables.

WhyIt runs at every non-number word and once at the end, so each run is emitted exactly once.

  // Units and tens add to the run, hundred and thousand scale it, 'and' joins it, any other word ends it.  for (const word of text.toLowerCase().match(/[a-z]+/g) ?? []) {    if (UNITS[word] !== undefined) chunk += UNITS[word]    else if (TENS[word] !== undefined) chunk += TENS[word]

Units and tens add Query time

WhatThe text is lower-cased and split into runs of letters (/[a-z]+/g), so hyphens and digits separate words. A unit or tens word is added to chunk.

Why"twenty-five" arrives as twenty and five and sums to 25. Units and tens are always added, so any two adjacent unit or tens words sum: "five six" reads as 11.

    else if (word === 'hundred' && open) chunk = (chunk === 0 ? 1 : chunk) * 100    else if (word === 'thousand' && open) (total += (chunk === 0 ? 1 : chunk) * 1000), (chunk = 0)

hundred and thousand scale Query time

WhatInside a run, hundred multiplies chunk by 100 (or sets it to 100 if chunk is 0). thousand adds chunk × 1,000 (or 1,000) to total and clears chunk.

WhyOutside a run ("a hundred"), the word falls to the else branch like any other word, and figuresIn() still records it as 100 from LARGER_WORDS. The comma expression on line 92 makes two assignments in one branch.

    else if (word === 'and' && open) continue    else {      close()      continue    }

and joins, anything else ends Query time

What"and" inside a run is skipped; any other word closes the run.

WhyThat reads "one hundred and five" as 105. It also joins two separate numbers: "between two and three days" yields 5, a figure the answer must then ground, so such a sentence is refused unless a cited passage or the question contains a 5.

    // Reached only by a number word: the run is under way.    open = true  }

Mark the run open Query time

WhatReached only after a word found in UNITS or TENS, or a hundred or thousand inside a run; sets open.

Whyhundred and thousand test open, so they scale only a run that has already started.

  // The text may end on a number word, so the last run is emitted too.  close()  return out}

The last run Query time

WhatCalls close() once more after the loop, then returns the values.

WhyWithout it, a text ending in a number word ("…came to twenty") would lose its last value.

figuresIn()

function · lines 107–135View on GitHub

Every figure a text states, as a set of digit strings.

Called by checkAnswer() checkUnits()Calls compounds()

/** * Every figure a text states, as digit strings. "4,200" is one figure; "0.5" is * read as ".5". The word "one" is a pronoun more often than a figure and is * not counted; the digit 1 is. */export function figuresIn(text: string): Set<string> {

What counts as a figure Query time

WhatReturns a Set of digit strings. The comment notes that "4,200" is one figure, "0.5" is read as ".5", and the word "one" is not counted while the digit 1 is.

WhyFigures are compared as text, so the answer and the passages both go through this function. "one" is excluded because it is far more often a pronoun ("one of the reasons") than a count.

  // Thousands separators out ("4,200" is 4200) and a leading zero off ("0.5" is .5), so one figure is one token however it was written.  const normalised = text.replace(/(\d),(?=\d{3}(?!\d))/g, '$1').replace(/\b0(\.\d)/g, '$1')

Normalise thousands separators and leading zeros Query time

WhatThe first regex removes a comma between a digit and exactly three digits not followed by another digit ("4,200" → "4200", "1,234,567" → "1234567"). The second drops a 0 at a word boundary before a decimal point and a digit ("0.5" → ".5").

WhyOne quantity becomes one token however it was punctuated. A comma before two or four digits ("3,25", "4,2000") is kept, so a list of numbers is not merged into one.

  // Every run of digits is a figure, as written.  const found = new Set<string>(normalised.match(/\d+/g) ?? [])

Every run of digits Query time

WhatEach maximal run of digits is a figure (/\d+/g).

WhyDecimal points and other punctuation split figures: "4.25" yields 4 and 25, and ".5" yields 5. Leading zeros are kept ("007" ≠ "7"), so a figure must be copied as written.

  // Spelled numbers up to twelve, as whole words, except "one" (see above).  const lower = normalised.toLowerCase()  NUMBER_WORDS.forEach((word, value) => {    if (value !== 1 && new RegExp(`\\b${word}\\b`).test(lower)) found.add(String(value))  })

zero to twelve as words Query time

WhatEach word of NUMBER_WORDS except one is tested as a whole word (\b on both sides) against the lower-cased text, and its value is added.

WhyWhole-word matching keeps "often" from stating 10 and "weight" from stating 8. A new RegExp is built for each word on every call, which costs little with 12 words.

  // The larger spelled numbers, each counted on its own.  for (const word of lower.match(/[a-z]+/g) ?? []) {    if (LARGER_WORDS[word] !== undefined) found.add(String(LARGER_WORDS[word]))  }

The larger words, each alone Query time

WhatEvery run of letters found in LARGER_WORDS adds its value.

WhyTogether with the zero-to-twelve step, a spelled-out compound also yields its parts: "twenty-five" yields 20 and 5 as well as 25. A passage that writes "twenty-five" grounds all three, and one that writes "25" grounds only 25. That is why ANSWER_RULES asks for figures as the passages write them.

  // Spelled compounds as their value ("five hundred" adds 500); one that comes to 1 is the pronoun again, so skipped.  for (const value of compounds(normalised)) if (value !== 1) found.add(String(value))  return found}

Compounds, except 1 Query time

WhatEach value from compounds() is added unless it is 1, and the set is returned.

WhyA run that comes to 1 is the word "one" alone, which is again the pronoun. compounds() also returns the value of a lone number word ("seven" → 7), which the set de-duplicates.

sentences()

function · lines 136–144View on GitHub

How many sentences a text has, with list numbers not counted as sentence ends.

Called by checkAnswer() checkUnits()Calls sentenceParts()

/** * Sentences, not list numbers: "Contents: 1. Talking to a Model; 2. The Loop" is one sentence. * A list number starts the text or follows ":", ";", "," or a line break; a figure ending a * sentence ("The fee was 5.") follows a word, and still ends it. */export function sentences(text: string): number {  return sentenceParts(text).length}

Count by sentenceParts Query time

WhatReturns the number of parts sentenceParts() finds. A list number ("1.") at the start of the text or after ":", ";", "," or a line break does not end a sentence; a figure after a word ("The fee was 5.") does.

WhyIn the baseline run (evals/JOURNAL.md), book-13's correct chapter list ("1. Talking to a Model; 2. …") was refused as fifteen sentences. The first fix exempted any number before a full stop and let five real sentences count as one ("What the verifier caught"). The rule now exempts only list positions.

Explained in Ep 1: A generation miss: the sentence counter split a numbered list From RAG deep dive, Ep 1: RAG Debugging: Retrieval, Reranking or Generation?

sentenceParts()

function · lines 145–151View on GitHub

Splits a text into sentences by the same rule sentences() counts with.

Called by sentences()

/** The sentences themselves, by the rule `sentences` counts with. */export function sentenceParts(text: string): string[] {  // Split at the whitespace after ".", "!" or "?", except after a list number of up to three digits that starts the  // text or follows ":", ";", "," or a line break; empty parts are not counted.  return text.split(/(?<=[.!?])(?<!(?:^|[:;,]\s*|\n)\d{1,3}\.)\s+(?=\S)/).filter((part) => part.trim().length > 0)}

The split Query time

WhatSplits at whitespace that (1) follows ".", "!" or "?", (2) does not follow a list number (one to three digits and a full stop at the start of the text, after ":", ";" or "," plus optional spaces, or after a line break), and (3) is followed by a non-space character. Empty parts are dropped.

Why(1) and (2) are lookbehinds and (3) is a lookahead, (?=\S). None of them consumes characters, so only the whitespace is removed and the punctuation stays with its sentence. The rule looks only at punctuation, so an abbreviation such as "e.g." followed by a space ends a sentence. The test suite's scripted model (tests/support/scripted.ts) also uses it to write marked text.

Reply

interface · lines 152–159View on GitHub

A whole reply in the JSON shape checkAnswer() reads.

/** The answer model's reply, unchecked: prose in `answer`, or a lead-in in `answer` and a list in `items`. */export interface Reply {  answer: string  /** One entry per thing the answer names, when it is a list; empty or absent for prose. */  items?: string[]  sources: string[]}

answer, items, sources Type only

WhatProse or a lead-in in answer, list entries in items, and the cited chunk ids in sources.

WhyThis is the structured-output shape the answer model returned before the answer was streamed as marked text. The streamed path does not use it. The suite's scripted model still builds replies in this shape and converts them to marked text.

Checked

type · lines 160–167View on GitHub

checkAnswer()'s verdict.

/** * The verdict. When `ok`, `answer` and `items` are what the page shows, trimmed, and `cited` * holds the given chunks the answer cites, in the order it cited them. */export type Checked =  | { ok: true; answer: string; items: string[]; cited: Chunk[] }  | { ok: false; reason: 'empty' | 'uncited' | 'ungrounded' | 'overlong' }

Pass with what to show, or a reason Type only

WhatA discriminated union: ok true with the trimmed answer, the items and the cited chunks in citation order, or ok false with one of empty, uncited, ungrounded, overlong.

WhyBecause success returns only the fields to show, a caller cannot display the unchecked reply by mistake. The four reasons are the same ones the streamed check returns and the fallback records.

checkAnswer()

function · lines 168–224View on GitHub

The same rules applied to a whole reply at once. Nothing in the repository calls it at this pin.

Calls figuresIn() sentences()

/** * Checks the model's reply against the passages it was given and the question, in this order: something was * said, every source is a given chunk, every figure is grounded, and the length is within bounds. */export function checkAnswer(reply: Reply, given: Chunk[], question: string): Checked {

Order of checks Query time

WhatChecks a whole Reply in this order: something was said, every source is a given chunk, every figure is grounded, and the length is within bounds.

WhyNo code in the repository calls it at this pin. The Worker streams and uses checkUnits(), and the tests import other functions. It is the whole-reply form of the rules checkUnits() applies per group, and its comments explain several of them.

  // The prose part of the reply, without stray spaces at either end.  const answer = reply.answer.trim()  // A list's entries, trimmed; an empty entry is dropped rather than shown as an empty bullet.  const items = (reply.items ?? []).map((item) => item.trim()).filter((item) => item.length > 0)

Trim; drop empty items Query time

WhatThe prose is trimmed; list entries are trimmed and empty ones removed.

WhyAn empty entry would render as an empty bullet and make an empty list look non-empty.

  // `reply.sources` are chunk ids, copied by the model from the `[id]` label each given passage  // carried. Each is matched to a given chunk by id, exactly; one that matches none (misspelt,  // invented, or from outside the context) fails the whole answer as `uncited`.  const ids = [...new Set(reply.sources)]

Distinct ids Query time

WhatThe cited ids, de-duplicated in first-cited order.

WhyThe model copies ids from the [id] labels in its prompt. Each must match a given chunk exactly, so a misspelt or invented id fails.

  // No answer (neither prose nor a list), or one citing nothing: the model's own "no passage  // answers it", shown as the fallback.  if ((answer.length === 0 && items.length === 0) || ids.length === 0) return { ok: false, reason: 'empty' }

Nothing said: empty Query time

WhatNo prose and no items, or no sources at all, returns reason empty.

WhyA reply that cites nothing is treated as the model's own "no passage answers" and shown as the fallback.

  // Each id matched to its given chunk, or null when no given chunk has that id.  const cited = ids.map((id) => given.find((chunk) => chunk.id === id) ?? null)  if (cited.some((chunk) => chunk === null)) return { ok: false, reason: 'uncited' }  // No null is left past the check above: these are the cited chunks, in the order they were cited.  const sources = cited as Chunk[]

Every id a given chunk Query time

WhatEach id is looked up among the given chunks; any miss returns uncited. Otherwise the chunks are kept in citation order.

WhyA citation to a chunk the model was not given cannot be verified against anything, so the whole reply fails instead of showing a source the model never saw.

The same idea, shown in the course's code: Citation check in code: every cited passage number must be one the model was shown From From engineer to AI engineer, Ep 8: Making it good, with numbers
  // Figures, by contrast, are compared as text on purpose: a number in the answer must appear,  // written the same way, in a cited passage or in the question. Every list item is checked the  // same way as the lead-in: a figure that appears only in a bullet is still a figure shown.  const grounded = new Set<string>()  for (const chunk of sources) for (const figure of figuresIn(chunk.text)) grounded.add(figure)  for (const figure of figuresIn(question)) grounded.add(figure)

The grounded figures Query time

WhatThe union of figuresIn() over every cited chunk's text and over the question.

WhyOnly cited passages count, so every figure must be supported by a passage the reply names. The question is included so the answer can repeat a figure the visitor asked about ("Is it 30 days?").

  // The first figure stated by no cited passage and not by the question refuses the whole answer.  for (const text of [answer, ...items]) {    for (const figure of figuresIn(text)) if (!grounded.has(figure)) return { ok: false, reason: 'ungrounded' }  }

Every stated figure grounded Query time

WhatEvery figure in the prose and in each item must be in the grounded set; the first that is not returns ungrounded.

WhyA wrong number is the most damaging error a document answer can make, and the easiest to verify mechanically. In the baseline run (evals/JOURNAL.md), book-14 said "six lenses" when only 3 of the 6 lenses had reached the model, and the check correctly refused it.

  // Length, refused rather than trimmed: a trimmed answer could drop the sentence or the item a  // citation was for.  if (items.length === 0) {    // Prose: the page promises two to four sentences.    if (sentences(answer) > MAX_SENTENCES) return { ok: false, reason: 'overlong' }

Prose: at most four sentences Query time

WhatWith no items, a reply of more than MAX_SENTENCES sentences returns overlong.

WhyThe reply is refused whole, because trimming sentences could drop the one a citation was for and leave a source shown for nothing.

  } else {    // A list: at most MAX_ITEMS entries, and the lead-in and each entry short. The allowance    // comes from the shape of the reply, not from the question's wording. A list can be longer in    // all than prose may be (a two-sentence lead-in and twelve two-sentence items is 26    // sentences); what is bounded is each piece, so no single bullet becomes a paragraph and the    // whole stays a list a reader can scan, never a long answer in one block.    if (items.length > MAX_ITEMS) return { ok: false, reason: 'overlong' }    if ([answer, ...items].some((text) => sentences(text) > MAX_ITEM_SENTENCES)) return { ok: false, reason: 'overlong' }  }  return { ok: true, answer, items, cited: sources }}

A list: per-piece bounds Query time

WhatWith items, more than MAX_ITEMS entries, or a lead-in or entry of more than MAX_ITEM_SENTENCES sentences, returns overlong. Otherwise it returns ok with the trimmed texts and the cited chunks.

WhyA list may be longer in total than prose (up to 26 sentences), so each piece is bounded instead of the whole, which keeps the list easy to scan.

UnitKind

type · lines 225–233View on GitHub

The three kinds of streamed unit.

/** * The streamed answer, one unit at a time (app.ts, AskEvent). The model writes plain text * with the ids of the passages each sentence rests on in square brackets (`… a $50 ticket * [a1b2c3-4].`), and a list as lines that start with "- ", each ending with its ids. A unit is one * prose sentence, found by the rule `sentences` uses, or one list line; a run of markers after a * sentence's full stop belongs to that sentence. */export type UnitKind = 'lead' | 'sentence' | 'item'

lead, sentence, item Type only

WhatThe comment defines the streamed format: plain text with each sentence's ids in square brackets, and a list as lines that start with "- ". It names two kinds of unit, one prose sentence or one list line, and says that markers after a full stop belong to the sentence before them. The third kind, lead (a list's lead-in), is named by the type and produced by units().

WhyThe kind travels to the page with each unit event, and the page draws a lead or sentence as prose and an item as a bullet. The comment points to AskEvent in app.ts, the event type these units travel in.

RawUnit

interface · lines 234–239View on GitHub

One complete unit as the model wrote it.

/** One complete unit of the model's text, its markers still in it. */export interface RawUnit {  kind: UnitKind  raw: string}

kind and raw text Type only

WhatThe unit's kind and its raw text, citation markers still in it.

WhyThe markers are needed to read the ids (idsIn()) and must be removed before figures are read (unmarked()), so the raw text is kept until checkUnits().

MARKER

constant · lines 240–247View on GitHub

The regular expression for a citation marker.

/** * A citation marker: one or more chunk ids in square brackets, "[a1b2c3-4]" or * "[a1b2c3-4, d5e6f7-8]". An id is letters, digits and underscores with at least one dash in it, * which every chunk id has (`<demo>-<upload>-<n>`, app.ts), so a bracketed word of the model's * own ("[sic]") is not read as a citation. Global, so `replace` and `matchAll` see every marker. */const MARKER = /\[\s*([A-Za-z0-9_]+(?:-[A-Za-z0-9_]+)+(?:\s*[,;]\s*[A-Za-z0-9_]+(?:-[A-Za-z0-9_]+)+)*)\s*\]/g

A bracketed list of chunk ids Module load

WhatMatches "[", optional spaces, one id, any number of further ids each preceded by a comma or semicolon with optional spaces, optional spaces, and "]". An id is runs of letters, digits or underscores joined by single dashes, with at least one dash. Capture group 1 holds the id list, and the g flag lets replace and matchAll find every marker.

WhyEvery chunk id has the form <account id>-<upload>-<n>, built from lowercase letters and digits (app.ts replaces any other character with x), so it always matches. A bracketed word with no dash, such as "[sic]" or "[1]", never matches.

matches: [a1b2c3-4], [a1b2c3-4, d5e6f7-8], [a1-2; b3-4]does not match: [sic], [1], [a1-]

PROSE_END

constant · lines 248–261View on GitHub

The regular expression that finds where a complete prose sentence ends in streamed text.

/** * Where each prose sentence ends, in text that still has its markers. Read left to right: *   (?<=[.!?])                       just after a full stop, "!" or "?"; *   (?<!(?:^|[:;,]\s*|\n)\d{1,3}\.)  but not after a list number ("1." at the start or after *                                    ":", ";", "," or a line break), the same rule as `sentences`; *   ((?:\s*\[[^\]\n]*\])*)           then any run of markers, captured, so they stay with the *                                    sentence they follow ("...30 days [a1-2]." or "...days. [a1-2]"); *   \s+(?=[^\s[])                    then whitespace, and ahead of it the next sentence's first *                                    character, which is not another marker. * A sentence is complete only when the text after it has begun, so a full stop at the very end of * the text so far does not end a unit: the model may still be writing that sentence's markers. */

Reading the pattern Never runs

WhatThe comment reads the pattern part by part: right after ".", "!" or "?"; not after a list number (the same rule as sentenceParts()); then any run of bracketed markers, captured; then whitespace followed by a character that is neither whitespace nor "[".

WhyIt also states the rule that makes streaming safe. A sentence is complete only once the next one has begun, because right after a full stop the model may still be writing that sentence's markers.

const PROSE_END = /(?<=[.!?])(?<!(?:^|[:;,]\s*|\n)\d{1,3}\.)((?:\s*\[[^\]\n]*\])*)\s+(?=[^\s[])/g

The pattern Module load

WhatTwo zero-width lookbehinds fix the position after sentence punctuation. Group 1, ((?:\s*\[[^\]\n]*\])*), takes any run of bracketed text that follows; whitespace, line breaks included, may precede each bracket, and a bracket's contents may not span a line. \s+ consumes the gap, and the lookahead (?=[^\s[]) requires the next sentence to have started.

WhyGroup 1 lets both marker styles work: "…30 days [a1-2]." (marker before the stop, group empty) and "…30 days. [a1-2]" (marker after it, captured into the sentence). The text "A [x-1]. [y" has no match, because the second marker is unfinished, so the sentence waits. The bracket class accepts any bracketed text, including words that are not ids, so a "[sic]" after a stop also stays with its sentence.

"Fees are due [a-1]. Late" → "Fees are due [a-1]." complete"Fees are due [a-1]." → not yet complete

proseUnits()

function · lines 262–282View on GitHub

Splits prose into its complete sentences and the remainder still being written.

Called by units()

/** * The prose sentences of `text` that are complete, and the remainder still being written. Each * match of PROSE_END marks the end of one sentence (its markers included, which is why the match's * first group is counted into the sentence); the next sentence starts after the whitespace. */function proseUnits(text: string): { done: string[]; rest: string } {

Signature Query time

WhatReturns done, the complete sentences with their markers, and rest, the text after the last complete one.

WhyThe caller decides what rest means: text still being written while streaming, the last sentence at the end, or a list's lead-in when a list line follows.

  const done: string[] = []  // Where the sentence being read began.  let start = 0

State: done and start Query time

Whatdone collects sentences; start is where the current sentence began.

WhySlicing between match positions keeps the model's exact text, line breaks inside a sentence included.

  // Cut the text at each sentence end, keeping its markers with it.  for (const match of text.matchAll(PROSE_END)) {    const end = (match.index ?? 0) + match[1].length    done.push(text.slice(start, end))    start = (match.index ?? 0) + match[0].length  }

Cut at each sentence end Query time

WhatFor each PROSE_END match, the sentence runs from start to the match position plus group 1's length (the trailing markers). The next sentence starts after the whole match, past the whitespace.

WhyThe match begins right after the punctuation because the lookbehinds consume nothing, so adding group 1's length is exactly what keeps "[a1-2]" in "…days. [a1-2]" with its sentence.

  // Whatever follows the last complete sentence is still being written.  return { done, rest: text.slice(start) }}

The remainder Query time

WhatReturns done and the text from start to the end.

Whyrest may be empty, a sentence in progress, or a sentence that ends with a full stop but has nothing after it yet.

units()

function · lines 283–345View on GitHub

Cuts the reply so far into its complete units: prose sentences, a list's lead-in, and list items.

Called by answering(): ASK 6–7Calls proseUnits()

/** * The complete units of the text so far, in order: prose sentences, a list's lead-in, and list * items. With `final`, the stream has ended and what is left is the last unit. * * This is called again after every piece of the model's reply, on the whole text so far, and it * must be stable: the units it returns for a text are the leading units it returns for any longer * text that begins the same way. Then the caller (app.ts, `release`) can slice off the units it * has already dealt with and take only the new ones, and a unit once released is never revised. * Stability is why the line being written is set aside, why a sentence needs the next one to have * begun, and why a lone "-" waits. */export function units(text: string, final: boolean): RawUnit[] {

Stability: earlier units never change Query time

Whatunits() is called after every piece, on the whole text so far; final means the stream has ended. The comment states the invariant: the units returned for a text are the leading units returned for any longer text that begins with it.

Whyrelease() in app.ts skips the first shown.length + held.length units, those already shown or held, so a unit once returned must never change kind, text or position. Each of its rules (holding back the open line, a sentence waiting for the next, a lone "-" waiting) exists to keep that invariant.

  const out: RawUnit[] = []  // Lines, because a list item is one line: the model writes each as "- ..." on a line of its own.  const lines = text.split('\n')

Split into lines Query time

Whatout collects the units, and the text is split at line breaks.

WhyList items are recognised line by line, because the model writes each "- " item on its own line.

  // The last line is still being written unless the stream has ended: it is held back and looked at separately below.  const open = final ? null : lines.pop() ?? ''

Hold back the open line Query time

WhatUnless final is set, the last line is removed from lines into open, since the model may still be writing it.

WhyA line is known to be complete only once a line break follows it. While streaming, "- Team Lead, Zon" must not be released as an item.

  // Prose gathered from the completed lines, until a list line or the end completes it.  let prose = ''

prose: lines since the last item Query time

WhatThe prose lines collected since the last list item.

WhyA sentence may run across several lines, so prose is gathered first and cut into sentences afterwards.

  // A list line completes the prose before it: its sentences, and the rest as the list's lead-in.  const lead = () => {    const { done, rest } = proseUnits(prose)    for (const raw of done) out.push({ kind: 'sentence', raw })    if (rest.trim().length > 0) out.push({ kind: 'lead', raw: rest })    prose = ''  }

lead(): a list line closes the prose Query time

WhatCuts the gathered prose: its complete sentences become sentence units, any remainder becomes a lead unit, and prose is cleared.

WhyOnce a list line starts, the prose before it can grow no further, so its last part is complete even with no sentence after it. That part is the list's lead-in ("He has held these jobs [a-1]:"), which ends in a colon and so would never match PROSE_END.

  // Sort the completed lines into list items and prose.  for (const line of lines) {    if (line.startsWith('- ')) {      // A completed list line is a whole item; the prose before it, if any, is the list's lead-in.      lead()      out.push({ kind: 'item', raw: line.slice(2) })

Completed list lines Query time

WhatEach completed line that starts with "- " closes the prose (lead()) and becomes an item without its "- ".

WhyOnly a dash and a space at the very start of a line make an item. "* ", "1. " or an indented " - " stays prose, which is why ANSWER_RULES spells out the syntax.

    } else if (line.trim().length > 0) {      // A completed prose line joins the prose; a sentence may run over several lines.      prose += (prose.length > 0 ? '\n' : '') + line    }  }

Completed prose lines Query time

WhatAny other non-blank completed line is appended to prose, joined to the previous one with a line break. Blank lines are skipped.

WhyJoining with "\n" keeps the line break as whitespace PROSE_END can split at, and as the line-break case of the list-number rule.

  // The line being written: once it starts "- " it is a list line, and the prose before it is complete;  // a lone "-" waits to see which it is.  if (open !== null) {    if (open.startsWith('- ')) lead()    else if (open !== '-' && open.trim().length > 0) prose += (prose.length > 0 ? '\n' : '') + open  }

The open line Query time

WhatIf the open line starts with "- ", lead() closes the prose before it, but the item itself is not emitted. If the open line is exactly "-", nothing happens. Otherwise, if it is non-blank, it joins prose.

WhyA lone "-" could start a list line or prose ("-5 degrees"). Treated as prose, it would complete the previous sentence as a sentence unit. If it then became a list line, lead() would emit that same text as a lead unit, a change of kind that breaks stability. So it waits for one more piece.

  if (final) {    // The end of the stream completes whatever prose is left: a last sentence with no full stop, or a lead-in with no list.    const { done, rest } = proseUnits(prose)    for (const raw of done) out.push({ kind: 'sentence', raw })    if (rest.trim().length > 0) out.push({ kind: 'sentence', raw: rest })

Final: everything left is complete Query time

WhatAt the end of the stream, the prose's complete sentences and then its remainder are emitted as sentence units.

WhyThe last sentence has nothing after it. A lead-in with no list after it is emitted with kind sentence, and either kind counts toward the prose cap.

  } else {    // Only the sentences already followed by another are complete.    for (const raw of proseUnits(prose).done) out.push({ kind: 'sentence', raw })  }  return out}

While streaming: only finished sentences Query time

WhatOtherwise only proseUnits().done is emitted, and out is returned.

WhyThe remainder may still gain words or markers, so it is not returned yet. The cost is one sentence of delay, because a sentence is released only when the model starts the next.

unmarked()

function · lines 346–354View on GitHub

A unit's text as the page shows it.

Called by checkUnits()

/** * A unit's text as shown: its markers out, the space they leave before punctuation closed up * ("30 days [a1-2]." becomes "30 days."), and runs of whitespace made one space. This is done * before `figuresIn` reads the text, since an id's digits would otherwise count as figures. */export function unmarked(raw: string): string {  return raw.replace(MARKER, ' ').replace(/[ \t]+([.,;:!?])/g, '$1').replace(/\s+/g, ' ').trim()}

Markers out, spacing closed up Query time

WhatEach marker is replaced by a space, spaces or tabs before . , ; : ! ? are removed, every whitespace run (line breaks included) becomes one space, and the result is trimmed.

Why"30 days [a1-2]." becomes "30 days." instead of "30 days .". checkUnits() calls it before figuresIn(), because an id such as a1b2c3-4 contains digits that would otherwise be read as ungrounded figures.

'The fee is $5 [ab-1, cd-2].' → 'The fee is $5.' (demo.test.ts)

idsIn()

function · lines 355–359View on GitHub

The ids a unit cites.

Called by checkUnits() uncited

/** The ids a unit cites, in the order it cites them, each once: the group inside each marker, split at its commas and semicolons. */export function idsIn(raw: string): string[] {  return [...new Set([...raw.matchAll(MARKER)].flatMap((m) => m[1].split(/\s*[,;]\s*/)))]}

Every id, once, in order Query time

WhatFor every MARKER match, group 1 is split at commas or semicolons and the spaces around them. The ids are flattened and de-duplicated by a Set, which keeps first-seen order.

WhyThat order is the order of first citation, which ASK 8 keeps for the sources. The split accepts commas and semicolons, as MARKER does.

'The fee is $5 [ab-1, cd-2].' → ['ab-1', 'cd-2'] (demo.test.ts)

Counts

interface · lines 360–365View on GitHub

Units released so far, by kind.

/** How many prose units (sentences and list lead-ins) and list items have been released so far. */export interface Counts {  prose: number  items: number}

prose and items Type only

WhatThe number of prose units (sentences and lead-ins) and of items already released.

WhyThe caps apply to the whole answer, but checkUnits() sees one group, so app.ts keeps these totals and passes them in.

UnitsChecked

type · lines 366–370View on GitHub

checkUnits()'s verdict.

/** A group's verdict: when `ok`, each unit's text to show, and the chunks the group cites. */export type UnitsChecked =  | { ok: true; units: { kind: UnitKind; text: string }[]; cited: Chunk[] }  | { ok: false; reason: 'empty' | 'uncited' | 'ungrounded' | 'overlong' }

Units to show, or a reason Type only

Whatok true with each unit's kind and display text and the group's cited chunks, or ok false with empty, uncited, ungrounded or overlong.

WhyOnly the unmarked text is returned for display, so the page never receives raw markers. The cited chunks are shared by every unit of the group.

uncited

constant · lines 371–373View on GitHub

Whether a unit has no citation of its own.

Called by answering(): ASK 6–7Calls idsIn()

/** Whether a unit cites nothing of its own, and so waits for the next one (`checkUnits`). */export const uncited = (unit: RawUnit) => idsIn(unit.raw).length === 0

No ids Query time

WhatTrue when idsIn() finds no id in the unit's raw text.

Whyrelease() in app.ts uses it to hold a unit instead of checking it. It shares its name with the failure reason 'uncited', which is what a held unit becomes if no cited unit follows it.

checkUnits()

function · lines 374–422View on GitHub

Checks a group of units (any held ones plus one cited unit) against the passages the group cites and the question.

Called by answering(): ASK 6–7Calls figuresIn() idsIn() sentences() unmarked()

/** * Checks units released together as `checkAnswer` checks a whole reply. Usually one unit; a * sentence the model wrote without ids ("No, it is a small loss.") is held and released with the * next unit that has them, checked against that unit's passages (Joel, 2026-10-30). The group must * cite at least one id and every id must be a given chunk; every figure in every unit of it must be * in a passage it cites or in the question, read after the markers are taken out (ids hold digits); * and no unit may be the fifth prose sentence, the thirteenth item, or an item longer than * MAX_ITEM_SENTENCES. `counts` are the units released before the group. */export function checkUnits(group: RawUnit[], given: Chunk[], question: string, counts: Counts): UnitsChecked {

The rules, per group Query time

WhatThe comment lists the rules. The group must cite at least one id, and every id must be a given chunk. Every figure in every unit, read with markers removed, must be in a cited passage or in the question. No unit may be the fifth prose unit, the thirteenth item, or an item longer than MAX_ITEM_SENTENCES. counts are the units released before the group.

WhyThese are checkAnswer()'s rules applied one group at a time, so the same reasons are recorded whether an answer is refused whole or stopped partway.

  // The texts as they would be shown, markers out. A unit that was only markers says nothing.  const texts = group.map((unit) => unmarked(unit.raw))  if (texts.some((text) => text.length === 0)) return { ok: false, reason: 'empty' }

A unit of markers only: empty Query time

WhatEach unit's display text is computed; if any is empty, the group fails as empty.

WhyA line holding only "[a1-2]" says nothing, and releasing it would draw an empty sentence or bullet.

  // Every id the group cites, matched to a given chunk by id, exactly, as `checkAnswer` matches  // them: one that matches none (misspelt, invented, or from outside the context) fails the group.  const ids = [...new Set(group.flatMap((unit) => idsIn(unit.raw)))]  if (ids.length === 0) return { ok: false, reason: 'uncited' }

At least one id Query time

WhatThe ids of all units, de-duplicated; if there are none, the group fails as uncited.

Whyrelease() never sends a group whose last unit lacks ids, so in practice this guards other callers.

  // Each id matched to its given chunk, or null when no given chunk has that id.  const cited = ids.map((id) => given.find((chunk) => chunk.id === id) ?? null)  if (cited.some((chunk) => chunk === null)) return { ok: false, reason: 'uncited' }  // No null is left past the check above: these are the cited chunks, in order.  const sources = cited as Chunk[]

Every id a given chunk Query time

WhatEach id is matched exactly against the given chunks' ids; any miss returns uncited. Otherwise the cited chunks are kept in citation order.

WhyThe given chunks are the passages in the model's prompt after rerank and widening. An id from outside them (misspelt, invented, or from another demo account) cannot be verified, so the group fails.

  // Figures are compared as text: a number in any unit of the group must appear, written the same  // way, in a passage the group cites or in the question. A held sentence is covered by the  // passages of the sentence it is released with, which is what makes holding it safe.  const grounded = new Set<string>()  for (const chunk of sources) for (const figure of figuresIn(chunk.text)) grounded.add(figure)  for (const figure of figuresIn(question)) grounded.add(figure)

The grounded figures Query time

WhatThe union of figuresIn() over the cited chunks' stored text and over the question.

WhyOnly the passages the group cites count, so each figure must be supported by a source the reader will see under the answer. A held sentence is covered only by the passages of the unit it is released with.

  // The first figure found in neither refuses the whole group.  for (const text of texts) for (const figure of figuresIn(text)) if (!grounded.has(figure)) return { ok: false, reason: 'ungrounded' }

First ungrounded figure fails Query time

WhatEvery figure in every unit's display text must be in the grounded set; the first that is not returns ungrounded.

WhyThe texts are the unmarked ones, so the digits in ids are not read as figures. Membership is exact string comparison: "4,200" in the answer matches "4200" or "4,200" in a passage, because figuresIn() normalises both the same way.

  // The caps, counted on from what was released before this group: the fifth prose sentence or  // the thirteenth item fails, as does an item longer than MAX_ITEM_SENTENCES. Refused rather  // than trimmed, as before: the answer stops at four or twelve and says so.  let { prose, items } = counts

Caps from the running counts Query time

WhatTakes local copies of the counts so far.

WhyThey are copies because a failing group must not change app.ts's counts; app.ts increments those itself as each unit is released.

  for (const [i, unit] of group.entries()) {    if (unit.kind === 'item') {      if (++items > MAX_ITEMS || sentences(texts[i]) > MAX_ITEM_SENTENCES) return { ok: false, reason: 'overlong' }    } else if (++prose > MAX_SENTENCES) {      return { ok: false, reason: 'overlong' }    }  }

Fifth sentence, thirteenth item, long item Query time

WhatFor each unit in order, an item increments items and fails if it is past MAX_ITEMS or longer than MAX_ITEM_SENTENCES by sentences(). A lead or sentence increments prose and fails past MAX_SENTENCES.

WhyA failing group is refused whole. The units already shown stay, and the page draws the stop line. evals/runs/2026-10-30T13-49-56-stream-final shows this outcome as "answered (stopped: overlong)" on book-20, boundary-01 and boundary-05.

prose > 4 → overlongitems > 12 → overlongitem sentences > 2 → overlong

  return { ok: true, units: group.map((unit, i) => ({ kind: unit.kind, text: texts[i] })), cited: sources }}

Pass: the units and their cited chunks Query time

WhatReturns each unit's kind and display text, and the group's cited chunks.

Whyapp.ts releases them in order and gives every unit of the group the same cited chunks, held units included.

An answer to the same question, checked unit by unit This is the pinned check.ts, run unit by unit as release() in app.ts runs it, on the answer Claude Sonnet gave to the same question in an earlier capture. Its passage ids come from that earlier run, not from the answer request. Each unit is checked against the widened passages the answer was given: it must cite ids of those passages, and every figure in it must appear in a passage it cites or in the question. The sentence splitter ends a sentence at a full stop followed by a space, so "v20. or higher" became two units. The first has no ids of its own, so it is held and checked with the next unit, against that unit's ids. Every unit of this answer passed. A unit that fails ends the answer at that point, with one of four reasons: empty, uncited, ungrounded or overlong. A held unit with no cited unit after it also ends the answer. Captured 2026-11-29 from the eval harness's Worker under wrangler dev (evals/worker.ts), case book-01 of evals/cases.jsonl, with book.pdf; check.ts at the pin replayed on its text, claude-sonnet-5-5, at 84ebd1f.

The passages it was given, as the answer prompt lists them

[
  {
    "id": "lxo1nooz8rftmuq3-13ti0gub-19",
    "file": "book.pdf",
    "page": 12,
    "last_page": 16
  },
  {
    "id": "lxo1nooz8rftmuq3-13ti0gub-493",
    "file": "book.pdf",
    "page": 262,
    "last_page": 264
  },
  {
    "id": "lxo1nooz8rftmuq3-13ti0gub-132",
    "file": "book.pdf",
    "page": 74,
    "last_page": 75
  },
  {
    "id": "lxo1nooz8rftmuq3-13ti0gub-9",
    "file": "book.pdf",
    "page": 8,
    "last_page": 9
  },
  {
    "id": "lxo1nooz8rftmuq3-13ti0gub-452",
    "file": "book.pdf",
    "page": 241,
    "last_page": 242
  },
  {
    "id": "lxo1nooz8rftmuq3-13ti0gub-456",
    "file": "book.pdf",
    "page": 243,
    "last_page": 244
  },
  {
    "id": "lxo1nooz8rftmuq3-13ti0gub-50",
    "file": "book.pdf",
    "page": 28,
    "last_page": 29
  },
  {
    "id": "lxo1nooz8rftmuq3-13ti0gub-61",
    "file": "book.pdf",
    "page": 34
  }
]

Each unit, and the check

[
  {
    "unit": "You need Node.js 20 or newer, along with npm [lxo1nooz8rftmuq3-13ti0gub-19].",
    "kind": "sentence",
    "cites": [
      "lxo1nooz8rftmuq3-13ti0gub-19"
    ],
    "verdict": "released",
    "shown_as": "You need Node.js 20 or newer, along with npm.",
    "figures": [
      "20"
    ]
  },
  {
    "unit": "To check, run `node --version`; if it prints something starting with v20.",
    "kind": "sentence",
    "cites": [],
    "verdict": "held: no ids of its own, waits for the next unit",
    "shown_as": "To check, run `node --version`; if it prints something starting with v20.",
    "figures": [
      "20"
    ]
  },
  {
    "unit": "or higher, you have what the examples need [lxo1nooz8rftmuq3-13ti0gub-19].",
    "kind": "sentence",
    "cites": [
      "lxo1nooz8rftmuq3-13ti0gub-19"
    ],
    "verdict": "released together with the held unit before it; the group's figures (20) checked against the passages this unit cites",
    "shown_as": "or higher, you have what the examples need.",
    "figures": [
      "20"
    ]
  }
]