# Groundwork > Connect sources, index them, ask with cited answers, and measure answers with evals. # Pipeline and adapters This page covers the ports a Groundwork pipeline is made of, the adapters available for each, how adapters are named and versioned, and the benchmark each port runs. ## Ports Every step in the pipeline is a port: a small interface in `src/core/ports.ts` that any number of adapters implement. Every model and every store is an adapter, so every model and store can be swapped by changing an id in the config. | Port | Interface | What it does | |---|---|---| | parse | `Parser` | Turns a file into text, page by page, with an optional per-page confidence | | transcribe | `Transcriber` | Turns audio into timed segments, optionally with speakers | | chunk | `Chunker` | Cuts text into overlapping pieces with character offsets | | embed | `Embedder` | Turns texts into vectors, as queries or as documents | | store | `StoreOpener` | Opens an `IndexStore` for keyword search, vector search and read-only SQL | | route | `Router` | Picks an answer path for a question, with a confidence and a reason | | rerank | `Reranker` | Reorders and trims search hits | | generate | `Generator` | Writes text from a prompt | `extract` is also a port name in `src/core/adapter.ts`, but the demo's extractor is a rule-based stage with no adapter registry yet. ## The adapter registry An adapter is one file under `src/adapters//`, exporting one `Adapter` (`src/core/adapter.ts`): ```ts type Adapter

= { id: string; // stable id used in configs, such as "local/bge-small" port: PortName; version: string; // bump when output changes for the same input local: boolean; // true when it runs on this machine and sends nothing out describe: string; // one line for listings and audit pages cost?: { usd: number; per: string }; impl: P; }; ``` Each port has a `registry.ts` that registers its adapters. `pick(registry, id)` returns the adapter, or an error that lists every known id. ```ts import { pick } from "./src/core/adapter.ts"; import { embedders } from "./src/adapters/embed/registry.ts"; const embedder = pick(embedders, "local/bge-small"); if (embedder.status === "ok") await embedder.data.impl.embed(["150 Hayes St"], "query"); ``` Python-backed adapters call a worker script in `scripts/` with `uv run --script`. Models used at question time (query embeddings, the reranker, the embedding router and the MLX models) stay loaded behind a localhost port through `scripts/resident.py`, shared by every process, and stop after 15 idle minutes. ## Adapter ids Ids name the provider and the model. These are registered today: | Port | Adapter ids | |---|---| | parse | `pymupdf`, `docling`, `docling/ocr`, `docling/ocrmac`, `docling/granite`, `tesseract`, `mlx/qwen2.5-vl-3b`, `ocr/routed`, `mistral/ocr` | | transcribe | `faster-whisper/tiny.en`, `faster-whisper/small.en`, `whisper/base.en` | | chunk | `builtin/words`, `chonkie/token`, `chonkie/sentence`, `chonkie/recursive`, `chonkie/semantic` | | embed | `local/bge-small`, `local/potion`, `ollama/nomic-embed-text` | | store | `store/sqlite-vec`, `store/sqlite-brute`, `store/pgvector` | | route | `rules/keywords`, `embed/centroid`, `mlx/qwen3-4b`, `claude/inline`, `cascade/centroid-mlx@0.3`, `cascade/centroid-claude@0.3` | | rerank | `none`, `cross-encoder/ms-marco-minilm-l6` | | generate | `mlx/qwen3-4b`, `mlx/qwen3-8b`, `ollama/qwen3-1.7b`, `claude/inline`, `anthropic/claude-haiku` | A cascade router runs a fast router first and hands the question to a slower one when the fast router's confidence is under the threshold in its id. `cascade/centroid-mlx@0.3` uses the embedding centroid, then Qwen3 4B. Adapters for paid services (`mistral/ocr`, `anthropic/claude-haiku`) exist but are off unless explicitly enabled. `claude/inline` runs through a local Claude subscription. ## Choosing adapters On the San Francisco demo, adapters are picked with command line options (see [Ask and search](/docs/ask)): ```sh deno task sf ingest --embed local/potion --store store/sqlite-vec deno task sf ask "Who raised the Hayes Street closure?" --embed local/potion --store store/sqlite-vec \ --path auto --router cascade/centroid-mlx@0.3 --rerank cross-encoder/ms-marco-minilm-l6 --model mlx/qwen3-8b ``` Ingest and ask with the same `--embed` and `--store` values. `--store builtin` (the default) keeps chunk search in the demo's own SQLite file. `store/pgvector` needs `scripts/pgvector.sh start` first. Videos take `--transcriber ` at ingest. The ingest chunk stage uses its own word-window chunker, read from `index.chunkSize` and `index.overlap`. The chunk adapters are benchmarked but not yet selectable at ingest. ## Versioning rules - Bump an adapter's `version` when its output changes for the same input, so audits can tell the runs apart. - Bump a stage's `version` when the stage's own logic changes. The stage name and version are the first part of its cache key. - The adapter id is part of the config the stage reads, so changing the id reruns that stage and the ones after it, and nothing before it. - Model ids belong in the config, including the provider's model version where there is one, so a silent model update counts as a change. ## Audit rows Adapter calls made while answering a question go through `audited` (`src/core/audit.ts`), which writes one ledger row per call: run id, port, adapter id and version, input and output hashes, time, cost and cache hit. Today the demo audits routing, reranking and generation. See the audit command in the [Quickstart](/docs/quickstart) and the planned [Audit](/docs/api/audit) resource. ## Benchmarks per port Each port has a general benchmark that runs before any customer data, on generated questions from a corpus or on small public sets. Every run writes `BenchResult` rows (`src/core/bench.ts`) to `tmp/bench/.json`, so all ports report into one table. | Task | Measures | |---|---| | `deno task bench:store` | Recall at 10 against exact search, query latency p50 and p95, ingest rate, size on disk | | `deno task bench:chunk` | Retrieval recall at 10 on synthetic questions per chunk set | | `deno task bench:embed` | Recall at 10 and MRR on synthetic question and passage pairs, texts per second | | `deno task bench:parse` | Character accuracy against born-digital text layers | | `deno task bench:ocr`, `bench:ocr-routing` | Character error rate on damaged and real scans | | `deno task bench:transcribe` | Word error rate on LibriVox clips against the book text | | `deno task bench:route`, `bench:cascade` | Accuracy against labeled best paths, and latency | | `deno task bench:rerank` | nDCG at 10 on the retrieval set | | `deno task bench:generate` | Citation validity and fact recall on the golden set | ## Current defaults Defaults hold until a customer's own evals say otherwise. From the first benchmark round: | Port | Default | |---|---| | store | `store/sqlite-vec` for one machine; `store/pgvector` past about 100,000 vectors | | chunk | `builtin/words` | | embed | `local/bge-small`; `local/potion` when speed matters | | parse | `pymupdf` for born-digital files | | transcribe | `faster-whisper/small.en` | | route | `cascade/centroid-mlx@0.3` | | rerank | `none` | | generate | `claude/inline`; `mlx/qwen3-8b` when nothing may leave the machine | The demo's store default is still `builtin`, its own SQLite file, rather than `store/sqlite-vec`. # Answer format This page describes the XML answer document, its elements, its Markdown form, and the citation check that runs on every answer. ## Two forms of one answer An answer comes back in two forms built from the same object: Markdown for people and chat, and an XML document that holds the same Markdown plus everything a product needs to render or check it. Prose is Markdown, citations are `[^id]` markers, and the things they point to are declared once as elements. The code is in `src/answer/xml.ts` and the spec is `specs/answer-xml.v0.md`. ## An example This is a real answer from the San Francisco demo, shortened. It came from: ```sh deno task sf ask "What is planned at 150 Hayes Street, and did it come up at the Board?" --path entities --answer --format xml ``` ```xml A permit filed on 2026-10-29 would convert the office building at 150 Hayes St into a 106-unit residential building [^s1]. At the 2026-10-20 Board of Supervisors meeting, 150 Hayes was named as one of four projects using the adaptive reuse program [^s2]. hayes st Table: permits permit number: 202610149441 ... Board of Supervisors, 2026-10-20 ... Table: businesses ... ``` ## Elements | Element | Required | Meaning | |---|---|---| | `answer` | Yes | Root. `id`, `path` (the answer path used), `config` (config hash), `run` (audit run id), `at` | | `body` | Yes | The answer in Markdown. `[^id]` cites a `source`; `media:id` in an image or link points at a `media` element | | `source` | One per marker | What a claim rests on. `kind` is `chunk`, `row`, `transcript`, `page`, `entity` or `web`. `href` is a stable source address. Optional `page`, `start` and `end` (seconds for audio, characters for text), and a short quoted excerpt as text | | `field` | No | A canonical field value the answer used, with the entity key, field name, the `source` it came from and a confidence | | `media` | No | An image, audio or video clip the answer refers to: `kind`, `src`, `alt`, optional `start` and `end` | | `entity` | No | A canonical entity the answer is about, so a product can link to it | | `refusal` | No | Present instead of claims when the answer declines. `reason` is `no-evidence`, `out-of-scope` or `rule` | ## How the prototype fills it `fromAnswer` turns an `AnswerData` object (see [Ask and search](/docs/ask)) into an answer document: - The answer model cites evidence by id, such as `[permits/175834582073]`. Each cited piece becomes a numbered `source` and its marker becomes `[^s1]`. A citation that matches no evidence keeps its id as the marker, so the check reports it. - A count, total or ranking cites the query that produced it, such as `[sql/permits-1]`. Each table query the agent runs is one piece of evidence holding its SQL and its rows, and the source panel shows it as a table. - The source `kind` comes from where the evidence came from: table rows are `row`, meetings and videos are `transcript`, PDFs are `page`, and anything else is `chunk`. - `href` is a `gw://` address. PDF pages add `#page=`, and videos link to the moment on YouTube. - Every canonical field of the entities the answer touched becomes a `field`, pointing at the source its value came from. - With no answer model set, the body is a list of the evidence, each item cited. - With no evidence at all, the answer includes ``. Some parts of the spec are not filled yet. The command line does not set `config`, `media` is always empty, `field` has no confidence, and refusals other than `no-evidence` are not produced. ## The Markdown form `renderMarkdown` produces the body followed by each cited source as a footnote, in the order first cited. Transcript sources show the moment and page sources show the page. For the example above: ```md A permit filed on 2026-10-29 would convert the office building at 150 Hayes St into a 106-unit residential building [^s1]. At the 2026-10-20 Board of Supervisors meeting, 150 Hayes was named as one of four projects using the adaptive reuse program [^s2]. [^s1]: Permit 202610149441 at 150 Hayes St: filed, gw://permits/175834582073 [^s2]: Board of Supervisors, 2026-10-20 at 1:35:50, gw://meetings/SFGTV_20261020_210000_Full_Board_of_Supervisors ``` Because the Markdown is derived from the same object, the two forms cannot disagree. The command line's default `--format md` prints a terminal view with evidence and trace rather than this footnoted form. ## Citation check `checkCitations` runs on every XML answer and returns: ```json { "ok": true, "markers": 2, "unresolved": [], "uncited": [], "badFields": [] } ``` | Field | Meaning | |---|---| | `ok` | True when every marker, field source and `media:` reference resolves | | `markers` | How many `[^id]` markers the body has | | `unresolved` | Markers with no matching source, and `media:` ids with no `media` element | | `uncited` | Sources nothing cites in the body or a field. Allowed, but flagged | | `badFields` | Fields that name a source that does not exist | This is the result for the example above. `s3` is cited only by a field, which counts as a use, so it does not appear in `uncited`. The check confirms that citations resolve. Whether each source supports the line that cites it is measured separately, by the generate benchmark (`deno task bench:generate`) and the citations row of the [Scorecard](/docs/scorecard). The spec's Check step plans a model-based support check and an audit ledger row for the result; neither is wired in yet. ## Parsing `parseAnswerXml` reads this format back into the same object, so a product or test can round-trip an answer. It reads one root with flat children and nothing else. ## In the hosted API The planned API returns this document for `format=xml`, and Markdown by default for chat. See [Ask](/docs/api/ask). The hosted API is in design. # API and MCP Ask your files from code over the API, or from an agent over MCP, with the key the demo gives you. The samples on this page name this site, so they work as you copy them. ## The API host `https://api.groundwork.computer` serves the API alone: web fetch and search, projects and keys, with [/openapi.json](https://api.groundwork.computer/openapi.json) and [/llms.txt](https://api.groundwork.computer/llms.txt). The same calls also work on this site. An id.orgsoft.org key, `om_sk_…`, opens all of it. Each call is charged to its account, from the Greenfield Pro allowance first and then purchased credit, and the reply says what it cost. Call it from your server: requests from a browser page are refused. ```sh curl -X POST https://api.groundwork.computer/v1/web/fetch \ -H "Authorization: Bearer $OM_KEY" -H "content-type: application/json" \ -d '{"url": "https://example.com"}' curl -X POST https://api.groundwork.computer/v1/web/search \ -H "Authorization: Bearer $OM_KEY" -H "content-type: application/json" \ -d '{"query": "retrieval evals", "limit": 5}' ``` | Endpoint | Body | Returns | |---|---|---| | `POST /v1/web/fetch` | `{ "url" }` | `url`, `title`, `text`, and `meta.charge_usd` | | `POST /v1/web/search` | `{ "query", "limit" }` | `results`, each with `title`, `url` and `snippet` | | `POST /v1/projects` | `{ "slug", "name" }` | The new project | | `POST /v1/keys` | `{ "project", "scopes" }` | A project key, shown once | | `POST /v1/projects/{project}/add` | `{ "text" }`, `{ "url" }` or `{ "file", "name" }` | The file added | | `POST /v1/projects/{project}/search` | `{ "query", "k" }` | `passages`, best first | | `POST /v1/projects/{project}/ask` | `{ "prompt" }` | `answer` with `[^s1]` markers, and `sources` | The id key works as its account's organization key, so the project calls below take it in place of `gwo_…`. ## Projects An app with clients of its own uses projects. Each project is isolated: its own files, index and build, and nothing in it is read by another project. Make one for each client. An organization key, `gwo_…`, makes projects and keys. It comes from us, is shown once, and belongs on your server. A project key, `gwp_…`, opens one project, to read (search and ask), write (add and build) or both. ```sh curl -X POST https:///v1/projects \ -H "Authorization: Bearer $GW_ORG_KEY" -H "content-type: application/json" \ -d '{"slug": "halvorsen-riley"}' curl -X POST https:///v1/keys \ -H "Authorization: Bearer $GW_ORG_KEY" -H "content-type: application/json" \ -d '{"project": "halvorsen-riley", "scopes": ["read", "write"]}' ``` Add text or files, build, then ask: ```sh curl -X POST https:///v1/projects/halvorsen-riley/add \ -H "Authorization: Bearer $GW_KEY" -H "content-type: application/json" \ -d '{"title": "1:1 with Dana", "text": "Riley Moreno: Before you start…"}' curl -X POST https:///v1/projects/halvorsen-riley/build -H "Authorization: Bearer $GW_KEY" curl -X POST https:///v1/projects/halvorsen-riley/ask \ -H "Authorization: Bearer $GW_KEY" -H "content-type: application/json" \ -d '{"prompt": "What are Riley'"'"'s growth edges in the meetings?", "format": "json"}' ``` `ask` takes a `prompt`, and optionally `instructions` for how the answer reads, `messages` for earlier turns, a `mode` of `chat`, `agent` or `auto`, and a `format` of `json` or `csv` with a `schema` or `columns`. Nothing is stored between calls: your app keeps the conversation. To rotate a key, make a new one, switch to it, then revoke the old one with `DELETE /v1/keys/{id}`. ## Try it with a session Start a session from code. It returns a key, shown once: ```sh curl -X POST https:///v1/sessions export GW_KEY=gwd_… ``` Or add files at [/demo/start](/demo/start), let them build, and choose **Make a key** in the Use step. The key opens only that session's files, and stops working when the session is deleted, after three idle hours. A new key from the page replaces the old one. Every call sends it as `Authorization: Bearer $GW_KEY`. Keep it in that environment variable rather than in code or a chat. ## Ask Ask from code with the API, or add the MCP server to an agent. ## Endpoints | Endpoint | Body | Returns | |---|---|---| | `POST /v1/sessions` | None, and no key | `key`, `expiresAt`, `limits` | | `GET /v1/build` | None | `state`, `built`, `steps`, `files` | | `POST /v1/ask` | `{ "question", "instructions", "thread" }` | `answer` in Markdown with `[^s1]` markers, `sources`, `run` | | `POST /v1/search` | `{ "query", "k" }` | `passages`, best first, with no model call | | `POST /v1/sources` | `{ "from" }`, a link or `notion`, `slack` or `drive` | `added`, or `wait` with a `signIn` link to open first | | `PUT /v1/files?name=` | The file's bytes | `added` | | `POST /mcp` | MCP over streamable HTTP | The `ask`, `search` and `add` tools | Search costs nothing and keeps working after the key's answers are used up. ## Add files and sources Adding a file or a source builds the index again on its own. `GET /v1/build` says when it is `done`, and the next question reads it. ```sh curl -X PUT "https:///v1/files?name=handbook.pdf" \ -H "Authorization: Bearer $GW_KEY" --data-binary @handbook.pdf curl -X POST https:///v1/sources \ -H "Authorization: Bearer $GW_KEY" \ -H "content-type: application/json" \ -d '{"from": "https://example.com/pricing"}' ``` A service you have not signed in to answers `wait` with a `signIn` link. Open it, then send the same call again. ## Shape the answer `instructions` say how the answer should read: a role to play, a length, a format. They are kept apart from the question and never change what counts as evidence. `thread` holds up to four earlier turns, so a follow-up is read in its conversation; reading it counts as one more answer. ```sh curl -X POST https:///v1/ask \ -H "Authorization: Bearer $GW_KEY" \ -H "content-type: application/json" \ -d '{"question": "And who approves it?", "instructions": "One sentence.", "thread": [{"question": "What does a large repair cost?", "answer": "Over 500 dollars."}]}' ``` ## MCP tools | Tool | Arguments | What it does | |---|---|---| | `ask` | `question` | Answers with citations to the page, row or moment | | `search` | `query`, `k` | Returns the best passages, with no model call | | `add` | `from` | Adds a link or a service by name, then rebuilds | The MCP tab under Ask has the command for Claude Code and the settings for any other MCP client. ## For agents - [/openapi.json](/openapi.json) describes every endpoint. - [/llms.txt](/llms.txt) lists the API with every guide. - Copy prompt beside the API and MCP tabs gives an agent these steps with this site's address filled in. # Ask and search This page covers how a question becomes an answer: the three answer paths, automatic routing, the options you can set, and what comes back. ## Answer paths Three answer paths share one setting, `query.path`. Each returns the same evidence budget (`query.topK`, 20 by default), the canonical fields of the entities it touched, and a written answer when an answer model is set. The code is in `src/query/paths.ts`. | Path | How it works | Best for | |---|---|---| | `search` | Hybrid keyword and vector search over every chunk, optional reranking, then an answer | Questions answered by passages in documents | | `agent` | A tool per source: SQL over tables, search over text, entity lookup. With a model, it plans its own calls for up to five steps. Without one, it runs SQL at every address the question names, then a search per source | Mixed sources, numbers from tables, multi-step questions | | `entities` | Links the question to canonical entities, follows the graph one hop, and searches only the records that mention them | Questions about a specific business, address or person | On the demo, a search-path question that counts or ranks, such as "How many paintings by Claude Monet are in the set?", also runs one query over the dataset's tables, since search sees only the closest twenty passages. Uploads and the art set work this way. From the command line, `--tables` does the same, so the art eval matches the demo: ```sh deno task sf eval --data tmp/art-demo --golden evals/art/golden.json --path search --model claude/inline --tables ``` With `query.prefetch` set to `context` (the default), the agent path starts with a hybrid search and a lookup of the entities the question names, both loaded into its first prompt, so many questions need no tool call. ## Automatic routing `--path auto` lets a router pick the path per question. The router is a route adapter, `cascade/centroid-mlx@0.3` by default: an embedding centroid classifier answers when its confidence is at least 0.3, and Qwen3 4B on MLX decides the rest. If the router fails or names an unknown path, the question falls back to `search`. The routing decision and its reason are added to the trace. On a held-out set of 60 questions across four domains, the local cascade picks the labeled best path 93% of the time. `cascade/centroid-claude@0.3` does slightly better when a model call off the machine is acceptable. See [Pipeline and adapters](/docs/adapters) for every router id. ## Asking from the command line ```sh deno task sf ask "Which businesses on Valencia Street had permit trouble?" --path auto --answer ``` | Option | Effect | |---|---| | `--path search\|agent\|entities\|auto` | The answer path, or `auto` to let the router pick. Default `search` | | `--answer` | Write an answer with `claude/inline` | | `--model ` | Answer model by id, such as `claude/inline` or `mlx/qwen3-8b` | | `--router ` | Route adapter for `--path auto`. Default `cascade/centroid-mlx@0.3` | | `--rerank ` | Rerank adapter. Default `none` | | `--embed ` | Embed adapter. Default `local/bge-small` | | `--store ` | Where chunk search lives: `builtin`, `store/sqlite-vec`, `store/sqlite-brute` or `store/pgvector` | | `--keyword-only` | BM25 alone, no vectors | | `--k ` | Evidence budget per answer. Default 20 | | `--prefetch none\|context` | Whether the agent path loads search hits and entities before its first turn | | `--format md\|xml\|json` | Terminal rendering (default), the XML answer, or the full answer object | | `--data

` | Data folder. Default `tmp/sf` | Ingest and ask with the same `--embed`, `--store` and `--keyword-only` values. Without `--answer` or `--model`, the answer model is `none`: Groundwork returns evidence and canonical fields with no generated text. ## What comes back Every path returns an `AnswerData` object (`src/query/types.ts`): ```ts type AnswerData = { path: "search" | "agent" | "entities"; question: string; evidence: Evidence[]; // retrieved chunks and rows, each with id, source, title, text, page or time, score, and how it was found entities: EntityCard[]; // canonical entities: key, type, fields, the record each field came from, mention count answer?: string; // present when an answer model is set trace: Step[]; // each tool call: tool, input, output, milliseconds modelCalls: number; ms: number; }; ``` The command line adds the audit run id. With `--format xml` the answer becomes an answer document with numbered sources and a citation check (see [Answer format](/docs/answer-format)). With `--format json` you get the object above plus `runId`. The `via` field on each piece of evidence says how it was found, such as `keyword`, `sql`, `search permits`, `prefetch` or `entity address.150-hayes-st`. Together with the trace, it shows why a source was in the context. ## Tracing an answer ```sh deno task gw audit ``` This prints every audited adapter call behind the answer, in order. See the [Quickstart](/docs/quickstart). ## Search on its own The `search` path without an answer model is the closest thing to a search endpoint in the prototype: run it without `--answer` and read the evidence list. ```sh deno task sf ask "outdoor dining on Valencia" --path search --format json ``` ## On the demo today Files uploaded to the demo can be asked over `POST /v1/ask` and searched over `POST /v1/search` with a key from get started, and the same two tools are served over MCP at `/mcp`. [Try your own files](/docs/your-files) has the requests. ## The planned hosted API The hosted API is in design and its shapes may change. It separates asking from searching: ```sh curl https://api.groundwork.dev/v1/projects/acme/ask \ -H "Authorization: Bearer $GW_KEY" \ -d '{ "question": "Which carriers raised dental premiums in 2025?" }' curl https://api.groundwork.dev/v1/projects/acme/search \ -H "Authorization: Bearer $GW_KEY" \ -d '{ "query": "termination clause", "topK": 10, "filter": { "tags": "contracts" } }' ``` ```ts const { answer, citations } = await gw.ask("Which carriers raised dental premiums in 2025?"); const hits = await gw.search("termination clause", { topK: 10, filter: { tags: "contracts" } }); ``` In the hosted product, which path runs is a project setting chosen per use case by evals, and the router can pick per question. See [Ask](/docs/api/ask), [Search](/docs/api/search) and [Entities](/docs/api/entities) in the API reference. # Concepts This page defines the terms used across the Groundwork docs and points at the code or spec behind each one. ## Projects A project is one body of data with its own sources, configuration, golden sets and scores. In the hosted design a project also scopes API keys (see [Projects and keys](/docs/projects-and-keys)). Locally, a project is a data folder: the San Francisco demo lives in `tmp/sf`, and every command takes `--data ` to point at another. ## Sources A source is anything Groundwork reads: a folder, a table, a set of transcripts, a YouTube channel, a bucket, a database. Each source belongs to one of two classes, set per source: - **Ingest.** Copied through the full pipeline and indexed. - **In place.** Queried live at answer time (SQL, Cypher or a federated vector search) and never re-embedded. It still emits catalog records so the answer agent knows what exists. **Promotion** moves a source from in place to ingest when evals show it helps. It is a switch on the source, not a rebuild. Only ingest sources exist in code today; in place and promotion are planned. See [Sources](/docs/sources). ## Records Every source emits the same shape, `IngestRecord` (`src/record.ts`): ```ts type IngestRecord = { id: string; // hash of connection id and native id, stable across syncs source: { kind: string; connection: string; nativeId: string; uri?: string; container?: string }; version: { hash: string; sourceVersion?: string; modifiedAt?: string; observedAt: string }; op: "upsert" | "delete"; content?: { mime: string; text?: string; blob?: string; bytes?: number; language?: string }; metadata: Record; tags: string[]; access?: { users?: string[]; groups?: string[]; public?: boolean }; links?: { type: string; target: string }[]; error?: { code: string; message: string }; }; ``` The id stays the same when a record changes. The version hash changes only when the content or metadata does, so an unchanged row keeps its hash across syncs and nothing downstream reruns. ## Stages and the cache key The pipeline is built from one primitive, the stage (`src/stage.ts`). A stage is a pure async function with a name, a version, and a `configOf` function that picks out only the config fields it reads. Its output is cached under: ``` @// ``` This has a few consequences: - A retry or a duplicate event finds its output already in the cache. - Changing a query setting such as `query.topK` reuses every index-time stage. - Changing the chunker reuses parsing and transcription. - Bumping a stage's version invalidates only that stage and what depends on it. `cached` wraps a stage with a blob store, `cachedEach` does the same item by item for batch stages such as embedding, and `pipe` chains stages left to right, stopping at the first result that is not ok. ## Adapters and ports Every pipeline step is a **port** with a small interface in `src/core/ports.ts`: parse, transcribe, chunk, embed, store, route, rerank and generate. An **adapter** is one implementation of a port, in one file, chosen by an id such as `local/bge-small` or `store/sqlite-vec`. The adapter id is part of the config a stage reads, so it lands in the cache key and swapping one reruns only what depends on it. See [Pipeline and adapters](/docs/adapters). ## Canonical entities and fields Extraction finds entities in records, and resolution groups mentions into one **canonical entity** per real thing, keyed `type.normalized-id` (for example `address.150-hayes-st`). Each entity keeps: - one canonical value per field, - every candidate value seen, with its provenance (the record, the source, the extractor that set it, and a time), - the records that mention it. Conflicts are kept, and the canonical value is picked by a rule. The demo's rule is `trusted-then-recent`: the most trusted source wins, then the most recent value. Entities are stored in xgraph2. ## Answers and citations An answer is the result of one question on one answer path. It holds the written answer (when an answer model is set), the evidence it rests on, the canonical entities it touched, a trace of the steps taken, the number of model calls and the time. Rendered as an answer document, each claim cites a declared source with a `[^id]` marker. See [Answer format](/docs/answer-format). ## Golden sets A golden set is a list of questions with what a good answer needs: the records, transcript moments or PDF pages that hold the evidence, and the facts the answer should state. The San Francisco set is `evals/sf/golden.json`. See [Evals and golden sets](/docs/evals). ## The scorecard The scorecard summarises evals and benchmarks as a grid: one row per dimension (retrieval, facts, answers, citations, and so on), one column per use case, each cell a traffic light against a stated threshold and each cell naming the file it came from. See [Scorecard](/docs/scorecard). ## The audit ledger and run ids Each question gets a run id. Adapter calls made for that question write a row to the audit ledger (`src/core/audit.ts`): run id, step, adapter id and version, input and output hashes, time, cost, whether it was a cache hit, and when it ran. `deno task gw audit ` prints the chain. The XML answer includes the run id in its `run` attribute, so any answer can be traced back to the adapters that produced it. # Evals and golden sets This page covers the golden set format, how answers are scored against it, the eval runner and its output files, and the sweeps that are planned on top. ## Golden sets A golden set is a JSON file of questions, each with the evidence a good answer needs and the facts it should state. The San Francisco set is `evals/sf/golden.json`, with 22 rows. A second set for video and PDF sources is `evals/sf/golden-media.json`. ```json { "name": "San Francisco mixed sources", "version": "2026-11-06", "asOf": "DataSF and Internet Archive pulls of 2026-11-06", "rows": [ { "id": "150-hayes-plan", "question": "What is planned at 150 Hayes Street, and did it come up at the Board of Supervisors?", "sources": ["meetings", "permits"], "gold": [ { "label": "permits", "table": "permits", "match": "all", "sql": "SELECT record_id AS id FROM t_permits WHERE permit_number = '202610149441'" }, { "label": "meeting", "meeting": "SFGTV_20261020_210000_Full_Board_of_Supervisors", "at": [5760], "match": "any" } ], "facts": [ { "claim": "Converts the office building to 106 homes", "terms": ["106"] }, { "claim": "Uses the adaptive reuse program", "terms": ["adaptive reuse"] }, { "claim": "Permit is filed, not issued", "terms": ["filed"] } ] } ] } ``` ## Row shape | Field | Meaning | |---|---| | `id` | Stable row id | | `question` | The question as a person would ask it | | `sources` | The sources a full answer draws on | | `gold` | One group per source the question needs | | `facts` | Claims a good answer states, each with terms that show it is present | A gold group takes one of four forms: - **Table rows**: `table` and `sql`. The SQL runs against the index before the eval, so the reference records always match the data the run sees. A query that returns nothing fails the run. - **Meeting moments**: `meeting` and `at`, in seconds from the start. - **Document moments or pages**: `doc` (such as `pdfs/bag041426_agenda`) with `at` or `pages`. - **A query over a table**: `query`, naming the table, such as `permits`. It is met by any query the answer runs over that table, for questions about a count, a total or a ranking that no single record holds. `match` is `all` when every item in the group should be retrieved, or `any` when one is enough. An `any` group can list alternatives in `or`, such as the same discussion as captions or as a page of the minutes. ## Scoring Scoring in `src/eval/score.ts` is mechanical, with no judge model. Each row gets: | Score | How it is computed | |---|---| | `recall` | For each gold group, the share of its items found in the evidence (or 1 or 0 for `any`), then the mean over groups. Each source counts equally | | `allSources` | True when every group has at least one item found | | `evidenceFacts` | The share of facts with any of their terms in the retrieved evidence and entity fields | | `answerFacts` | The share of facts with any of their terms in the written answer, when there is one | A transcript chunk covers a gold moment when it overlaps the minute starting at that moment. Terms are compared after case and accent folding. Each row also lists the facts it missed and the hits per group. ## Running an eval ```sh deno task sf eval deno task sf eval --path auto --answer deno task sf eval --keyword-only ``` | Option | Effect | |---|---| | `--path ` | Score one path. Default is `search`, `agent` and `entities` in turn | | `--answer`, `--model ` | Also write answers and score `answerFacts` | | `--golden ` | Another golden set, such as `evals/sf/golden-media.json`. Default `evals/sf/golden.json` | | `--about ""` | What the data is, given to the answer model in place of the San Francisco description | | `--keyword-only`, `--embed`, `--store`, `--router`, `--rerank`, `--prefetch`, `--k` | The same settings as `ask` | The runner (`src/eval/run.ts`) prints a line per row and path, then a summary table: | Path | Recall | All sources found | Facts in evidence | Facts in answer | Model calls | Mean time | |---|---|---|---|---|---|---| | agent | 83% | 73% | 83% | 91% | 72 | 10279 ms | ## Run files Each run is saved to `tmp/sf/evals/