WeKnora/internal/modelcontext/README.md

139 lines
7.7 KiB
Markdown
Raw Normal View History

# Model context boundary
`modelcontext.Registry` is the only application-facing boundary for values
that are shortened before an LLM call and restored afterwards. The whole
codec lives in this one package:
| File | Role |
| --- | --- |
| `registry.go` | `Registry` facade — the only type request lifecycles use |
| `handle_table.go` | `handleTable[M]`, the generic bidirectional primitive behind every handle space |
| `sources.go` | source handles (`cN`/`dN`/`bN`/`wN`) and the tool-argument codec |
| `citations.go` | protocol prompts, `<ref/>` → `<kb/>`/`<web/>` expansion, citation stream expander |
| `model_output.go` | compact source-centric renderings of tool results |
| `resources.go` | durable-resource handles (`res://NNNN`) |
| `stream.go` | `streamHold` suffix-hold primitive and every streaming decoder |
| `tool_policy.go` | the single policy layer: per-tool key contracts + `sourceKeySpaces` dispatch |
| `mcp.go` | MCP bridge routing handles (`msN`/`mtN`), definition projection and envelope codec |
| `mcp_sources.go` | bounded citation sidecar for HTTP(S) links in successful MCP results |
| `handles.go` | exported `HandleTable` for invocation-local spaces (`iN`, `ref-N`, `c000`) |
refactor(modelcontext): consolidate source_refs parsing, fixed data_analysis table, and identifier leak report (#3372) * refactor(wiki): consolidate source_refs parsing and resolution source_refs entries ("uuid" or "uuid|title") were parsed by ten independent implementations that disagreed on whitespace handling, on whether a model-supplied title could be trusted, and on how a leading pipe was treated. The scope-enforced and legacy agent resolvers also duplicated the lookup and the routing step looked every document up a second time. - types.ParseWikiSourceRef / FormatWikiSourceRef / WikiSourceRefMatchesKnowledge are now the only readers and writer of the format. - resolveWikiSourceDocuments replaces resolveAuthorizedSourceRefs, resolveSourceRefs and wikiKnowledgeBasesForSourceRefs: one lookup per document, titles always rebuilt from server data, dedupe by canonical ID, unknown documents fail closed in every mode. - removeSourceRef now matches padded or titled refs of a deleted document. * refactor(data_analysis): expose the selected document as a fixed table name The tool required the document ID inside the SQL text and blindly string-replaced it with the physical DuckDB table name, which forced the model-context codec to rewrite handles inside quoted SQL and let the UUID-derived k_<uuid> table name reach the model through stored schema summaries. The document is now selected only by knowledge_id. Every query runs on a dedicated connection where "dataset" is a temporary view over the physical table (DuckDB temporary objects are connection-local, so concurrent sessions stay isolated). The physical name remains accepted for internal callers; any other table fails validation with an error naming the table the model should use. Schema summaries, the schema tool, the analyst prompt and the tool schema all name the same table, so data_analysis.sql no longer carries source handles and its text codec policy is removed. * feat(modelcontext): report raw identifiers that survive encoding Text-level compaction exists because raw UUIDs reach model context through producers the registry never sees: error strings, slugs, results of unknown shape. Retiring it requires knowing where those producers are. Registry.LeakedIdentifiers scans an encoded message list for UUID-shaped values in every application-composed field (user messages are skipped), classifies each as registered (codec missed a rewrite) or unregistered (producer emitted a raw ID), and SummarizeLeaks renders one line per field. The agent engine and the three RAG pipeline call sites log the report as a warning after EncodeMessages. * fix(chat_pipeline): align RAG data analysis with the fixed table contract The RAG data-analysis plugin still asked the planning model to fill in knowledge_id and to write SQL from a prompt that exposed the raw knowledge UUID, then passed the model's JSON straight to Execute. Under the new data_analysis contract a query that names anything but the dataset table is rejected, and the plugin logged that rejection at error level and moved on, so the analysis vanished without any signal. A "no analysis needed" plan took the same error path. The pipeline now owns document selection: the model returns only needs_analysis and sql, the prompt names the dataset table and never shows the knowledge ID or physical table, and the plugin builds the tool input itself. A rejected query is fed back to the model once for repair; a query that still fails is reported through pipelineWarn with the SQL and the tool error, and "not needed" is logged as such instead of as a failure. Covered by unit tests with a scripted model and executor: not-needed, pipeline-owned knowledge_id, one-shot repair, persistent failure surfaced, unparseable plan rejected.
2026-09-17 14:08:16 +00:00
| `leaks.go` | `LeakedIdentifiers` report of raw UUIDs that survive `EncodeMessages`, logged at every model-call site |
## Identity rules
- Durable application identities: UUIDs, Wiki slugs, URLs, and
`resource://...` references.
- Request-local model handles: `cN`, `dN`, `bN`, `wN`, `msN`, `mtN`, and `res://NNNN`.
- Tool-private request handles: `iN` for Wiki issues.
- Ingest-call handles: `cNNN` and `ref-N`, allocated with `HandleTable`.
- Temporary handles are decoded before tool execution, persistence, or UI
delivery. They are never accepted as durable authorization or routing data.
## Request lifecycle
1. Create one `Registry` for the complete request or Agent execution.
2. Register structured source identities as they enter the context.
For Agent tools, use `EncodeTools` to project MCP routing enums and source summaries.
3. Call `EncodeMessages` immediately before the model call.
4. Decode tool calls through `DecodeToolCalls` before parsing or execution.
5. Decode complete responses with `DecodeResponse`, or streaming text with one
`StreamDecoder` per response channel.
Unknown handle-shaped values in declared tool fields are rejected before tool
execution. The same per-tool policy is applied when historical assistant tool
calls and tool results are replayed, so handles neither disappear nor drift to
new numbers across Agent rounds.
The registry owns codec ordering. Resource references are encoded before
source IDs so a Wiki slug such as `summary/<knowledge-id>` cannot be corrupted
into `summary/d1`.
Source addressability is separate from citation eligibility. Use
`RegisterContextChunk` for bound-KB directory entries. Replayed citations,
legacy tool history, and tool arguments also register navigation handles only.
`ModelToolResultForTool` and explicitly supplied retrieval results authorize
citations for the current execution; rereading a historical source promotes the
same handle without renumbering it. Both complete and streaming decoders drop
references that have not been backed by current evidence.
## Observability
refactor(modelcontext): consolidate source_refs parsing, fixed data_analysis table, and identifier leak report (#3372) * refactor(wiki): consolidate source_refs parsing and resolution source_refs entries ("uuid" or "uuid|title") were parsed by ten independent implementations that disagreed on whitespace handling, on whether a model-supplied title could be trusted, and on how a leading pipe was treated. The scope-enforced and legacy agent resolvers also duplicated the lookup and the routing step looked every document up a second time. - types.ParseWikiSourceRef / FormatWikiSourceRef / WikiSourceRefMatchesKnowledge are now the only readers and writer of the format. - resolveWikiSourceDocuments replaces resolveAuthorizedSourceRefs, resolveSourceRefs and wikiKnowledgeBasesForSourceRefs: one lookup per document, titles always rebuilt from server data, dedupe by canonical ID, unknown documents fail closed in every mode. - removeSourceRef now matches padded or titled refs of a deleted document. * refactor(data_analysis): expose the selected document as a fixed table name The tool required the document ID inside the SQL text and blindly string-replaced it with the physical DuckDB table name, which forced the model-context codec to rewrite handles inside quoted SQL and let the UUID-derived k_<uuid> table name reach the model through stored schema summaries. The document is now selected only by knowledge_id. Every query runs on a dedicated connection where "dataset" is a temporary view over the physical table (DuckDB temporary objects are connection-local, so concurrent sessions stay isolated). The physical name remains accepted for internal callers; any other table fails validation with an error naming the table the model should use. Schema summaries, the schema tool, the analyst prompt and the tool schema all name the same table, so data_analysis.sql no longer carries source handles and its text codec policy is removed. * feat(modelcontext): report raw identifiers that survive encoding Text-level compaction exists because raw UUIDs reach model context through producers the registry never sees: error strings, slugs, results of unknown shape. Retiring it requires knowing where those producers are. Registry.LeakedIdentifiers scans an encoded message list for UUID-shaped values in every application-composed field (user messages are skipped), classifies each as registered (codec missed a rewrite) or unregistered (producer emitted a raw ID), and SummarizeLeaks renders one line per field. The agent engine and the three RAG pipeline call sites log the report as a warning after EncodeMessages. * fix(chat_pipeline): align RAG data analysis with the fixed table contract The RAG data-analysis plugin still asked the planning model to fill in knowledge_id and to write SQL from a prompt that exposed the raw knowledge UUID, then passed the model's JSON straight to Execute. Under the new data_analysis contract a query that names anything but the dataset table is rejected, and the plugin logged that rejection at error level and moved on, so the analysis vanished without any signal. A "no analysis needed" plan took the same error path. The pipeline now owns document selection: the model returns only needs_analysis and sql, the prompt names the dataset table and never shows the knowledge ID or physical table, and the plugin builds the tool input itself. A rejected query is fed back to the model once for repair; a query that still fails is reported through pipelineWarn with the SQL and the tool error, and "not needed" is logged as such instead of as a failure. Covered by unit tests with a scripted model and executor: not-needed, pipeline-owned knowledge_id, one-shot repair, persistent failure surfaced, unparseable plan rejected.
2026-09-17 14:08:16 +00:00
Every model-call site runs `LeakedIdentifiers` on the encoded messages and
logs a warning naming the role or tool whose text still carries a raw UUID.
A *registered* leak means the codec missed a rewrite site; an *unregistered*
leak means a producer emitted an identifier that never entered the registry.
Text-level compaction (`CompactKnownText`) stays in place as defense in depth
until those producers are fixed and the report stays quiet.
Langfuse generation observations contain the exact encoded payload sent to and
returned by the model. Agent tool spans contain both `model_arguments` (the
model-emitted handles) and `resolved_arguments` (the durable values actually
executed), plus `argument_resolution` and any unresolved handles. Sensitive
tools report only argument keys and resolution counts.
Langfuse is an observer of this boundary; it must not implement another handle
mapping.
## Built-in tool policies
Canonical ID-bearing arguments for knowledge, graph, data, web, and Wiki tools
are decoded centrally through a tool-name plus JSON-field allowlist. The
`sourceKeySpaces` table is the single source of truth for which keys are
ID-bearing and which handle space they register into; per-tool `sourceIDKeys`
contracts gate which of those keys each tool may use.
refactor(modelcontext): consolidate source_refs parsing, fixed data_analysis table, and identifier leak report (#3372) * refactor(wiki): consolidate source_refs parsing and resolution source_refs entries ("uuid" or "uuid|title") were parsed by ten independent implementations that disagreed on whitespace handling, on whether a model-supplied title could be trusted, and on how a leading pipe was treated. The scope-enforced and legacy agent resolvers also duplicated the lookup and the routing step looked every document up a second time. - types.ParseWikiSourceRef / FormatWikiSourceRef / WikiSourceRefMatchesKnowledge are now the only readers and writer of the format. - resolveWikiSourceDocuments replaces resolveAuthorizedSourceRefs, resolveSourceRefs and wikiKnowledgeBasesForSourceRefs: one lookup per document, titles always rebuilt from server data, dedupe by canonical ID, unknown documents fail closed in every mode. - removeSourceRef now matches padded or titled refs of a deleted document. * refactor(data_analysis): expose the selected document as a fixed table name The tool required the document ID inside the SQL text and blindly string-replaced it with the physical DuckDB table name, which forced the model-context codec to rewrite handles inside quoted SQL and let the UUID-derived k_<uuid> table name reach the model through stored schema summaries. The document is now selected only by knowledge_id. Every query runs on a dedicated connection where "dataset" is a temporary view over the physical table (DuckDB temporary objects are connection-local, so concurrent sessions stay isolated). The physical name remains accepted for internal callers; any other table fails validation with an error naming the table the model should use. Schema summaries, the schema tool, the analyst prompt and the tool schema all name the same table, so data_analysis.sql no longer carries source handles and its text codec policy is removed. * feat(modelcontext): report raw identifiers that survive encoding Text-level compaction exists because raw UUIDs reach model context through producers the registry never sees: error strings, slugs, results of unknown shape. Retiring it requires knowing where those producers are. Registry.LeakedIdentifiers scans an encoded message list for UUID-shaped values in every application-composed field (user messages are skipped), classifies each as registered (codec missed a rewrite) or unregistered (producer emitted a raw ID), and SummarizeLeaks renders one line per field. The agent engine and the three RAG pipeline call sites log the report as a warning after EncodeMessages. * fix(chat_pipeline): align RAG data analysis with the fixed table contract The RAG data-analysis plugin still asked the planning model to fill in knowledge_id and to write SQL from a prompt that exposed the raw knowledge UUID, then passed the model's JSON straight to Execute. Under the new data_analysis contract a query that names anything but the dataset table is rejected, and the plugin logged that rejection at error level and moved on, so the analysis vanished without any signal. A "no analysis needed" plan took the same error path. The pipeline now owns document selection: the model returns only needs_analysis and sql, the prompt names the dataset table and never shows the knowledge ID or physical table, and the plugin builds the tool input itself. A rejected query is fed back to the model once for repair; a query that still fails is reported through pipelineWarn with the SQL and the tool error, and "not needed" is logged as such instead of as a failure. Covered by unit tests with a scripted model and executor: not-needed, pipeline-owned knowledge_id, one-shot repair, persistent failure surfaced, unparseable plan rejected.
2026-09-17 14:08:16 +00:00
`database_query.sql` has an explicit policy because source handles can be
embedded inside quoted SQL values when the model filters the real
`knowledges`/`chunks` tables; unquoted SQL aliases and arbitrary prose are
never rewritten. `data_analysis.sql` carries no handles: the selected document
is always exposed as the fixed table `dataset`, so only `knowledge_id` is
decoded. Wiki issue IDs use the same lifecycle
via an `iN` handle space.
Dynamic MCP tools are intentionally opaque in both arguments and results.
Their schemas and identity semantics are controlled by the MCP server, so the
application must not guess that an arbitrary `id`, `knowledge_id`, or `url`
field is durable or rewrite it. Durable resource handles inside MCP arguments
still use the normal `res://NNNN` codec. A future MCP ID mapping must be an
explicit server/tool annotation and should plug into this registry rather than
create a parallel mapper.
Successful MCP execution results additionally receive an
`external_source_candidates` sidecar with up to 50 distinct observed HTTP(S)
links mapped to `wN`. The external payload is not rewritten, discovery schemas
are not scanned, and article IDs are never used to guess URLs. A candidate link
does not establish that its page was read: the model must select the link whose
associated result supports the claim. When no handle is supplied, the citation
protocol permits an exact supplied source URL as a Markdown link, never a
borrowed knowledge-base citation.
The application-owned MCP bridge is an explicit exception for routing fields:
`discover_mcp_tools.server_id` uses `msN`, and `call_mcp_tool.tool_ref` uses
`mtN`. Tool definition enums, service summaries, discovery results and replayed
calls share the same request registry. Only directory envelope fields are
registered; `input_schema`, `call_mcp_tool.arguments`, and external execution
results remain opaque. Arguments are restored before authorization, validation,
execution, persistence and UI events. Unknown routing handles fail closed.
For model-emitted `call_mcp_tool` calls, one extra JSON-string encoding of the
`arguments` envelope is accepted only when it contains a complete JSON object
(including `{}`). Normalization runs before resource-handle decoding; original
model arguments are retained for tracing. Nested business strings are unchanged,
and malformed JSON, arrays, `null`, and further encoding layers remain invalid.
The canonical object still passes the existing routing, schema and approval checks.
## Wiki routing
`WikiRouteResolver` is intentionally separate. It stores server-side
slug-to-knowledge-base provenance gathered during Wiki search/read operations,
and can only return knowledge bases already present in the Agent's authorized
Wiki scope. It is routing state, not a model handle table. Reads scan every
legal Wiki KB so cached provenance cannot hide a duplicate slug; mutations
require one unique owner. New pages use link provenance, a single Wiki scope,
or a single source-document owner and reject ambiguous routing instead of
asking the model for a durable KB ID.
Document/tag-constrained Wiki and graph requests are filtered by the same
server-owned `SearchTargets` provenance. Uncited/global Wiki pages and graph
results outside that subset fail closed; only an explicit whole-KB target
authorizes whole-KB content.