Joel Stevick

The ask · ASK 5 · stage 5 of 7

Rerank and widen

After retrieval and the whole-document check, Claude Haiku reads the candidate pool of up to 48 chunks and names the passages that answer, best first. Its choice goes first, the rest of the pool follows in pool order, and the list is cut to 12 (ANSWER_CHUNKS). For an account too large to read whole, widen() then joins each chosen chunk with the chunk before it and the chunk after it in the same file, under a shared budget of 10,800 characters. The result, given, is the only text the answer model sees at ASK 6.

Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
demo/src/app.ts10 / 10 lines on this page explainedlines 705-714 of 1124; the rest are on other stage pages
demo/src/models.ts64 / 64 lines on this page explainedlines 236-299 of 355; the rest are on other stage pages
demo/src/widen.ts96 / 96 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.

answering(): ASK 5

segment · lines 705–714View on GitHub

Where the ask reranks the pool and widens the choice.

Calls rerank() widen()

  // ASK 5 · rerank (Claude picks the best passages), then widen (add their neighbours)  // Each chosen chunk with its neighbours, unless every chunk is already given. It passed 5 of 5  // boundary cases against 4 of 5 for 60% more a question, past the bar set before the runs;  // Joel switched it on for the better answers (/blog/widening, evals/runs/*-widen-*).

Why widening is on Never runs

WhatThe comment names the stage and records the evidence for widening. With widening, 5 of 5 boundary cases passed; without it, 4 of 5 passed, and widening cost about 60% more a question. The 60% holds for the boundary questions themselves (about $0.0113 to $0.0181 each); the cost of a whole run rose about 54%.

WhyThe boundary cases (evals/cases.jsonl, boundary-01 to -05) each put the question's words in one chunk and the answer in the next chunk of the same file. Without widening, boundary-03 failed in both runs; with it, all five passed in both.

evals/runs/2026-10-21T21-17-59-widen-before, 21-27-27-widen-before: boundary 4 of 5evals/runs/2026-10-21T21-37-07-widen-after, 21-45-42-widen-after: boundary 5 of 5evals/runs/2026-10-21T21-17-59-widen-before vs 21-37-07-widen-after: boundary cases $0.0563 → $0.0910 in all (+62%)evals/runs/*-widen-*: run cost $0.32–0.33 before, $0.50 after (about +54%)

  yield { type: 'stage', stage: 'reranking' }  const chosen = await rerank(models.claude, question, pool)

Rerank the pool Query time

Whatanswering() yields a stage event, which the demo page shows as "Choosing passages…", then awaits rerank() with the Claude client, the question and the pool. The pool is the fused candidates, or every chunk when the documents were read whole.

Whyrerank() never throws. Any failure inside it returns the pool in fusion order, so the ask always reaches ASK 6 with passages to answer from. The stage event goes out first because the Haiku call can take seconds.

Explained in Ep 1: Re-ranking: a model orders the pool of 48, the top 12 widened From RAG deep dive, Ep 1: RAG Debugging: Retrieval, Reranking or Generation?
The question form with "Choosing passages…" on the status line under it.
The status line after the reranking stage event arrives. It reads "Choosing passages…" while Claude Haiku ranks the candidate pool. 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.
  // When every chunk is already given there is nothing to widen into.  const given = whole || options.widen === false ? chosen : widen(chosen, all)

Widen, unless everything is already given Query time

Whatgiven is the reranker's choice unchanged when the documents were read whole (12 chunks or fewer) or when Options.widen is false. Otherwise it is widen(chosen, all).

WhyWhen the documents were read whole, rerank() already returned every chunk, so there is no neighbour left to add. widen: false exists so the tests can compare both paths, and the deployed demo app never sets it.

demo/src/models.ts The model clients and prompts.

ANSWER_CHUNKS

constant · lines 236–242View on GitHub

How many passages the answer is written from, before widening.

/** * How many chunks the answer is written from: about 11,000 characters, room for * every entry of a two-page résumé. A question asking for every one of something * needs every passage that holds one; five left half of them out. */export const ANSWER_CHUNKS = 12

Twelve passages Module load

Whatrerank() returns at most 12 chunks, and a demo account with 12 chunks or fewer is read whole (app.ts:689). At up to 900 characters a chunk (CHUNK_CHARS), 12 chunks hold at most 10,800 characters.

WhyA question asking for every one of something needs every passage holding one. With 5, the résumé's jobs question lost the employers on page 2; with 16, the evals gained nothing and cost 17% more. check.ts caps a list at 12 items (MAX_ITEMS) to match.

ANSWER_CHUNKS = 12CHUNK_CHARS = 900 (chunks.ts)evals/JOURNAL.md, The failure: 5 chunks dropped page 2 of the résuméevals/JOURNAL.md, round 4: 16 passages, no gain, 17% more cost

Explained in Ep 1: A reranker miss: 3 of 3 in the pool, 1 of 3 in the top 12 From RAG deep dive, Ep 1: RAG Debugging: Retrieval, Reranking or Generation?

RERANK_RULES

constant · lines 243–249View on GitHub

The reranker's system prompt.

/** The reranker's instructions: pick the passages that answer, best first. */const RERANK_RULES = `You choose which passages answer a question about a set of documents.You are given the question and a numbered list of passages.Return the numbers of the passages that answer the question, best first, at most ${ANSWER_CHUNKS}.When the question asks for every one of something (every job, every date, every fee), include every passage that holds one.Return an empty list if none answers it.`

The reranker's instructions Module load

WhatThe system prompt, a template literal filled once at module load. It asks for the numbers of the passages that answer, best first, at most 12; for a question about every one of something, every passage that holds one; and an empty list if none answers.

WhyThe "every one of something" line is for list questions, where the answer is spread over many passages and a relevance ranking alone would keep only the closest few. The prompt's limit of 12 is only an instruction, so the code cuts the list to 12 itself.

rerank()

async function · lines 250–299View on GitHub

Orders the pool by Claude Haiku's choice, then fusion order, and cuts it to 12.

Called by answering(): ASK 5

/** * The chunks the answer is written from: Claude Haiku's choice from the pool * first, as in Howard's Lantern's worker/src/law-rerank.ts * (`haikuRerankFor`, `chooseLaws`), then the rest of the pool by fusion, up to * ANSWER_CHUNKS. The reranker orders the context; it does not cut it, because a * passage it passed over may still hold part of the answer. Failing or naming a * passage it was not given, the pool by fusion alone. */

The unchosen fill the rest Never runs

WhatThe doc comment states the contract: Haiku's choice first, then the rest of the pool by fusion, up to ANSWER_CHUNKS; on failure, or a passage number it was not given, the pool by fusion alone.

WhyPassages the reranker did not choose still fill the remaining places up to 12, because a passage it passed over may still hold part of the answer. rerank() is a port of Howard's Lantern's law rerank (haikuRerankFor, chooseLaws).

export async function rerank(claude: Claude, question: string, pool: Chunk[]): Promise<Chunk[]> {  // Nothing to rank, so nothing to answer from.  if (pool.length === 0) return []

Signature and the empty pool Query time

WhatTakes the Claude client, the question and the pool; an empty pool returns an empty list without a model call.

Whyanswering(), the only caller of rerank(), has already ended an empty pool with the fallback line (app.ts:698). The guard is defensive and keeps a pointless model call from ever being made.

  // Ask Haiku which passages answer the question, best first.  try {    const reply = (await claude({      model: RERANK_MODEL,      system: RERANK_RULES,      // Passages go in numbered by position, [0] onward; the model answers with those numbers.      user: `Question: ${question}\n\nPassages:\n\n${pool.map((chunk, index) => `[${index}] ${chunk.text}`).join('\n\n')}`,

One call to Haiku, passages numbered Query time

WhatCalls Claude Haiku (RERANK_MODEL, claude-haiku-5-5) with RERANK_RULES as the system prompt. The user message is the question, then each chunk's text under a label [0], [1], … in pool order, with no ids, files or pages.

WhySmall integer labels are cheap to emit, and the model cannot mistype them the way it could mistype chunk ids of about 28 characters (<account id>-<upload>-<n>). The labels follow pool order, which is fusion order, so the model reads the best-fused passages first. When the documents are read whole, the chunks retrieval did not return follow in upload order.

RERANK_MODEL = 'claude-haiku-5-5'up to 48 passages × 900 characters

Explained in Ep 1: The Claude Haiku reranker: numbered passages, fallback, token limit From RAG deep dive, Ep 1: RAG Debugging: Retrieval, Reranking or Generation?
The rerank request, as sent to Claude Haiku The request holds the question, then the candidate pool, each passage numbered by its position from [0]. output_config holds a JSON schema, so the response's one text block is a JSON string of that shape. Its "ranked" list holds pool positions, best first, and names no chunk ids. rerank() puts those passages first and fills up to 12 from the rest of the pool in fusion order, and widen then joins neighbouring chunks. The effort in output_config is the request's only reasoning setting, and the response has no thinking block. 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-haiku-5-5, at 84ebd1f.

Request body

{
  "model": "claude-haiku-5-5",
  "max_tokens": 1024,
  "system": "You choose which passages answer a question about a set of documents.\n
You are given the question and a numbered list of passages.\n
Return the numbers of the passages that answer the question, best first, at most 12.\n
When the question asks for every one of something (every job, every date, every fee), include every passage that holds one.\n
Return an empty list if none answers it.",
  "messages": [
    {
      "role": "user",
      "content": "Question: What version of Node do I need before starting the book's examples?\n
\n
Passages:\n
\n
[0] Introduction 7\n
1. Node.js 20 or newer, and npm. Check the version you have with\n
node --version ; if it prints something starting with v20. or higher, you\n
have w…[459 characters]…ell environment rather than in a file you might commit:\n
export ANTHROPIC_API_KEY=\"sk-ant-...\"\n
While you are in the console, set a spending limit under Billing .\n
\n
[1] 10 Introduction\n
discussed is the only thing on the page. Complete files are labelled with\n
a line of exactly this shape, immediately above the code:\n
**Listing: `…[522 characters]…if you change one string in one place; Chapter\n
1 shows you where that string lives.\n
Newer models invent fewer facts and agree with wrong suggestions less\n
often.\n
\n
[2] Appendix B: The Finished Workflow 257\n
fetch-depth : 0\n
- uses : actions/setup-node@v4\n
with :\n
node-version : 20\n
- run : npm ci\n
- name : Regression suite\n
run : npm…[303 characters]…\": {\n
\"quorum\": {\n
\"source\": {\n
\"source\": \"github\",\n
\"repo\": \"AiFirstDevelopment/quorum\"\n
}\n
}\n
},\n
\"enabledPlugins\": {\n
\"quorum@quorum\": true ,\n
\"tests@quorum\": true\n
}\n
}\n
\n
[3] That\n
point is the training cutoff , and after it the model knows nothing — not\n
because it refuses to answer, but because it has no way to distinguish\n
“after my …[516 characters]…ng about the API of\n
a fast-moving library, and next most about the library’s own best\n
practices. From inside the weights, the version it learned is the\n
library.\n
\n
[4] The parts you are going to build\n
Agentic workflows do not all need the same parts. A job that classifies\n
text or drafts a summary satisfies the definition above…[492 characters]…ch names\n
the chapter that builds it.\n
The first four cover acting. Together they are the agent.\n
A model call. One HTTP request carrying your instructions and ev-\n
\n
[5] Introduction 9\n
{\n
\"compilerOptions\": {\n
\"target\": \"ES2022\",\n
\"lib\": [\"ES2022\"],\n
\"module\": \"nodenext\",\n
\"moduleResolution\": \"nodenext\",\n
\"types\": [\"node\"],\n
\"strict\": …[489 characters]… you commit anything. Chapter 10 has you\n
run git add -A , and without this every change a reviewer reads from\n
Chapter 7 onward arrives buried in node_modules/ .\n
\n
[6] import fs from \"node:fs\";\n
import path from \"node:path\";\n
import { runAgent, READ_ONLY_TOOLS } from \"./loop.js\";\n
const PLANNER = [\n
\"You are writing a plan for a c…[554 characters]…r would expect and will not get.\",\n
\"Open questions are things you could not settle by reading the code. Never\",\n
\"invent an answer to one; list it and move on.\",\n
\n
[7] import fs from \"node:fs\";\n
import path from \"node:path\";\n
import { execFileSync } from \"node:child_process\";\n
\n
[8] Work-\n
ing through every chapter and re-running the examples a few times each\n
costs a few dollars rather than a few hundred, so five dollars is comfort-\n
ably mor…[574 characters]…ete before committing.\n
Every example ahead reads the key from the environment for that\n
reason.\n
3. A project directory. Everything you build lives in one folder:\n
\n
[9] 8 Introduction\n
mkdir agentic-workflow && cd agentic-workflow\n
npm init -y\n
npm install @anthropic-ai/sdk\n
npm install --save-dev typescript tsx @types/node\n
Anthrop…[476 characters]…\n
\"@anthropic-ai/sdk\": \"^0.124.0\"\n
},\n
\"devDependencies\": {\n
\"@types/node\": \"^20.14.0\",\n
\"tsx\": \"^4.16.0\",\n
\"typescript\": \"^5.5.0\"\n
}\n
}\n
Then run npm install once more.\n
\n
[10] On the model these examples use, thinking is\n
on unless you switch it off, and that has two consequences you will see\n
before you set either field: the output_tok…[414 characters]…hing in the chapters ahead sets either one. The defaults are what\n
every example was run with, and the token counts you add up in Chapter\n
4 include the thinking.\n
\n
[11] 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();\n
\n
[12] What It Knows and Forgets 69\n
There are two fixes, and they are the same fix at different scales.\n
Put the current truth in the context. If the request depends on…[560 characters]…hat 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
[13] 118 Running the Thing\n
Figure 8.1: The model chooses what to try and reads what happened. The\n
running happens in between, in your code.\n
Warning: If you skip step…[540 characters]…rogram does; you are guessing at what\",\n
\"might break it, from the plan alone.\",\n
\"\",\n
\"Return one input per line and nothing else. No numbering, no\",\n
\"commentary.\n
\n
[14] Introduction 3\n
erything sent and received so far, and one response. The model retains\n
nothing between calls: everything it knows on call n is what you put\n
in ca…[573 characters]…or, 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
[15] Tests That Can Fail 143\n
The tests\n
Node has a test runner built in, so there is no dependency to install and\n
nothing to configure.\n
Listing: demo/src/slugify.test…[555 characters]…ss\"); // capital sharp s\n
});\n
test(\"input with no slug characters becomes untitled\", () => {\n
assert.equal(slugify(\"///\"), \"untitled\");\n
assert.equal(slugify(\" \"),\n
\n
[16] Appendix B: The Finished Workflow 231\n
agentic/budget.ts\n
From What It Knows and Forgets.\n
import fs from \"node:fs\";\n
import Anthropic from \"@anthropic-ai/sdk\";\n
imp…[274 characters]…ng is worse than none.\n
// input_tokens is only the part of the prompt that was neither written\n
// to the cache nor read from it; the three prompt counts add up.\n
\n
[17] 222 Appendix B: The Finished Workflow\n
const slug = folded.replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n
return slug.length > 0 ? slug : \"untitled\";\n
}\n
dem…[507 characters]…OT = process.cwd();\n
const readFileTool: Anthropic.Tool = {\n
name: \"read_file\",\n
description:\n
\"Read a UTF-8 text file from the project and return its contents. \" +\n
\n
[18] 218 Appendix B: The Finished Workflow\n
tsconfig.json\n
From Introduction.\n
{\n
\"compilerOptions\": {\n
\"target\": \"ES2022\",\n
\"lib\": [\"ES2022\"],\n
\"module\": \"nodenext\",\n
\"modu…[350 characters]… line, not a stack trace.\n
if (!process.env.ANTHROPIC_API_KEY) {\n
console.error(\"ANTHROPIC_API_KEY is not set. Export it and run this again.\");\n
process.exit(1);\n
}\n
\n
[19] Appendix B: The Finished Workflow 245\n
});\n
agentic/judge.ts\n
From Somebody Has to Decide.\n
import fs from \"node:fs\";\n
import path from \"node:path\";\n
import { execFil…[326 characters]…\"You may not expand scope: a real defect outside this change is a\",\n
\"follow-up, never a repair.\",\n
].join(\"\\n
\");\n
const ADJUDICATOR = [\n
\"You are judging a change.\n
\n
[20] Appendix A: Glossary 209\n
R\n
rate limit — Chapter 1, 01-talking-to-a-model.md . A cap on how\n
many requests or tokens an account may use per minute, so that one\n
cl…[553 characters]…body of material that a particular request actually needs,\n
and sending only that. In its simplest form, read_file .\n
role — Chapter 1, 01-talking-to-a-model.md .\n
\n
[21] 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 takes the\n
package apart.\n
What you need before Chapter 1\n
Four things, none of which takes long.\n
\n
[22] 142 Tests That Can Fail\n
Everything in Chapters 6 through 9 is a judgement : a plan somebody\n
read, six reports somebody generated, a decision somebody made. All\n
…[422 characters]…mo/src/slugify.ts\n
// Characters that have a conventional multi-letter expansion. These must\n
// run before normalisation: NFD does not decompose ß into anything.\n
\n
[23] From Yours to Shared 175\n
reviews/ , and verdict.md , which is the layout you built in Chapter\n
6 with a different root directory.\n
tests is Chapter 10: behavioral…[460 characters]…r that is you on another machine, a colleague, or an\n
automated run, gets the same commands, because the settings are in\n
version control rather than on a laptop.\n
\n
[24] The guard\n
It is one script, which calls no model, needs no API key, and takes about\n
a second.\n
Listing: agentic/guard.ts\n
import fs from \"node:fs\";\n
import path fr…[156 characters]…detail: string;\n
}\n
// The same one command CI runs. A guard that checks a different suite\n
// from the one the project declares is checking nothing in particular.\n
\n
[25] 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 end of a\n
twe…[503 characters]… knowledge in play, and misunderstanding what is in\n
it causes a specific category of failure.\n
The weights were fitted on text gathered up to some point in time.\n
\n
[26] Contents\n
• Introduction\n
• 1. Talking to a Model\n
• 2. Giving the Model Hands\n
• 3. The Loop\n
• 4. What It Knows and Forgets\n
• 5. Why It Lies to You\n
• 6. Writing It…[108 characters]…an Fail\n
• 11. Rules a Prompt Can’t Hold\n
• 12. From Yours to Shared\n
• 13. Inside a Plugin\n
• Conclusion\n
• Appendix A: Glossary\n
• Appendix B: The Finished Workflow\n
\n
[27] One per command in Chapter 12’s table, plus four that\n
measure rather than build: audit , calibrate , history and status .\n
Open skills/3-review/SKILL.md and read…[362 characters]…t tools: What that settles\n
quorum-reviewer Read, Grep, Glob,\n
Bash\n
Reads and runs;\n
cannot Edit or Write\n
quorum-scribe Write Writes review files;\n
cannot read code\n
\n
[28] Writing It Down First 95\n
keep the steps, at which point the plan describes what happened rather\n
than what was wanted.\n
Example: Halfway through the accents chang…[461 characters]…s the code first, as plan.ts does, surfaces things you\n
did not know were there. The ß case in the running example came from\n
one.\n
The costs are just as specific.\n
\n
[29] Anthropic serves several models at once\n
— larger and slower, smaller and cheaper — and the model ID is how\n
you choose between them.\n
In Chapter 7 you will run th…[268 characters]…ff, and leaving it stan-\n
dalone means your first program depends on nothing but the SDK. Every\n
file from here on imports MODEL and requireApiKey from setup.ts .\n
\n
[30] Why It Lies to You 83\n
Asking for a confidence score. The number is generated the same\n
way the answer was. A fabricated function name comes with a fabricated\n
95%…[569 characters]…e\n
terms. A summary can assert that a requirement is met, whereas\n
a written-down requirement can be compared against the code,\n
which is what Chapter 6 builds.\n
2.\n
\n
[31] stateless — Chapter 1, 01-talking-to-a-model.md . Retaining noth-\n
ing between requests. Every response is produced from scratch using\n
only what that request con…[548 characters]…gent — Chapter 7, 07-a-second-pair-of-eyes.md . A process\n
that runs in its own fresh context, does one bounded job, and returns a\n
result to whatever started it.\n
\n
[32] Listing: .github/workflows/guard.yml\n
name : guard\n
on :\n
pull_request :\n
jobs :\n
guard :\n
runs-on : ubuntu-latest\n
steps :\n
- uses : actions/checkout@v4\n
with :\n
fetch-d…[180 characters]…if [ -d \"work/$slug\" ]; then\n
npx tsx agentic/guard.ts \"$slug\" \"origin/${GITHUB_BASE_REF}\"\n
else\n
echo \"no work item for branch $GITHUB_HEAD_REF; nothing to guard\"\n
\n
[33] Giving the Model Hands 39\n
.. ; it does not follow symbolic links, and readFileSync does. If\n
the project can contain a symlink pointing outside it — an npm\n
works…[538 characters]…built in\n
the next chapter:\n
const listFilesTool: Anthropic.Tool = {\n
name: \"list_files\",\n
description:\n
\"List the files in a directory of the project, one per line.\n
\n
[34] Neither 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
[35] 182 Inside a Plugin\n
number already in that directory. Then tell the user where the file is and\n
how many findings it holds. Do not act on the findings; that is t…[530 characters]…s tools are the ones on the tools: line and\n
no others. It receives one user message, the task, and runs Chapter 3’s\n
loop until the model stops asking for tools.\n
\n
[36] The model is a pure function of its input: same weights, same input,\n
same distribution over outputs. Memory, personality and continuity are\n
supplied by the prog…[332 characters]… line, not a stack trace.\n
if (!process.env.ANTHROPIC_API_KEY) {\n
console.error(\"ANTHROPIC_API_KEY is not set. Export it and run this again.\");\n
process.exit(1);\n
}\n
\n
[37] Where this leaves you\n
Eleven chapters have produced a plan format, a builder, six lenses, a\n
judge, a suite proven able to fail, a guard, a hook, and a job that runs\n
on somebody else’s computer.\n
Every line of it is code you wrote. That is the position from which to\n
look at somebody else’s version.\n
\n
[38] 6 Introduction\n
Chapter 12 is where you stop typing and start delegating, and Chapter\n
13 opens the package you delegated to and reads it against what you\n
wrote.\n
…[554 characters]…irectly: not through a wrapper, a framework or a\n
chat window, but a program of yours that makes an HTTP request to\n
Anthropic and does something with the answer.\n
\n
[39] Those are Chapter 11’s three layers,\n
and a plugin carries all three, so put each rule in the lowest layer\n
that can hold it.\n
Trying it, then shipping it\n
The harn…[377 characters]…on is the sentence in the script, and the model, told what to do\n
instead, proposes a new file.\n
Shipping it takes one more manifest, and a short one. The market-\n
\n
[40] 208 Appendix A: Glossary\n
indistinguishable from those of correct output. The reason reading the\n
answer is not a quality control.\n
plugin — Chapter 12, 12-from-yo…[575 characters]…ll be measured and\n
which result counts as which outcome. Borrowed from science, for the\n
same reason: a hypothesis chosen after seeing the data is a description.\n
\n
[41] Running the Thing 117\n
Rule: The behavior lens starts the real thing. Importing the func-\n
tion under test directly writes a different kind of test — the subject\n
…[574 characters]…The model proposes inputs. This is a task it is genuinely good\n
at: reading a plan and thinking of the awkward cases. Nothing\n
here is a claim about behaviour.\n
2.\n
\n
[42] Two plugins can each carry a review\n
skill without colliding, and a skill or an agent called by a bare name,\n
without its prefix, does not resolve.\n
Listing: plugi…[512 characters]…the harness substitutes\n
the plugin root , the directory the plugin was actually installed into,\n
before it runs the command, and hooks.json below relies on that.\n
\n
[43] The versions in that file are not the\n
ones the earlier commands installed, and package-lock.json records\n
what was installed; Chapter 11’s build job installs from the lock file and\n
refuses one that disagrees with package.json .\n
And add a TypeScript configuration beside it.\n
Listing: tsconfig.json\n
\n
[44] 206 Appendix A: Glossary\n
M\n
marketplace — Chapter 12, 12-from-yours-to-shared.md . A place\n
plugins are published and found; for Claude Code, a git repository wit…[575 characters]…0, 10-tests-that-can-fail.md . A check\n
that must pass before a change can be merged, enforced by something\n
other than the good intentions of the person merging.\n
\n
[45] If they agree, you have learned something\n
about the tool. If they disagree, find out which of you is right before\n
you adopt it for anything you could not have c…[255 characters]…t enforces the rules the others merely promise.\n
The next chapter opens the package you just installed and reads it, file\n
by file, against the version you wrote.\n
\n
[46] From Yours to Shared 173\n
The tools: line is doing something your version could not do as cleanly.\n
A reviewer with no Edit and no Write cannot modify code, so “r…[404 characters]…o a sandbox. It raises the cost of\n
drift substantially and it does not eliminate it, and a tool that claims\n
otherwise is describing something it has not tested.\n
\n
[47] \" +\n
\"Use this when you are unsure what a file is called.\",\n
input_schema: {\n
type: \"object\",\n
properties: {\n
dir: {\n
type: \"string\",\n
description: \"Project-relative d…[104 characters]…ke a choice, and the\n
choice is made from your description fields and nothing else. If\n
read_file said only “reads a file” and list_files said only “lists files,”"
    }
  ],
  "output_config": {
    "format": {
      "type": "json_schema",
      "schema": {
        "type": "object",
        "properties": {
          "ranked": {
            "type": "array",
            "items": {
              "type": "integer"
            }
          }
        },
        "required": [
          "ranked"
        ],
        "additionalProperties": false
      }
    },
    "effort": "low"
  }
}

Response

{
  "model": "claude-haiku-5-5",
  "id": "msg_011ChX7dR3yw7LFqYPUkpTon",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "{\"ranked\":[0,1,9,5]}"
    }
  ],
  "container": null,
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "stop_details": null,
  "usage": {
    "input_tokens": 12535,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0,
    "cache_creation": {
      "ephemeral_5m_input_tokens": 0,
      "ephemeral_1h_input_tokens": 0
    },
    "output_tokens": 18,
    "output_tokens_details": {
      "thinking_tokens": 0
    },
    "service_tier": "standard",
    "inference_geo": "global",
    "speed": "standard"
  },
  "diagnostics": null
}
      schema: { type: 'object', properties: { ranked: { type: 'array', items: { type: 'integer' } } }, required: ['ranked'], additionalProperties: false },

The reply's schema Query time

WhatclaudeFor sends this JSON Schema as structured output, so the reply is JSON with exactly one property, ranked, an array of integers.

WhyStructured output removes the parsing failures of free text. The schema does not bound the integers, so rerank() still checks their range.

      // Haiku 5.5 thinks first, inside this limit: at 256 its thinking spent the tokens before      // the list was written (4 of 25 eval questions, evals/runs), and with thinking off it      // ranked worse. Low effort and room to finish.      maxTokens: 1024,      effort: 'low',      // 48 passages took up to 4.3 s in the evals: 5 s left too little room before the fallback.      timeoutMs: 8000,    })) as { ranked?: unknown }

Token limit, effort, timeout Query time

Whatmax_tokens 1024, effort low and an 8-second timeout. The reply is cast to { ranked?: unknown }, so rerank() must check it before using it.

WhyHaiku 5.5 thinks before it writes, and the thinking counts against max_tokens. At 256 tokens it ran out before writing the list on 4 of 25 questions. With thinking off it ranked worse. Low effort with room to finish fixed both. 48 passages took up to 4.3 s, too close to the old 5-second timeout.

maxTokens = 1024effort = 'low'timeoutMs = 8000evals/JOURNAL.md, baseline: 256-token cap hit on 4 of 25evals/JOURNAL.md, round 2: low effort, 1024 tokensevals/JOURNAL.md, verifier: up to 4.3 s at 48 passages

    // The passage numbers the model chose.    const ranked = reply.ranked

The chosen numbers Query time

Whatranked is read from the reply, still typed unknown.

WhyThe next lines check it before the code trusts it.

    // A number outside the list means the model named a passage it was not given: the whole reply is distrusted.    if (!Array.isArray(ranked) || ranked.some((n) => !Number.isInteger(n) || n < 0 || n >= pool.length)) {      throw new Error(`the reranker named passages that were not given: ${JSON.stringify(reply)}`)    }

Distrust the whole reply on one bad number Query time

WhatIf ranked is not an array, or any entry is not an integer from 0 to pool.length − 1, rerank() throws, with the reply in the error message.

WhyA number outside the list means the model is answering about passages it was not given, so its whole ranking is suspect. The throw sends control to rerank()'s catch, the same path a timeout takes.

    // `ranked` holds positions in `pool`, the `[index]` labels the passages were sent under: not    // ids, not text. `includes` below is by object identity, on the same Chunk objects.    const chosen = [...new Set(ranked as number[])].map((n) => pool[n])

Numbers back to chunks Query time

WhatRepeats are removed with a Set, and each number is mapped to pool[n].

WhyThese are the same Chunk objects as in the pool and in all, so the includes test that follows, and widen's sets, compare by object identity.

    // The chosen first, then the rest of the pool in fusion order, cut to ANSWER_CHUNKS.    return [...chosen, ...pool.filter((chunk) => !chosen.includes(chunk))].slice(0, ANSWER_CHUNKS)

Chosen first, then the rest, cut to 12 Query time

WhatReturns the chosen chunks, then every unchosen pool chunk in pool order, cut to 12.

WhyAn empty ranked list ("none answers") returns the first 12 in pool order, so the reranker can reorder the context and can never empty it. Whether the documents answer the question is decided at ASK 6–7, by the answer model and the check.

  } catch (error) {    console.error('demo ask: the reranker did not answer', error)    // Fallback: the pool in fusion order.    return pool.slice(0, ANSWER_CHUNKS)  }}

Fall back to fusion order Query time

WhatAny error (no API key, an HTTP error, the timeout, JSON that does not parse, a bad number) is logged, and the first 12 of the pool are returned in fusion order.

WhyA reranker outage lowers ranking quality, and the question is still answered. The log line lets the drop be found later.

demo/src/widen.ts Neighbour widening, one pure function of arrays that calls no service.

Module scope

module scope · lines 1–20View on GitHub

The licence, what the module does, the Chunk import and the budget.

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

Licence Never runs

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

WhyThe repository is public under MIT. Licence scanners read the SPDX line without parsing prose.

/** * The passages the answer is written from: each chunk the reranker chose, * joined with the chunk before it and the chunk after it in the same file. * * The idea of Howard's Lantern's worker/src/learner-ask.ts * (`wholeSections`, "Hop 6"): there the rest of each chosen statute's section * is added after the rerank, under a character budget. A PDF has no sections, * so here the unit is the neighbouring chunk. A chunk is cut at a sentence end, * so a rule and its exception are often split across two chunks, and the * reranker picks only the half that matches the question's words. */

Why neighbours are added Never runs

WhatThe module comment: each chunk the reranker chose is joined with the chunk before it and the chunk after it in the same file. The idea comes from wholeSections in Howard's Lantern's learner-ask.ts, which adds the rest of a statute's section. A PDF has no sections, so here the unit is the neighbouring chunk.

WhyThe chunker cuts after the last sentence end between characters 450 and 900, else at the last space, so a rule and its exception often end up in two chunks. Retrieval and the reranker then match only the half that shares the question's words.

import type { Chunk } from './retrieval'

The Chunk type Type only

WhatImports the Chunk type from retrieval.ts; the import is erased at build time.

Whywiden reads seq, file, page and text, and sets lastPage on a joined passage.

/** The neighbours added stop here: 12 × 900, so the answer's context at most doubles. */export const WIDEN_CHARS = 10_800

The budget Module load

WhatWIDEN_CHARS is 10,800, the most neighbour text one call adds.

Why12 chunks of at most 900 characters are 10,800, so widening at most doubles the answer's context, and with it the input cost of the answer call.

widen()

function · lines 21–96View on GitHub

Adds each chosen chunk's neighbours under the budget and joins adjacent chunks into one passage.

Called by answering(): ASK 5

/** * `given` widened, in the reranker's order. A run of neighbouring chunks is one * passage, under the id of its first given chunk, so nothing is sent twice. A * chunk without `seq` (stored before the order was) is never widened, and is * never anyone's neighbour. */

The contract Never runs

WhatThe result keeps the reranker's order. A run of adjacent chunks is one passage, under the id of its first given chunk in that order, so no text is sent twice. A chunk without seq is never widened and is nobody's neighbour.

WhyChunks stored before seq existed have null there, so their place in the file is unknown.

export function widen(given: Chunk[], all: Chunk[]): Chunk[] {  // Every chunk of the demo, looked up by its file and its place in that file.  const bySeq = new Map<string, Chunk>()  for (const chunk of all) if (chunk.seq != null) bySeq.set(`${chunk.file}\u0000${chunk.seq}`, chunk)  // The chunk at a given place in a file, if there is one.  const at = (file: string, seq: number) => bySeq.get(`${file}\u0000${seq}`)

Index every chunk by file and place Query time

WhatbySeq maps "<file>\u0000<seq>" to the chunk, for every chunk of the demo account with a seq; at(file, seq) looks one up.

WhyOperating systems do not allow NUL in a file name, so the composite key cannot collide for a real upload, although the Worker does not reject a name that contains one. seq counts chunks across the whole file, so a neighbour may be on the next page.

  // Every chunk that goes in: the given ones always, then their neighbours under the budget.  // `taken` and `placed` are sets of Chunk objects, so `has` is by identity, not text: `given`  // holds the very objects `all` does (fuseKeywordAndVector and rerank pass them through unchanged).  const taken = new Set<Chunk>(given)  // One budget, in characters, shared by the whole call: not per chunk, not per side.  let added = 0

What goes in, and the shared budget Query time

Whattaken starts as the given chunks, and added counts neighbour characters for the whole call.

WhyThe given chunks are always sent and never count against the budget. taken is a Set of objects, which works because given holds the same objects that all holds.

  // In the reranker's order, so the best-ranked chunks get their neighbours first.  for (const chunk of given) {    // A chunk stored before the order existed has no known neighbours.    if (chunk.seq == null) continue

Best-ranked first Query time

WhatWalks the given chunks in the reranker's order, skipping any without seq.

WhyWhen the budget runs out, the chunks the reranker ranked highest have already had their neighbours.

    // One neighbour each side: the chunk just before and the chunk just after, in the same file.    for (const seq of [chunk.seq - 1, chunk.seq + 1]) {      const neighbour = at(chunk.file, seq)      // Skipped if there is none (the file's edge), it is already in, or it would overspend the budget.      if (neighbour === undefined || taken.has(neighbour) || added + neighbour.text.length > WIDEN_CHARS) continue

One neighbour each side Query time

WhatLooks at seq − 1 and seq + 1 in the same file, and skips a neighbour that does not exist (the file's edge), is already taken, or would push added past WIDEN_CHARS.

WhyThe skip uses continue, so a long neighbour that does not fit still leaves room for shorter ones later in the list.

      // Taken: it counts against the budget.      taken.add(neighbour)      added += neighbour.text.length    }  }

Take the neighbour Query time

WhatThe neighbour joins taken and its length is added to the budget.

WhyBeing in taken is what lets the run-building pass find it.

  // Each given chunk's run of taken neighbours, the first time one of its chunks is reached.  const placed = new Set<Chunk>()  // The passages that go back to the caller, in the reranker's order.  const passages: Chunk[] = []

The output: placed and passages Query time

Whatplaced tracks the chunks already sent inside a passage. passages is the result, in the reranker's order.

WhyTwo given chunks next to each other in the file must be sent once, as one passage.

  for (const chunk of given) {    // Already inside an earlier chunk's run: it went out there, once.    if (placed.has(chunk)) continue

Skip chunks already sent Query time

WhatWalks the given chunks again in order; one already inside an earlier run is skipped.

WhyIts text is in that earlier passage, under that passage's id.

    // The run starts as the chunk on its own.    const run = [chunk]    if (chunk.seq != null) {      // Walk outward each way while the next chunk was taken. A run grows past a chunk's own two      // neighbours only where given chunks lie close together in the file.      for (let seq = chunk.seq - 1, c = at(chunk.file, seq); c !== undefined && taken.has(c); c = at(chunk.file, --seq)) run.unshift(c)      for (let seq = chunk.seq + 1, c = at(chunk.file, seq); c !== undefined && taken.has(c); c = at(chunk.file, ++seq)) run.push(c)    }

Grow the run outward Query time

WhatStarting from the chunk, the loops prepend the chunk before while that chunk is taken, and append the chunk after while that chunk is taken.

Whytaken holds the given chunks and their neighbours, so a run can pass through several given chunks that lie close together in the file. A run stops at the first chunk that was not taken.

    // Every chunk in the run counts as sent, so none goes out twice.    for (const c of run) placed.add(c)

Mark the run sent Query time

WhatEvery chunk of the run goes into placed.

WhyA later given chunk inside this run is then skipped at line 63.

    // Nothing was added around it: the chunk goes as it is.    if (run.length === 1) {      passages.push(chunk)      continue    }

Nothing added: the chunk as it is Query time

WhatA run of one is pushed as the original Chunk object.

WhyIts id, page and text are unchanged, so its citation and source read exactly as without widening.

    // A run is one passage, under its given chunk's id, spanning the run's pages, the texts joined.    const pages = run.map((c) => c.page)    passages.push({      id: chunk.id,      file: chunk.file,      page: Math.min(...pages),      lastPage: Math.max(...pages),      text: run.map((c) => c.text).join('\n'),    })  }

A run becomes one passage Query time

WhatA new passage with the given chunk's id and file, page and lastPage from the lowest and highest page in the run, and the texts joined with newlines in file order.

WhyThe answer model can cite only the given chunk's id, because check.ts matches cited ids exactly against given, and a neighbour's own id would fail. The check looks for each figure of a sentence in the cited passage's text, which is now the joined text, so a figure that only the neighbour states still passes. answer() and the sources show "pages a–b" when lastPage is past page.

  return passages}

Return the passages Query time

WhatReturns the passages, at most as many as the given chunks.

WhyThey become given in answering() and are listed to the answer model at ASK 6.