Knowledge Retrieval (RAG)
How knowledge attached to an agent reaches the model, and how to tune it.
Data model
A knowledge base (
Knowledge) is one source: uploaded files (vector KB, indexed in Qdrant) or a graph (Neo4j).A knowledge repository groups knowledge bases. Agents are only ever granted whole repositories (
AgentRepository); at execution time svc-core expands them to member KBs and deduplicates.Per-grant overrides live in
AgentRepository.config(e.g.{"top_k": 10, "depth": 3}) and apply to every member KB.Per-agent pipeline overrides live in
Agent.config["retrieval"](see Configuration).
Flow
svc-core svc-ai
──────── ──────
agent chat ──▶ _load_agent_knowledge_bases() ExecuteRequest.spec.knowledge_bases
_load_agent_retrieval_config() ──▶ ExecuteRequest.spec.retrieval
│
▼
__knowledge_plan__ plan()
1 query planning (LLM / keywords)
2b document targeting
│ a lane per kind (the turn's mix),
▼ side by side with the web and tools
__<kind>_retrieval__ search()
2 graph retrieval (Neo4j) ─┐ entity names
3 hybrid vector retrieval ◀┘ seed lexical queries
dense + lexical → RRF
4 rerank (the lane's own judge) + relevance gate
5 neighbour-chunk expansion (overlap trimmed)
│
▼
__retrieval_join__ pack()
6 pack to token budget by role → [S#] ids
│
retrieval_context (Markdown) ─▶ skill nodes / synthesis
retrieval_citations (structured) ─▶ SSE `citations` frame
│
svc-core WS ◀── tokens, citations (document id, page, chunk span, snippet) ◀──┘
Plan, search, pack (26 October 2026)
RetrievalPipeline.run is three steps, which it composes over one lane holding every knowledge base:
plan(stages 1 and 2b) decides what to look for, once: the query set and literal terms, and the documents the request names (KnowledgePlan). Targeting reads the plan's terms, never the graph's, so a document is targeted once and a name no knowledge base holds is reported once.search(stages 2–5) runs one lane: its knowledge bases searched for the plan's queries and judged together, by one judge that is told only about them. Each is then read for its kind (a temporal window), the lane's own requested documents are added whole, and the leading passages are widened to their neighbours (LaneResult). It takes the lane's ownRetrievalConfig(candidates, judge slots).pack(stage 6) packs the lanes' passages and facts within one budget, cites and renders them, and adds up their counts. Errors stay in the order the stages ran (graph, targeting, vector), and a lane stage's timing is the longest lane's.
Composed over one lane, the steps are exactly the single pass before them. tests/knowledge/test_retrieval_lanes.py holds them to snapshots taken before the split (tests/knowledge/snapshots/): every message the planner and judge were sent and every field of the bundle, for domain-only knowledge with a graph, all three kinds at once, a requested whole document, and exclude with an offset. The lanes are the seam the per-category retrieval nodes are built on (Searched in lanes).
Direct search without running an agent:
POST /app/knowledge/{knowledge_id}/searchPOST /app/repositories/{repository_id}/search
Body: {"query": "...", "retrieval": {...overrides}, "ai_model_id": "<optional svc-ai model id>"}. Both proxy to svc-ai POST /knowledge/retrieve and return the same bundle an agent would receive: passages, graph_facts, citations, context_markdown, queries, skipped_kbs, timings_ms. Supplying ai_model_id enables LLM query planning and reranking; without it the deterministic stages still run.
Asking about a specific file
Files are stored under a sanitised name in MinIO (Annual Report 2024.pdf → Annual_Report_2024.pdf, with a short suffix on name collisions) while the index and the UI show the original name. Everything that touches files therefore goes through svc-ai/app/knowledge/documents.py, which:
lists a KB's documents from the index (original name, sanitised name, folder, pages, chunks) with a storage fallback for files not yet indexed;
resolves any spelling the user or model produces — original or sanitised name, different casing, missing extension, underscores vs. spaces, close misspellings — and reports "closest matches" on a miss;
returns a document's parsed text assembled from its indexed chunks (so PDF and Office files read correctly), falling back to raw storage only for plain-text formats.
On top of that, the pipeline's document targeting stage detects documents named in the question. Their passages are searched in a document-scoped pass, boosted above unscoped hits and never crowded out by the per-KB cap. Whole-document requests ("summarise X", "what is in X", or just the filename) include the document text itself, sized by full_document_share. Filename-like mentions that match nothing are rendered as NOT FOUND in the context so the agent says so instead of guessing.
The gate also enforces this deterministically: if the request names an attached knowledge base or a stored document, it is routed to internal retrieval even when the LLM router chose direct, external or tools. On most routes the check reads the request, its standalone form and the whole previous exchange, so "summarise it" after an answer that cited a file still finds that file. When triage chose the web alone, it reads only the person's own words: the request, triage's standalone query and their previous message. The agent's previous reply never counts there, because it names the agent's own sources (CHAINR Bot's ends "[1] 03-agents.md (CHAIN-R User Guide)").
Why a named file can always be found
Three independent sources are merged whenever a document is looked up, so discovery never depends on a single subsystem being healthy:
The document manifest — svc-core attaches its
KnowledgeDocumentrows (name, sanitised storage name, folder, MIME type,index_status,index_error,chunk_count) to every KB spec it sends to svc-ai. This is authoritative for what exists.The vector index — chunk counts and pages for indexed files.
The MinIO listing — fallback when the other two are empty.
Reading a file that is not indexed yet (or whose indexing failed) fetches the stored bytes and converts them on demand through docling, so read_document works seconds after upload and the answer states the indexing status instead of "not found". Indexing status is recorded by svc-core on the document row (pending → indexed / failed with the error) and is visible in list_documents output.
The only expected failure is a genuinely ambiguous name — the same file name in several attached knowledge bases — in which case read_document lists the candidates and asks for knowledge_base.
One embedding of each query (28 October 2026)
A turn embedded the same query once per knowledge base, per lane (every lane's queries start with the request), per corrective pass and per search_knowledge call: a plain waterfall-or-V-model question made 16 embedding calls for three texts. A run now carries an EmbeddingCache in its config (app/services/embedding_cache.py, set by AgentGraphBuilder.run_config as the source registry is), and Embedder.embed_many reads it: a text the run has embedded is not embedded again, and one another branch is embedding is waited for. Keyed by the embedder and the text; outside a run (indexing, a direct search) nothing changes. Pinned by tests/services/test_embedding_cache.py (side-by-side Send branches included).
Knowledge tools
Agents see one small, stable tool set regardless of how many knowledge bases are attached or what they are called:
| Tool | Arguments | Purpose |
|---|---|---|
read_document | document, knowledge_base?, offset? | One file by exact or approximate name, across all KBs, a part at a time: up to 12,000 characters from offset, ending at a paragraph, with "characters X–Y of N" and where the next part begins (28 October 2026; it returned up to 60,000 characters on every call, and run 4's DPIA question carried four ICO pages on every later round of its tool loop, 30,000 to 116,000 input tokens a round) |
list_documents | knowledge_base? | File names, folders, page/chunk counts, indexing status |
explore_graph | entity, knowledge_base?, depth? | Entities and relationships in graph KBs |
knowledge_base accepts a KB name or id (approximate names resolve) and is only needed to target one of several. A search_knowledge naming none searches what the turn's mix searches (all of the agent's knowledge when the mix searched none: a direct or web route), never one confirmed empty; knowledge bases that found nothing share one line ("No results above the relevance threshold in: …"), and a kind's note (dated, a method) appears only above results (28 October 2026). Run 1's a-dpia had searched all sixteen of its agent's knowledge bases, the dated news the mix left out included, and printed "No results" with a dated note for each. The earlier per-KB tools (search_<kb>, files_<kb>, explore_<kb>) derived their names from user-typed KB names, which made names long, unstable across renames and prone to collisions, and multiplied schema tokens per KB; they remain in the registry for compatibility but the graph no longer uses them.
The best passages in all (29 October 2026)
search_knowledge's top_k (default 6, at most 20) was the passages of each knowledge base, so an agent holding thirteen got up to 78 passages a call: 22–31k tokens a result, and a-patching in scenario run 7 read 1.1M input tokens ($0.38; run 6 $0.06). It is now the passages in all. Each knowledge base is searched as before, at the same time rather than one after another (rag.search_hits, at most its own top_k setting). The hits are then ranked together as one knowledge base's are (rag.best_overall): every hit's similarity (one embedder, so comparable across collections) and its keyword score, fused by rank with the same weights. The best top_k are kept and formatted per knowledge base (rag.format_hits), the one holding the best passage first. A knowledge base that matched only below them is named on one line ("Also matched, below the best passages above: …"), so the agent can search it alone. The retrieval record counts only the passages handed on. Pinned by tests/tools/test_knowledge_tools.py (TestTheBestPassagesInAll).
What a passage reads as (29 October 2026)
Pages are stored as Markdown with their links, and in run 7 58% of a legislation.gov.uk passage's characters were link targets ([S.I. 2026/82](https://www.legislation.gov.uk/id/uksi/2026/82) after every amendment note). A model paid for them in every search, judge and answer call, and could cite none of them, since a passage's citation is its page. app/knowledge/passage_text.py readable keeps each link's words and drops its address. Images keep theirs, because a document may show a picture the knowledge holds. Code is left as written. It applies wherever a model reads stored knowledge: search results (rag._format_search_results), the pipeline's passages and neighbour windows (joined as stored, then read, so a link cut at a chunk's end does not stop the overlap matching), and read_document. Stored pages, the crawl's links and deep citations are unchanged.
The crawl also kept page navigation: "Skip to main content" and headings with no words, which was all the NCSC's overview page held. passage_text.tidy_lines drops them at extraction (web_extract.extract_markdown, both of its paths) for pages crawled from now on, and readable drops them from what is already stored. Pinned by tests/knowledge/test_passage_text.py.
The query planner knows the date (29 October 2026)
The planner was given no date, and for c-ai-rules' "this month" it wrote "June 2024". Its user message now opens with Today: … (retrieval._planner_request, prompts.today()), in the request so the system prompt stays the same all day. Its prompt says to leave dates, years and periods out of the queries, naming a year only when the question names that year. How recent results are is applied separately (the temporal lane's window), and a date in a query matched the UK GDPR's dated amendment footnotes rather than the subject. One lane and a query set per lane alike; the lane snapshots fix the date (tests/knowledge/test_retrieval_lanes.py).
Configuration (RetrievalConfig)
| Key | Default | Meaning |
|---|---|---|
multi_query / max_queries | true / 4 | LLM query expansion and the cap on total queries (original included) |
top_k | 8 | Final passages per KB (per-KB config.top_k overrides) |
candidate_k | 24 | Candidates per query per search leg |
score_threshold | the embedder's floor | Dense similarity floor (cosine). Unset, it is the active embedder's standard floor (0.35 for OpenAI, a provisional 0.25 for Titan): a score means different things in different vector spaces. |
lexical | true | Keyword leg via Qdrant full-text index |
rrf_k | 60 | Reciprocal-rank-fusion constant |
neighbour_window | 1 | ±N adjacent chunks merged around each hit |
max_passages_per_document | 4 | Diversity cap |
graph_depth / graph_entity_limit | 2 / 10 | Neo4j walk depth and entity cap (per-KB config.depth overrides depth) |
graph_seeds_vector_queries | true | Entity names from graph hits become lexical queries |
rerank / rerank_candidates | true / 30 | LLM listwise reranking of the fused head |
min_relevance | 0.4 | The relevance judge's verdict, applied: a passage it rates below this (0 unrelated, 0.5 helpful background, 1 answers it) is dropped, and so is the unjudged tail behind its head. A passage from a document the request names always stays. 0 keeps everything. Applies only when a judge ran (rerank with a model). See Relevance |
max_context_tokens | 12000 | Budget for the rendered evidence block. It was 6,000 until 28 October 2026, which packed two to five of the 12–16 passages the lanes handed on; agents then made up for it with knowledge searches of their own |
always_retrieve | true | Gate always includes internal retrieval when KBs are attached, unless a successful triage chose web only (respect_triage_web_route). See Which turns search the knowledge and Agent Graph |
respect_triage_web_route | true | A successful triage's web-only route (retrieve · external) stands on an agent with knowledge, when the inventory it read was complete and the person's own words name no attached document, knowledge base or file. Off, always_retrieve adds internal retrieval to every route, as before October 2026 |
respect_triage_direct_route | true | A successful triage's direct stands on the same terms, and not when the request names a period an agent with dated knowledge holds. Off, always_retrieve forces the search, as before 28 October 2026 |
agentic_when_thin | true | In hybrid mode, run the agentic gap-fill pass only when the pipeline's evidence falls short: nothing found, a search failed, a document the request names matched nothing, or a named document the evidence holds nothing from. No passage count: min_sufficient_passages is gone, and a stored value is ignored |
agentic_max_iterations | 4 | The agentic pass's model rounds (1–10), plus one call to write up when they run out. A round may run several searches, so the pass is asked for up to this many targeted queries and to stop when the task is covered or a search adds nothing new. It was the worker default of 10 |
document_targeting | true | Detect named documents; scoped search + boost + whole-document inclusion |
max_targeted_documents | 3 | Cap on named documents handled per query |
full_document_share | 0.6 | Share of the token budget a whole-document request may use for the document text |
Example agent config:
{
"retrieval": {
"mode": "pipeline",
"top_k": 6,
"neighbour_window": 2,
"max_context_tokens": 4000
}
}
Ingestion
Upload (svc-core) stores the file in MinIO, creates the KnowledgeDocument row with index_status: pending, and queues a background task that runs parse (docling-serve's POST /v1/convert/file, whose content is under document in its reply, with the DoclingDocument's pages preferred to its markdown; or local for plain text; see web-knowledge.md) → chunk (512 tokens, 64 overlap) → embed via svc-ai (POST /knowledge/embed) → upsert into Qdrant. svc-core has no LLM egress, so embedding must go through svc-ai; this also pins ingestion and retrieval to one embedding model, the one svc-ai's inference backend uses (app/services/embeddings.py: Titan Text Embeddings V2 in London on Bedrock, text-embedding-3-small on direct).
Each collection records the model that built it in Qdrant's collection metadata, and each document the model that embedded it (document_metadata.embedding). Indexing into a collection another model built is refused before anything is spent, and search skips such a collection's dense leg rather than compare vectors from two models. When the model changes, the knowledge_reindex scheduled job rebuilds every collection from what is stored (scheduler.md).
The outcome is written back to the row: indexed with chunk_count, or failed with index_error prefixed by the stage that broke (parse:, embed:, index:). Documents uploaded before status tracking are resolved lazily when listed (indexed or not_indexed, by counting their chunks in Qdrant).
Reindexing re-reads the stored file and runs the same task:
POST /app/knowledge/{id}/documents/{doc_id}/reindexPOST /app/knowledge/{id}/reindex?only_failed=true|false
The knowledge base page shows each document's status (with the error on hover for failures) and offers Reindex per document and Reindex failed / Reindex all for the knowledge base.
Website sources are ingested by their crawl rather than by upload: each page is a document whose newest snapshot is chunked from its extracted markdown and indexed the same way, replacing the previous snapshot's chunks. See web-knowledge.md.
Ingestion requirements
Hybrid search relies on payload indexes that svc-core/app/util/qdrant_client.ensure_collection creates idempotently on every indexing run: a full-text index on text and keyword/integer indexes on document_id, original_filename, source_id and chunk_index. Collections created before this change are upgraded the next time a document is indexed into them; until then the lexical leg still works via a slower full scan. Each point also stores folder_path, which is surfaced in citations.
Semantic search and the inventory on qdrant-client 1.17
Until October 2026 every agent's knowledge was searched by keyword only, and routing was told every vector knowledge base was empty. svc-ai pins qdrant-client 1.17, which has neither AsyncQdrantClient.search nor CollectionInfo.vectors_count. Each failure was caught and logged:
The dense leg raised
AttributeErroron every request, after paying for the query's embedding, and returned nothing. Only the keyword leg answered, so a passage was found because it shared a word with the request.The routing inventory (
_build_kb_metadata, read by triage, planning and the query planner) counted 0 chunks for every vector knowledge base. It then said "Empty collection — no documents indexed yet. Do not query this KB." and listed no documents. CHAINR Bot's user guide was among them.
Now:
One nearest-neighbour call. Every nearest-neighbour query goes through
rag._nearest(query_points).Failures are reported, not hidden. A semantic leg that cannot run says so in
RetrievalBundle.degraded: it failed, or its collection awaits a re-index. That is apart fromerrors, because the keyword leg still answered. A keyword-only hit in a tool search reads(keyword match), notrelevance 0.000.The count comes from
points_count. A collection that cannot be read within 3 s is unknown (vector_count: None), never reported as 0. It is asked again after 20 s, rather than waited on by every turn. A collection never created (svc-core creates one on a knowledge base's first upload or crawl) holds 0. Its searches return nothing without embedding the query or reporting a failure.The inventory names documents from svc-core's manifest and the index scan (
documents.list_documents, the listing the gate already makes). It reads every knowledge base at once, since it sits on the path to each turn's first model call. It says "Empty — do not query" only of a knowledge base confirmed empty. It returns whether it is complete (GraphState.kb_inventory_complete, on the gate's trace frame), which is False when a count, a listing or a graph schema could not be read.
tests/services/test_qdrant_contract.py holds every client call in rag.py to the installed client in three ways: an AST check, the response models' fields, and a round trip through the real client in local in-memory mode. The other Qdrant tests use a client double specced on AsyncQdrantClient (tests/services/qdrant_fakes.py), so a removed method fails there too. A bare AsyncMock() had answered search all along.
Joining chunks back together
The chunker carries the last 64 tokens of each chunk into the next. A neighbour window (retrieval._expand_group) and a whole document's text (documents._assemble) are both joined by documents.join_chunks, which drops that repeat. It is found as the shortest exact match of at least 24 characters between the end of one chunk and the start of the next, capped at 1,200, and only between consecutive chunk indexes. In repetitive text, such as a table's identical rows, a coincidental match then leaves a little text repeated, where the longest match would delete real rows. Chunks with no overlap are joined by a newline.
Every boundary used to repeat about 300 characters: 8–12% of a merged window, counted against the context budget. On the real user guide (34 chunks, 52,000 characters) the old join repeated about 17% of the text; the new one reconstructs it exactly.
Which turns search the knowledge
Every substantive turn of an agent with knowledge searches it (always_retrieve), with two exceptions: a turn a successful triage sent to the web alone (respect_triage_web_route, on by default, 18 October 2026), and one it judged the knowledge has nothing to do with (respect_triage_direct_route, 28 October 2026; below). Asked "whats in the news", CHAINR Bot searched its guide whatever triage had chosen (the trace could not say what that was), and answered from the guide's paragraph on the built-in News repository.
A web-only triage (retrieve · external) stands only when all of these hold:
Triage answered. A failed triage's fallback never routes web-only on an agent with knowledge (
_fallback_routereturnsinternalorboth).The inventory it read was complete and not empty (
kb_inventory_complete). One that could not be read in full may have hidden what bears on the request.The person's own words name no attached document, knowledge base or file. Only the request, triage's standalone query and the person's previous message count, never the agent's previous reply.
Every other route (tools, internal, both, any + combination) still gains internal retrieval, and a named document still forces it. On a plain agent, such as CHAINR Bot, a kept web-only route becomes direct: the agent searches the web itself, so no knowledge retrieval runs. On a skill-graph agent, __external_retrieval__ runs alone. Turning the setting off restores the earlier behaviour exactly.
Triage is told to judge a knowledge base by what it is for, its description, and not by a document or section whose name shares a word with the request (prompts.GATE_KB_PURPOSE_RULE). The honest inventory (above) names the guide's 04-knowledge.md, which describes the News repository, and without that sentence it could turn a news question into retrieve_both. How well gpt-oss follows it is not measured live.
The gate's trace frame says what triage chose and each change the gate made (result.triage; see Agent Graph). Pinned by tests/agents/test_triage_web_route.py, tests/agents/test_routing_policy.py and tests/agents/test_news_turn_replay.py.
A known limit: a plain agent still holds search_knowledge on a web-only turn. Only its prompt keeps it from searching knowledge that has nothing to do with the request.
A direct triage stands (28 October 2026)
Asked "Suggest a quick vegetarian dinner", a compliance agent searched its law and security knowledge anyway; asked "How should we prioritise 40 feature requests?", a law-only agent had 120 passages judged and kept none. Both turns were then filed as questions the knowledge could not answer, so the unanswered recommendation offered to add knowledge on recipes.
Triage's direct now stands (_direct_route_hold) when triage answered, the inventory it read was complete, and the person's words name no knowledge base, repository or document. It also stands aside when the request names a period and the agent holds dated knowledge. The gate's frame says "kept: triage judged the knowledge does not bear on the request". Pinned by tests/agents/test_routing_policy.py (TestADirectTriage).
A repository named is its sources named. svc-core sends each knowledge base's repository names (KnowledgeBaseSpec.repositories, from the agent's grants), and the mention check and _named_knowledge_bases match them (_naming). "According to the Security guidance repository, what are the NCSC's 10 Steps?" had named nothing, because only a source's own name counted.
Knowledge that holds nothing yet (28 October 2026)
The first scenario run began before any web built-in had been crawled, and every turn searched them anyway. The lanes found nothing. The join's own pass searched again and wrote what it made of that as the evidence ("no indexed documents… [S1, S2]"), and the agent answered from it. Now:
The gate confirms which hold nothing (
graph._confirmed_empty, intoGraphState.empty_kb_ids): a collection whose count is exactly 0 (rag.collection_metadataconfirms an approximate 0 with an exact count). One whose count could not be read is not empty.The mix leaves them out (
knowledge.mix.decide(empty=…), reasonmix.EMPTY, "nothing indexed yet"), deciding over the rest as if the agent held only those. With all of it empty, the turn searches no knowledge (plan modenone), runs no judge and no agentic pass.search_knowledgeskips them (make_knowledge_tools(empty=…)), and says "X: This knowledge base has nothing indexed yet." when asked for one by name. Its description does not change, so the cached tool block holds.A request naming empty knowledge (a knowledge base, or a repository all of whose sources are empty) carries a
<knowledge_search>note: it could not be searched, so the agent answers from what it knows and says the answer is not from it (graph._named_empty). Asked about "the Security guidance repository" before it was crawled, the agent had refused to answer.
Pinned by tests/agents/test_empty_knowledge_turns.py (through the real graph), tests/knowledge/test_mix.py (TestEmptyKnowledge), tests/tools/test_knowledge_tools.py and tests/services/test_qdrant_contract.py.
An agent that searches only when triage says so (October 2026)
always_retrieve is on by default: retrieve, then let the relevance judge drop what does not bear (CRAG, Self-RAG). For CHAINR Bot it was the wrong default. Its one knowledge base is the CHAIN-R user guide, for questions about CHAIN-R, and with the setting on every request but a web-only one searched it — "write a poem" included. On "render pdf of different climbing knots":
triage reasoned to its output cap (16,384 tokens, 42 s) and was discarded;
the fallback route searched the guide;
the judge rated its "Documents and PDFs" section 0.50, so it was kept and put in front of the agent.
What changed:
CHAINR Bot's retrieval config turns
always_retrieveoff (svc-coreCHAINR_BOT.config). Triage reads what the guide is for, so a platform question still routesretrieve·internal(the inventory's bias rule), and anything else staysdirector goes to the web. User agents keep retrieve-then-judge.A failed triage does not assume the knowledge either. With
always_retrieveoff,_fallback_route(text, has_kbs, always=False)routes as for an agent without knowledge: the web for a time-sensitive request,directotherwise. A plain agent still hassearch_knowledgeand web search. A named knowledge base or document still forces retrieval.Triage fails fast. Its call is capped at 4,096 output tokens (
_CLASSIFICATION_MAX_TOKENS; a healthy triage used about 1,850), so a runaway fails in seconds, and nothing asks again (see Agent Graph).What the answer is made into is not its subject. Triage (
GATE_KB_PURPOSE_RULE) and the relevance judge are told that a PDF, a document, a chart or a table is not what the request is about: "a PDF of climbing knots" is about climbing knots, and a passage on making PDFs is unrelated.
Pinned by tests/agents/test_triage_node.py (through the real graph and the stream), tests/agents/test_fatal_errors.py (_fallback_route) and svc-core tests/test_system_resources.py.
A document the person attached is not knowledge (24 October 2026)
svc-core used to paste a chat's documents into the person's message. The gate's file-mention check read <source>report.pdf</source> as the person naming a file of the knowledge base, forced a guide search with the whole report as its query, and the packed evidence said "'report.pdf' — NOT FOUND … tell the user this file is not available". It said the same of manifest.json, a name only the report mentioned. Since the attachments work, a turn's documents travel beside the words, and retrieval treats them as the agent's own material:
Triage reads a manifest of them (names, sizes, a preview, never a body) and routes a request about them
direct. The knowledge default does not override that (_attachment_route_hold), and a failed triage answers from them.An attached document's name is no knowledge mention, and neither is a file name that appears only inside one (
find_mentioned_documents(exclude=, elsewhere=), throughDocumentTargeter.detect). Neither is searched for, and neither is reported NOT FOUND. A knowledge base file named beside an attachment is still searched.The request's echo is capped in the packed evidence: "Retrieved for" at 300 characters, at most six search queries of 200 (
ECHO_*). The query internal retrieval plans with is cut at 2,000 characters.read_documentgiven an attached document's name reads that document, unless the call names a knowledge base.
See Attachments.
Retrieval by category
A knowledge base arrives with the category of the repositories it was granted through (KnowledgeBaseSpec.category; see knowledge). app/knowledge/categories.py decides what each category changes, one Behaviour class each, so neither the pipeline nor the graph branches on a category's name. An older svc-core that sends none, or a value this copy does not know, is read as domain.
| Domain | Temporal | Reasoning | |
|---|---|---|---|
| Candidates per search | candidate_k | twice that | candidate_k |
| The relevance judge is told | its description | that it is dated, so recency is weighed apart | that it is a framework, rated for whether its method applies |
| After the judge | as it is | kept to a window, weighed for recency | as it is |
| Packed | as the evidence | as the evidence | apart, with up to 30% of max_context_tokens |
| The answering node reads it | <knowledge> | <knowledge>, under "Dated evidence — newest first" | <frameworks>, before <knowledge> |
| Its answer remembered | yes | no: the episode keeps the question | yes |
Domain is unchanged. Knowledge that is all domain reads exactly what it read before categories existed: the same inventory, the same judge brief, the same evidence, word for word. tests/knowledge/test_categories.py pins this, so CHAINR Bot, whose only knowledge is its guide, is unaffected.
What triage decides
The gate records a RetrievalTurn in state.context["knowledge_turn"], from which it decides the turn's mix (below):
complexity: triage's grade of the request. None when triage failed, and then nothing is ruled out. A request for what something is, says or means (a definition, a clause, the difference between two named things) issimplehowever weighty its subject (prompts.TASK_COMPLEXITY).named: the knowledge bases the request names (_named_knowledge_bases, the mention check's whole-word match).live: triage judged that the request needs current information (_needs_live_data).window_days: how recent the request wants dated knowledge to be. Only an agent with temporal knowledge is asked, byDatedTriageProfile(_RecencyCue.time_window:TIME_WINDOWS, a day being two). Every other agent's triage schema, and its cached prompt, are unchanged. The person's words decide (categories.turn_window, 28 October 2026):a period they name (
named_window: today, this week, the last two weeks, the past three months, since September) is the window, the narrowest that reaches back that far;words that only ask for what is recent ("latest", "recently") keep triage's window;
with neither, triage's window is dropped.
Each change is listed among the gate's adjustments. On "What has the NCSC warned about in the last two weeks?" triage gave no window, the mix read a lookup, and the NCSC's own news went unsearched. A vendor's "99% of phishing emails" claim had come back with two days.
liveneeds the words too (_needs_live_data(…, text), 28 October 2026): triage's own web route counts alone, but a web tool it names counts only when the person's words read as time-sensitive (_LIVE_DATA_RE, or a named period). Asked how to prioritise a backlog, triage had named all sixteen of the agent's tools, web search among them, and the request read as current. Words that ask about now count alone, though: since run 4 (same day) the words are split (_ABOUT_NOW_RE: latest, recent, this month, news, what's new…;_MAYBE_NOW_RE: current, prices, update…), and only the second kind needs a web tool beside it. "What's new in UK AI regulation this month?" had read as a lookup when triage named onlysearch_knowledge, and was answered from statute text.A web-led request that works a problem through keeps its method (the mix's
workedmodifier): "given recent advisories, what should we patch first, and how should we decide?" now searches Reasoning beside Temporal.web_led: when a request about what is current goes to the web alone and the web-only route stands, the gate still sends it to internal retrieval for its temporal knowledge (retrieve · both, recorded in the gate frame's adjustments). A plain agent then searches the web itself, as before. A turn checkpointed before the mix said this asonly: ["temporal"], whichRetrievalTurn.readstill reads.
The mix: which kinds an input searches (26 October 2026)
app/knowledge/mix.py decides, from the turn alone and never a model, which kinds of knowledge a request searches and in what role:
primary: the evidence the answer rests on;
supporting: evidence beside it;
method: a framework to apply (Reasoning).
The first matching row of ROLES is the input's profile:
| Profile | When | Domain | Temporal | Reasoning |
|---|---|---|---|---|
current_web | about what is current, sent to the web (web_led) | — | primary | — |
analysis_current | live, and moderate or complex | supporting | primary | method |
current | live, simple | supporting | primary | — |
analysis | moderate or complex | primary | — | method |
lookup | simple | primary | — | — |
Then the modifiers:
named: a knowledge base the request names is searched, that one, as method for Reasoning and supporting otherwise;
window: a period named, though nothing current was asked, turns Temporal on as supporting;
promoted: if no evidence lane leads, the first held of Domain, then Temporal, becomes primary;
single_kind: an agent holding one kind always searches it, at its configuration's own values. Domain-only knowledge (CHAINR Bot) is therefore searched exactly as before, whatever the request;
economy: the Economy cost profile leaves supporting lanes out (
PipelineEffort.supporting_lanes).
A kind the agent holds that the turn leaves out is recorded with why (LEFT_OUT, fixed reasons only).
How each role is sized. Each lane runs at its role's size (Searched in lanes):
| Role | Candidates | Judge slots | Queries | Share of the budget |
|---|---|---|---|---|
| supporting | half | half | 2 | 30% of the evidence share |
| method | half | a third | 2 | its kind's budget_share, reserved |
Where it is recorded. The gate decides the mix once the route is final and writes state.context["knowledge_mix"] (Mix.wire: the profile, modifiers, lanes, what was left out, and the signals, never the person's words, since the batch response returns the context). The gate's frame carries it as knowledge_mix. The knowledge nodes search what the mix lists (mix.searched), a lane per kind. The turn's report gains profile, and each source its role. An unsearched turn's report still records the profile. svc-core keeps both on the retrieval record (knowledge_turns.profile, knowledge_retrievals.role, migration 115), so the mix can be measured over a workspace's answers, and the decision record's Steps name each lane with its role and counts.
Searched in lanes (26 October 2026)
Each kind of knowledge a turn's mix runs is searched by a node of its own, side by side with the others, the web and the tools, and every branch meets once before the answer:
__planning__ → __knowledge_plan__ ─┬─ __domain_retrieval__ ─┐
├─ __temporal_retrieval__ ─┤
├─ __reasoning_retrieval__ ─┼─▶ __retrieval_join__
├─ __external_retrieval__ ─┤ (deferred: once)
└─ __tool_retrieval__ ─┘
__knowledge_plan__reads the turn's mix and plans the search once (RetrievalPipeline.plan) over the knowledge bases the mix searches: with two or more lanes, one call writes each lane its own queries (A query set per lane); with one, theQueryPlanone search always made._knowledge_plan_routerthen sends a lane per kind and, on a first pass, the web and the tools the route also asked for: every branch one node deep, so they run in one superstep. Inagenticmode it plans nothing and sends no lane: the join runs the tool loop.A lane (
__<kind>_retrieval__) searches its own knowledge bases with its own queries (RetrievalPipeline.search), judged by its own relevance judge, which is told only about them, at its role's size: its candidates, judge slots (which also cap each knowledge base's hits) and how many of the queries it runs. A big Domain repository no longer takes the judge slots a Temporal or Reasoning one needed. A lane whose search fails records it (LaneResult.failure) and the others go on; when every lane fails, the turn's search failed, as one search failing did.__retrieval_join__packs the lanes within one budget (RetrievalPipeline.pack): a method lane reserves its kind's share; two evidence lanes split the rest by their shares (70 / 30), what one leaves unused goes to the other, the leading one first, and caps and duplicates are counted across them; the leading lane cites first, so on a turn about what is current the dated evidence comes before the reference material. One evidence lane packs as one lane always did. Then everything one retrieval step did: the turn's marks, its record, and inhybridmode the agentic pass when the evidence falls short. Only the join writesretrieval_context— the knowledge, then the web's section, then the tools', whichever finished first — and the branches' staged fields (knowledge_plan,domain_lane…,web_context,tool_context) are cleared there.
Knowledge of one kind is searched exactly as before. One lane, at the configuration's own values: the planner and its judge are sent the same messages, once each, and the same evidence is packed (tests/agents/test_knowledge_lanes_turns.py). That is CHAINR Bot.
What a turn costs. One planner call (writing every lane's queries), and a judge call per lane that runs, concurrently:
| Turn | Before | After |
|---|---|---|
| Domain + Temporal, a lookup | 1 + 1 (30 shared slots) | 1 + 1 (Domain only) |
| Domain + Temporal, about what is current | 1 + 1 | 1 + 2 (30 + 15 slots) |
| Domain + Reasoning, an analysis | 1 + 1 | 1 + 2 (30 + 10) |
| All three, complex and current | 1 + 1 | 1 + 3 (30 / 15 / 10) |
| Corrective pass | 1 + 1 | 1 + a judge per evidence lane |
Each pass adds two supersteps (the plan and the join). On a turn that searches the knowledge and the web, the web starts after the planner call.
A query set per lane (26 October 2026)
One planner call writes each lane its own queries, so dated material is searched for what changed and frameworks for a method, not for the words of the request. The schema asks for exactly the kinds that run (retrieval.lane_plan_schema), one of four fixed ModelOutputs built from one mixin a kind, and never for a lane that will not run:
| Kinds that run | Schema | Fields |
|---|---|---|
| Domain + Reasoning | ReferenceMethodQueryPlan | reference_queries, method_queries |
| Temporal + Reasoning | DatedMethodQueryPlan | dated_queries, method_queries |
| all three | LaneQueryPlan | all three |
Each also has entity_hints, the literal terms every lane matches. Each field's description is its kind's Behaviour.query_note: reference material for what the request asks; dated material for what changed (updates, announcements, revised guidance), with dates left out because the turn's window is applied apart; a method or framework that applies, never the request's facts. The prompt is the planner's own plus one paragraph that each field's queries are for its kind, and it says each field's count (the lane's max_queries from the mix, less the question).
Each lane's set (KnowledgePlan.lane_queries) starts with the question and keeps to its count; queries is all of them, the question once, and is what the evidence header names. A call that fails leaves every lane the question alone and records planner_failure. One lane plans on QueryPlan with the planner's prompt unchanged, so CHAINR Bot's planner is sent exactly what it was. The calls keep purpose="retrieval.query_planner". The plan's frame lists each lane's own queries, and so does each lane's.
The trace. The plan's frame names each lane, its role, knowledge bases and queries; a lane's says what it found, showed its judge, ruled out, left out of the window and handed on (counts, never a passage); the join's carries the evidence as before, with lanes (each lane's budget, use, passages packed and budget taken over). Every node_start and node_end says when it ran (t_ms, from the stream's start), and node_start its pass (pass). The graph plan's retrieval stage is a fork, its branches (a lane per kind the agent holds, the web, the tools) and a join.
How fe-core draws it (components/chat/ExecutionPipeline, 26 October 2026). The retrieval chip on the rail lists the branches of its latest pass, a dot for each one's state and its role in the mix, and its caption is wall clock. Opened, the stage shows each pass: the mix (MixNote: the profile, the signals, each lane's role, share and reason, what was left out and why), the plan's lanes and their queries, a row per branch with its funnel (LaneFunnel: queries → found → judged → ruled out → out of window → handed on → packed) and a bar for when it ran within the pass, then the join with its packing table. util/pipelineUtils.ts reads a stage by pass then by branch (buildFlows); a stage's time is its wall clock (stageWallClock: first start to last end; on a stored trace without times, the plan, the longest branch and the join, never their sum), and so is the header's (runWallClock). "N passes" counts revisions only — the "×2 attempts" that internal ∥ external read as is gone — and a parallel stage fails only when its join, or every branch, failed; otherwise it is Partial (degraded). The gate's knowledge_mix tells the rail which lanes will run before they do. Every system node is named once, objects/systemNodes.ts, pinned to svc-ai's graph by a test.
Temporal: dated knowledge
Temporal.adjust runs after the relevance judge:
The window. It is triage's
time_window, or else the source's ownmax_age_days, which the crawl already holds it to. A passage outside it is left out (RetrievalBundle.out_of_window), unless it comes from a document the person named.Recency. A dated passage keeps
0.6 + 0.4 × 0.5^(age / 14 days)of its score: relevance leads, and among the relevant the newest comes first. An undated one keeps 0.6.Dates. A passage is dated by its
publisheddate, else by when its page was stored (fetched_at).
The evidence lists dated passages after the rest under "Dated evidence — newest first", with the day they are read as of. A passage with no date says "date unknown". search_knowledge shows the same dates, newest first, under categories.DATED_RESULTS_LINE.
The filter runs in Python on the wider candidate pool. Qdrant has no date index on these collections, and a pre-filter in the query is a follow-up, to be measured first.
Reasoning: frameworks
A framework is a method to apply, not a fact to cite. Its passages:
are packed apart (
RetrievalBundle.frameworks_markdown), with up toReasoning.budget_shareof the context budget plus whatever the evidence left (the lane frame'sspilled_in), and cited after the evidence. An agent of methods only packs the whole budget; until 28 October 2026 it had the share alone, and packed two of the sixteen frameworks it found;reach the answering node, synthesis and the quality check as
<frameworks>in<request_context>, before<knowledge>, never in the cached system message. Which one the agent applies, if any, is its choice: the quality check judges only whether a method it uses is applied correctly;are left out of the hybrid agentic pass, which fills gaps in the evidence. Frameworks alone keep the turn in pipeline mode.
A graph knowledge base follows its category for whether it is searched, but its facts are always rendered as evidence.
Relevance
Searching then judging beats routing by knowledge base names, which guesses (CRAG, Self-RAG). That holds only if the judging happens. Until October 2026 it did not:
The judge's verdict only reordered passages. The reranker's rating was blended 70/30 with the search rank, and nothing was dropped. The top search hit for "what is in the news" was CHAINR Bot's user guide page on the built-in News repository, matched by the word news. It was rated 0, kept 0.3 of a score, and was packed, cited and shown as the answer's source. A lone hit was never judged at all. Now the rating is applied (
relevance_gate,min_relevance), and every passage is judged, one included.The judge is told what relevance is not. A passage that only shares a word or a topic name with the question, such as documentation of a feature called the same thing as the question's subject, is unrelated, unless the question is about that feature.
Nothing relevant ends the search. When the judge rules out everything the search found (
RetrievalBundle.judged_out), the knowledge does not cover the request:the hybrid agentic pass does not search it again (it used to, found the same things, and the agent cited them);
the quality check's gap-fill does not send the turn back to it;
the answering agent is told its knowledge bases hold nothing for the request (
<knowledge_search>), so it neither cites nor searches them.
A search that found nothing still gets its agentic pass: a reformulated query may find what the first missed.
Evidence is framed as candidates. The
<knowledge>block says to use and cite only the passages that bear on the request. The evidence header and the knowledge-tool guidance used to say to answer from it and cite it ("Only state facts supported by this evidence") whatever it held.
Pinned by tests/knowledge/test_retrieval.py (TestRelevanceGate), tests/agents/test_knowledge_retrieval_nodes.py (TestNothingRelevant) and tests/agents/test_irrelevant_knowledge.py, through the real graph.
What the judge is told, and when it fails
That was not enough. On gpt-oss-120b the judge rated the same guide paragraph 1.0 for "whats in the news", and the gate kept it, as built. A judge reply cut off at its token cap had also been salvaged as a judge that rated nothing, so the gate stood aside in silence. Since 18 October 2026:
The judge sees what was searched. Its request lists each searched knowledge base's name and description (
retrieval._knowledge_brief, the first 300 characters of each), and its prompt says to judge a passage against what that knowledge is for. A question about something outside it is not answered by a passage that documents a page or feature named like its subject.Failures are reported, not hidden.
RetrievalBundle.planner_failureandjudge_failuresit besidedegradedand apart fromerrors(which means retrieval itself failed, and sends a hybrid turn to the agentic pass). A failed query planner falls back to the passthrough plan, as before. The internal retrieval node's trace frame carriesresult.report(planner_failure,judge_failure,degraded,judged_out) whenever one of them has something to say, and the node logs a WARNING.GraphState.retrieval_reportholds the same for the turn; a failure stays reported even when a corrective pass's judge worked (_merge_reports). fe-core draws the failures as cautions andjudged_outneutrally. These had reached the logs only.A failed judge fails open, visibly. The judge has failed when it raised (a reply cut off that does not parse whole included) or rated no passage. Every passage is then kept without a rating, so the relevance gate does not apply. Each passage's header reads
relevance unjudged(a requested document's aside), and the<knowledge>block of the answering agent, and of synthesis on a skill graph, says: "Retrieved for this request, but these passages were not checked for relevance; use and cite only those that bear on the request." Failing closed would strip a knowledge-grounded agent of all its evidence over a judge's hiccup, and it would then say its knowledge holds nothing. A judge that rated only some passages has not failed: the unrated ones go, as before. The quality check is not told the evidence was unjudged.The evidence header shows the judge's own rating (
relevance 0.87). It readsrelevance unjudgedonly when the judge failed for the run, and never on a document the person named (a targeted passage or a FULL DOCUMENT), which is in the evidence whatever its rating. Otherwise, as withrerankoff, it shows no relevance. It used to show the blend the passages are ordered by (0.7 × rating + 0.3 × search rank), which read as a rating whether or not a judge had seen the passage.The planner and judge have their own output caps. In an agent's graph the query planner runs with at most 4,096 output tokens and the judge with 8,192 (
graph._retrieval_step_llm), on the first pass and on corrective ones, on the same model as before. They had run at the system budget, raised towards 16,384. A reasoning model (gpt-oss-120b) ran each to it: about 38 s and 17k output tokens, twice in one turn. The judge gets more room because a cut-off judge leaves the turn unjudged, where a cut-off planner only loses its alternative queries. A structured reply cut off at a cap is read whole (safe_json.loads_exact) or not at all, never salvaged. Knowledge and repository search (svc-core) give their one model 8,192 for both steps. See Cost Monitoring.
Enough evidence, and the agentic pass
One relevant passage is enough. In hybrid mode the agentic gap-fill pass runs only when the pipeline found nothing, a search failed, a document the request names matched nothing, or a named document is one the evidence holds nothing from (graph._bundle_sufficient). It used to want three passages, so most turns paid for a tool loop that searched the same knowledge again. The pass is bounded by agentic_max_iterations (default 4, was 10). NODE_RETRIEVAL no longer asks for an exhaustive search ("Never stop after a single call", "at least 3 targeted queries" are gone). Fewer passes may find less where one passage is found and the answer needs more; the benchmark is what measures it.
What the pass hands on is what its tools found, never its own words (28 October 2026). It used to end with a structured summary of its findings, which became the evidence: asked about the NCSC's news while the feed held nothing, it wrote "no indexed documents… [S1, S2]", ids that named nothing, and the agent answered that no warnings had been issued. Now (graph._pass_findings):
The evidence is its tools' results that found something — a search with results, a document read, a graph walked; never a listing, "No results" or "No document named …" — under "## Additional findings", each with its own
Cite as: [S#].NODE_RETRIEVALasks for one line, not a summary, and the task's "Synthesise…" step is gone.Nothing found reads as nothing relevant: no evidence,
KNOWLEDGE_NOT_RELEVANT_KEY, so the agent neither cites the knowledge nor searches it again.No knowledge tools, no pass. It used to "summarise the task" alone and hand that on.
Not streamed (
graph._unstreamed_config,reply_formats.UNSTREAMED_TAG): the pass's text, and the web and tool workers', had streamed into the chat ahead of the answer.Its tool calls are stored (
AgentGraphBuilder._tool_call_recorder, also the web and tool workers'), so the decision record's Tool calls and Web sources list them; it had said "No tool was called" of a turn whose only searches were the pass's.
Pinned by tests/agents/test_knowledge_retrieval_nodes.py (TestHybridMode, TestTheRetrievalWorkers).
Corrective retrieval
A failed quality check sends the turn back to the knowledge for its gaps (retry_retrieval, CRAG) only when all of these hold (graph._knowledge_can_fill_gaps):
No web tool answered this run (
source_ledger.web_answered: aweb_searchorurl_fetchresult that names a page). An error report, a search that matched nothing and one past its call limit do not count. This is checked first.Knowledge bases are attached, and the check named gaps.
The judge did not rule out everything (
KNOWLEDGE_NOT_RELEVANT_KEY).This turn's knowledge search handed something on (
KNOWLEDGE_SEARCHED_KEYinstate.context).retrieval_contextcannot say so, because it also holds the web and tool retrieval nodes' sections.The turn searched evidence: a gap is a missing fact, so only the evidence lanes (primary and supporting) search for it, and an agent whose only knowledge is frameworks gets no corrective pass. The frameworks were searched again and thrown away before the lanes.
Otherwise the agent revises with its own tools. The trade-off: an agent with knowledge and web search whose answer came from the web gets no corrective pass over its knowledge, even when the gap could be there. It can still search its knowledge when it revises.
What the evidence already holds is not offered again. Every pipeline passage citation carries chunk_span, the chunks its text holds after neighbour expansion ([0, n−1] for a whole document; null without chunk provenance or expansion). A corrective pass excludes the spans already cited (retrieval.cited_spans, each evidence lane's RetrievalPipeline.search(exclude=…)):
a candidate inside a cited span is dropped before the judge sees it;
a neighbour's window stops short of cited chunks;
a passage that still covers cited chunks (a whole document) is dropped after expansion.
When every hit is cited already, the gap-fill is empty and the judge is not called. Graph facts carry no span, so one can still be packed again under a new id.
When the gap-fill finds nothing, the agent is told the details "are not in the knowledge bases beyond the evidence already given; that says nothing about whether they can be found elsewhere." It used to be told to "state plainly that these details are not available", which had it call unavailable what its own tools could find.
Citations
Every source has an id, and CHAIN-R writes the Sources block (19 October 2026)
CHAINR Bot on gpt-oss-120b answered "whats in the news" with [1] and [2] after its headlines and no Sources section, and the chat said "Sources the answer cites: 0". The response standard had asked for numbered web markers and a model-written Sources section, nothing credits a bare number, and nothing wrote the section when the model did not. Now:
Every source a run's models see carries an id from one per-run registry (
app/util/source_registry.py), carried in the run config (configurable["__chainr_sources"], set byAgentGraphBuilder.run_configfor batch, stream and resume). It is read withsource_registry.current()in every node,Sendbranch, tool and executor thread, and allocation is locked. A ContextVar set inside the streaming generator would belong to whichever task advanced it; the__key keeps it out of checkpoint metadata.One id per source: a page by its URL, so a search hit, its fetch and a knowledge base's snapshot of that page share one; a knowledge base's document by its id; a graph entity by name. A document's passages share its id, and the passage's page and chunk stay on the citation.
Shown where the model reads it: a packed passage is headed
#### [S3](ContextPacker.select). Aweb_searchblock, aurl_fetchpage, aread_documentresult and eachexplore_graphsection open withCite as: [S3], kept when a long result is abridged block by block. Asearch_knowledgepassage is labelled[S3] file p.2 (relevance …)in place of[1]. Knowledge trailers carry each source'scitation_id, and the ledger's parsers read the ids into each citation. Outside a run (a tool called on its own) nothing changes.A resumed run seeds the registry from its checkpointed citations, so ids carry on.
The model cites by id and writes no Sources section (
RESPONSE_FORMATTING_STANDARDS, the retrieval workers' prompts, the built-in workers' and report skills' prompts). A deep citation is the source's id plus an inline link to the original._retrieval_evidenceheadings are no longer numbered ("### web_search result"), since a number reads as a marker.A marker that names no source goes back once (
answer_sources.check_markers). A number not tied to a source, or an id never handed out, setsEvaluatorVerdict.citation_problemsafter a model check ran. The agent revises with a note listing the ids it was given and saying to change only the markers and not search again. Corrective retrieval ignores citation problems, and a skipped or unavailable check never sends one back.On the verdict that ships the answer (
graph._final_verdict, shared with the router),answer_sources.finalise:normalises the markers;
takes out a citation section the model wrote, but only when it ends the answer and every entry names a run source by id, URL or name. Its numbers then map to those sources exactly, so a reading list that is the answer stays;
escapes every other bare number (
\[2\]);renumbers
[S#]to[1],[2]… by first use, a group becoming one marker each, and drops an id never handed out;appends
**Sources**with one line per cited source before any trailing render fences:- [1] [Title](<url>) — Publisher · 2026-10-19, a document- [2] 03-agents.md — CHAIN-R User Guide, and a deep citation— via [Listing](<url>). Titles are escaped and only http(s) is linked.
Nothing happens when the run handed out no ids, when the answer is a typed output, or when it is JSON whole. It is idempotent.
What the chat shows is what the block lists: the done frame's and the batch response's
cited_citationsare the finalised sources in order, each with itsmarker(answer_sources.delivered_citations). Every retrieved citation the answer cites is stamped with its marker too, for a skill run's record. svc-core storesmarkerinmeta.cited_sources, unredacted. fe-core numbers its cards by it, and its preview renumbers[S#]by first use as the server will.Documents too:
render_documentrenumbers a body that cites ids and builds itssourceslist from them (answer_sources.renumber_document); a document citing none keeps its own list.History, memory and a pipeline's next step read the answer plain (
answer_sources.plain): no block and no markers, since their ids name sources a later turn was never shown.
Pinned by:
tests/util/test_source_registry.py: shared ids, threads, propagation through a real graph withSendand a sync tool, checkpoint metadata, the tools' lines and the knowledge search;tests/agents/test_answer_sources.py: every finaliser case;tests/agents/test_news_sources_replay.py: the incident through the real graph — bare numbers sent back with the ids, the delivered block, andcited_citationswith markers.
What every citation carries
Every passage and graph fact carries its source's id (S1, S2, …) in the rendered context and in the structured citation list (tool: "retrieval" / "retrieval_graph", kb_id, document_id, page_number, chunk_index, chunk_span, snippet, score). A passage from a website page also carries url, its title and fetched_at, and its evidence header says page as of <date> — a page snapshot can go stale in a way an uploaded file does not. Tool-derived citations (web search, the knowledge tools in agentic mode) are appended after them with contiguous indexes, each with its source's citation_id within a run.
Every citation has a kind
Every citation svc-ai sends — the stream's citations frames, the done frame's citations and cited_citations, and ExecuteResponse.citations / cited_citations — carries kind, read from its tool by one table keyed by exact tool name (source_ledger.TOOL_KINDS):
| Tool | kind |
|---|---|
search_knowledge, query_knowledge_base, retrieval (pipeline passages) | knowledge |
explore_graph, query_knowledge_graph, retrieval_graph (graph facts) | graph |
read_document | document |
| any other tool | other |
list_documents lists names, not content, and is no source. No prefix counts: a tool merely named search_*, explore_* or files_* used to read as a knowledge search. One per-tool parser table (source_ledger.CITATION_PARSERS) reads every tool's sources, for the batch path, the stream, the quality check's ledger and web_answered, and only tool results are read, never a node's own reply. url_fetch pages now reach the streamed citations too; the stream path had no branch for them. search_knowledge and explore_graph end their result in one combined trailer of {source, kb_name}, read from the last marker (app/util/source_trailers.py). A search over several knowledge bases used to write one trailer per section, and the reader then cited nothing.
Known limits: POST /knowledge/retrieve citations carry no kind, nor does GraphState.retrieval_citations.
What a chat shows is what the answer cites
The citations frames stream every passage as it is retrieved, before any answer is written. svc-ai's done frame also carries cited_citations (source_ledger.cited_citations), and the batch path's ExecuteResponse does too. A citation counts as cited only on exact evidence that the answer names it:
its pipeline id,
[S3]: inline anywhere (glued to a word or another id too:agent[S1],[S1][S2]), as a Sources entry's marker, or written in an entry's text;its URL, linked or written anywhere in the answer outside code (scheme,
www., fragment and trailing slash aside);its title, source or file name, or their stems without an extension ("Employee Handbook", "03-agents"; never a web page's title), as whole words in a Sources entry. Names compare case-insensitively, any run of punctuation as one space, so gpt-oss's "03‑agents" matches.
Never by a number alone, and never by the knowledge base's name, which names every passage of it. (This reading is the fallback for an answer that was not finalised; a finalised answer's sources are the finaliser's, above.) The run numbers its citations in the order it retrieved them, so [1] beside a web headline had credited the run's first passage, a user guide page, with the headline. An answer with numbered markers and no id, URL or name now shows no sources. Each page or document is shown once: an id credits its own passage, and a URL or name the first passage of a page or document no id named. A document is its URL, else its knowledge base and document id: a README.md in two knowledge bases is two.
A resumed turn's sources include those from before its pause. A turn paused mid-answer (ask_user, an approval gate after retrieval) resumes as a new stream, which saw only what came after the pause: the answer's [S1] credited nothing, and svc-core stored that. The resumed stream now starts from the checkpoint's completed nodes' passages and tool results (graph_based._citations_before_pause). A node the pause cut short runs again and streams its own.
Markers are normalised first (source_ledger.normalise_citation_markers). gpt-oss writes 【1】:
【n】,[n]and〔n〕, with ASCII or fullwidth digits and an optionalS, become[n]/[Sn], spaced from a word or marker they were glued to (agent [S1],[S1] [S2]);gpt-oss's references into its tool output, cursor references (
【3†L1-L5】) and browsing ids (【turn0search3】), are removed;every other
【…】is text and stays: Chinese and Japanese use them for headings, labels and dates;code spans and fences are left alone, and it is idempotent.
It runs on the quality check's draft (so the stored answer is normalised on every outcome, a skipped check included), on the done frame's and the batch response's output, and before the sources are read. Streamed tokens are not normalised; fe-core draws the wide markers as the same chips (processCitations). Direct model chat is not normalised.
The quality check matches an entry by its id first (source_ledger._match, the evaluator's <citation_check>). An entry marked [S3] is that passage, and an id the run never handed out is unmatched, whatever the entry names: every such entry names its knowledge base, and that name had matched the knowledge base's first passage, so an invented [S9] … (CHAIN-R User Guide) read as verified. Without an id, a document's name is tried before a knowledge base's.
Sources sections are read as models write them (parse_sources_section): a heading alone on its line (Source(s), Reference(s) or Citation(s), with optional bold, #, a count such as "(5)" or a colon), then list-shaped entries ([1] …, [S2] …, 1. …, any bullet, marked or not, and a line that is itself a link). Prose before the first entry is skipped, and a line that is not list-shaped ends the section. An inline "Sources: …" line lists its own entries. gpt-oss's drafts used to read as having no Sources section.
The response standard (RESPONSE_FORMATTING_STANDARDS, every answering node and synthesis) asks for exactly what is credited: every fact marked with the id its source was shown with ([S2]), never a number, and no Sources section — CHAIN-R writes it. Until 19 October 2026 it asked for numbered web markers and a model-written section, which an answer without the section turned into "0 sources".
Stored on the answer
svc-core forwards the list as a final citations frame (on_sources), which replaces the streamed list in fe-core (util/citations.nextCitations). It also stores it on the assistant message as meta.cited_sources, on both chat paths: the stream from the done frame, the batch prompt from ExecuteResponse.cited_citations. No migration is needed, since meta is JSON.
A projection (
transformers.cited_sources_meta,CITED_SOURCE_KEYS): index, kind, tool, title, source, url, kbname, citationid, documentid, pagenumber, published, author, attribution, licenceurl, fetchedat, links, via and collection, each only when set. Never the passage text (snippet), score orchunk_span: the message is not a copy of the knowledge base. About 0.3 KB a source.Redacted by the turn's Output rules (
RulePass.redact), so a value aredact_piirule hid in the answer is hidden in a source's title or URL behind the same placeholder. Only the fields a person reads are (title, source, url, kbname, collection, author, attribution, licenceurl, links and via): a detector can read a UUID's digits as a phone number or a card, which would corrupt an id and protect nothing.[]when the answer cites nothing, so a reloaded chat shows no sources rather than everything the turn retrieved. Absent on blocked, stopped and errored turns and on those stored before 18 October 2026, where fe-core falls back to its session cache — keyed by the stored message's id. Keyed by position, a blocked turn (which advances none) had shown the next answer's sources.
A reloaded chat (util/citations.storedCitations) and Activity's Sources the answer cites panel read it, grouped by kind. That panel replaced "Grounding Sources · fully grounded", which claimed grounding from any search_* call that returned anything, ignoring the web and the quality check. A turn stored without the key shows "Tools queried" instead, with no claim about which tools the answer used.
Redacted on the way out, too. svc-ai's StreamGuard redacts the done frame's citations and cited_citations for a redact_pii Output rule, as it does any streamed citations frame. svc-core forwards cited_citations to the browser before its own output rules run, so an address in a cited title had reached the page unredacted. The answer itself is still judged by audit_done_frame.
A skill run's record keeps every citation (citations), as a record of what the run read.
Extending
All stages are strategy classes in svc-ai/app/knowledge/retrieval.py (QueryPlanner, Reranker, VectorKBRetriever, GraphKBRetriever, ContextPacker). Swap one by constructing RetrievalPipeline(cfg, planner, reranker, vector_retriever, graph_retriever, packer); RetrievalPipeline.from_config wires the defaults.