M7: a first-class imported knowledge library
A campaign can import local .txt and .md files as Canon, Reference or Inspiration, and the class is load-bearing rather than a label: it decides the words a passage is framed with in the prompt, the weight it carries when passages are ranked, and which budget it competes in when the context is tight. This is a separate subsystem, which is the Phase 0B decision (IMPORTED-KNOWLEDGE-DESIGN.md §73). Story Cards do not carry classification, provenance, content identity, chunking, an index or a lifecycle, and they were not promoted into something that does. Nothing here reads or writes one. The subsystem, in backend/app/knowledge/: classes the three classes, their weights, and the prompt framing chunking deterministic, heading-aware, 60-800 tokens, no overlap fts SQLite FTS5 with porter stemming; scoped and bounded in SQL importer validate, hash, store, chunk, index — in one transaction embeddings local Ollama vectors through the shared provider retrieval query construction, hybrid merge, rerank inject the budgeted cut and the rendered prompt sections Relevance admission is a separate stage from ranking, and that separation is the milestone's most expensive lesson. An independent review found the first implementation deciding relevance with a floor expressed as a share of the best candidate — which the best clears by construction — so a passage was admitted on every turn regardless of the scene. A query about tide tables and container tonnage retrieved all five sources of a fantasy campaign, narrator-only hidden Canon among them. So the pipeline is now: candidate generation -> admission -> ranking -> class weighting -> budget Admission reads raw, candidate-set-independent signals: the cosine the model returned, and how many distinct meaningful query terms a passage contains. Ranking reads normalized ones, because bm25 has no fixed range and cosine's zero is not zero. Normalization decides order among things that matched; it can never decide whether anything matched. Authority is applied after admission, so a class orders what matched and never rescues what did not. Retrieval may therefore return nothing, and on a scene unrelated to the library it does. The other decisions that each replaced an obvious wrong one: - The class multiplies relevance rather than adding to it. An additive bonus satisfies "Canon outranks Reference" and makes "do not include irrelevant Canon" impossible, because a large enough constant wins on its own. - The semantic floor is measured, not guessed: 113 production-path pairs against nomic-embed-text put targeted matches at 0.55-0.85 and off-topic pairs at 0.36-0.56, and 0.58 sits between them. Because it is a property of that model and not of cosine similarity, it is keyed to the model rather than applied to whatever is configured: an embedding model with no measured calibration in this build does not borrow the number. Semantic admission is skipped, the campaign retrieves lexically, and the reason is stated in the knowledge status and in the turn's provenance. Degrading to lexical keeps the library usable; lending the threshold to an unmeasured model is how the admitted-everything defect would return. - One lexical term is not evidence. Two distinct meaningful terms, or one that is neither a standing campaign entity nor a negligible share of the query. The stop list grew from 42 words to 261, all function words — no subject matter, because a stop list that removes subject matter stops finding "The Silver Key". - Lexical retrieval is a production path, not a fallback. It finds the proper nouns and invented terms a setting bible is made of, and the library is fully usable with no embedding model configured. Safety is structural rather than filtered. Imported text reaches the prompt whole, inside a section that says what it is, under a rule stating the authority order in words and refusing every instruction inside it. No endpoint accepts a filesystem path, so H08 has no mechanism to escape from. Nothing renders imported content as HTML, so a script tag is five visible characters and a remote image is never fetched. Import, chunking, indexing, retrieval and a turn open no socket at all; only embeddings do, through the endpoint allowlist the memory bank already uses. Provenance is the rendered text, not a foreign key: deleting a source cannot turn a historical turn's evidence into dangling ids. Schema: knowledge_sources, knowledge_chunks, knowledge_embeddings, and an FTS5 virtual table attached to knowledge_chunks as a DDL hook so it is created and dropped with the table it indexes. Migration 92. A pre-M7 database opens unchanged and needs no sources to play. Bundle: the source content and the reader's judgements about it travel; the passages, index rows and vectors are rebuilt on import, so a restored campaign is searchable immediately without a reindex step. One runtime dependency: python-multipart, Starlette's multipart parser. It is what makes the upload surface possible, and the upload surface is why no pathname is ever accepted. The test doubles were the reason the defect shipped, so they were corrected too. The retrieval stub scored unrelated text at 0.06-0.20 where the real model scores it at 0.43-0.44, and its docstring said it had deliberately removed the constant component that "would put a similarity floor under every pair" — which is exactly the property real models have. The stub now has that floor, one test fails if it is ever removed, and another reproduces the superseded rule and asserts it is still fooled by the same fixture. Run against the pre-corrective implementation, the new suite fails 13 of 18. Tests: 939 passed, 14 skipped (836/7 at M6). 110 new across seven files, one of which mocks nothing between itself and Ollama and re-measures the similarity separation on every run. 43/43 checks in a real Firefox, reproduced. Docker build clean. Four other defects found by review or by the browser run were fixed here rather than carried: an unreachable relevance constant that appeared to enforce something and did not; acceptance tests using the wrong fixture files, so G07's trap was never exercised; a bidirectional override surviving into displayed filenames; and, from the implementation pass, the Insights panel showing M5's two state sections as raw keys and the source inspector refetching on every keystroke. M7 was independently reviewed, which returned PASS WITH CORRECTIVE WORK REQUIRED. Both blocking findings are closed, and closeout resolved the embedding-model calibration boundary the corrective pass had left as debt. planning/reports/M7-IMPLEMENTATION-REPORT.md carries the review, the corrective closeout and the closeout verification in sequence, none overwriting another. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017HdaXiFbscatQaLS7dJk6b
This commit is contained in:
co-authored by
Claude Opus 5
parent
a6e9c7a32b
commit
480414efe0
@@ -1192,3 +1192,116 @@ software privilege
|
||||
```
|
||||
|
||||
A source can be highly relevant and authoritative as Canon while still being completely untrusted as executable application input.
|
||||
|
||||
---
|
||||
|
||||
## 76. As Implemented in M7
|
||||
|
||||
Everything §74 lists as required for v1 is built, and every capability §74 lists
|
||||
as "strongly preferred and planned" is built as well. What follows records what
|
||||
was chosen where this document offered options, and what was deliberately left
|
||||
out. It does not weaken any requirement above.
|
||||
|
||||
### Storage (§11, §14)
|
||||
|
||||
Source text lives **in SQLite**, on the source row. The alternative this document
|
||||
also permits — an application-owned file area with the database as metadata
|
||||
authority — was rejected as more machinery for no benefit at this scale: one
|
||||
transaction covers the source, its passages and its index, so a failed import
|
||||
cannot leave a file with no row or a row with no file; the export carries the
|
||||
content with no second archive format; and there is no directory whose contents
|
||||
can drift out of step with the rows describing it. Sources are capped at 1 MiB.
|
||||
|
||||
Source versioning (§14, §43) is **not** implemented. The v1 model is the simpler
|
||||
one this document permits: a duplicate is refused with a conflict naming the
|
||||
source that already holds the content, and the reader may deliberately import a
|
||||
second copy. There is no supersession chain and no version history.
|
||||
|
||||
### Chunking (§15-§17)
|
||||
|
||||
Deterministic, heading-aware, no overlap. A heading boundary closes a passage
|
||||
only once it has reached 60 tokens; below that the packer runs through the
|
||||
boundary and writes every heading it crosses into the passage text, so a
|
||||
reference document of one-line sections becomes usable passages instead of a
|
||||
hundred fragments. The ceiling is 800 tokens and a longer paragraph is split at
|
||||
sentence boundaries.
|
||||
|
||||
Overlap (§15) was declined rather than forgotten: it duplicates text into a
|
||||
bounded budget, and the redundancy suppressor downstream exists to notice two
|
||||
passages saying the same thing — which is what overlap manufactures. The heading
|
||||
trail gives each passage its context without duplicating any of it.
|
||||
`CHUNKING_VERSION` is how a change to any of this would be rolled out.
|
||||
|
||||
### Retrieval (§26, §29, §30) — corrected after independent review
|
||||
|
||||
Relevance is decided **before** authority and **before** any comparison between
|
||||
candidates, which is what makes §30's two requirements compatible. The first
|
||||
implementation ranked first and cut at a share of the best candidate; that cannot
|
||||
reject anything, because the best always clears a share of itself, so irrelevant
|
||||
Canon reached every prompt. `TECHNICAL-DESIGN.md` §13.2 records the architecture
|
||||
and the general lesson.
|
||||
|
||||
Admission uses signals with meaning of their own:
|
||||
|
||||
```text
|
||||
semantic raw cosine >= a measured, model-specific floor
|
||||
lexical >= 2 distinct meaningful terms, or exactly 1 that is neither the
|
||||
name of a standing campaign entity nor a negligible share of the
|
||||
query
|
||||
```
|
||||
|
||||
**Retrieval may return nothing**, and on a scene unrelated to the library it
|
||||
does. That is required behaviour, not a degenerate case: §30's "do not include
|
||||
irrelevant Canon merely because it is authoritative" has no other meaning when
|
||||
*every* source is irrelevant.
|
||||
|
||||
The semantic floor is **calibrated per embedding model**. It was measured
|
||||
against `nomic-embed-text`; a model this build has not measured does not inherit
|
||||
the number, and semantic retrieval is skipped for it with the reason reported,
|
||||
leaving lexical retrieval — a first-class path under §23-24 — to carry the
|
||||
library. §25's "generate embeddings locally, preferably through Ollama" is
|
||||
unchanged; what is added is that a *similarity threshold* is model-specific and
|
||||
must be measured before it is trusted. `TECHNICAL-DESIGN.md` §13.3 records the
|
||||
policy and what it costs.
|
||||
|
||||
Hybrid, and the ranking among survivors is:
|
||||
|
||||
```text
|
||||
relevance = max(lexical, semantic) + 0.15 x min(lexical, semantic)
|
||||
score = relevance x class weight canon 1.00 ref 0.85 insp 0.70
|
||||
```
|
||||
|
||||
Both inputs are normalized against the best surviving value of their own path,
|
||||
because `bm25` has no fixed range and cosine's zero is not zero. The class
|
||||
**multiplies** relevance rather than adding to it, so it can order what matched
|
||||
and can never rescue what did not.
|
||||
|
||||
Entity linking (§33), tags (§34), manual priority (§35) and scene pinning (§36)
|
||||
are **not** implemented. Entity and place names do reach the query, because it is
|
||||
built partly from the authoritative state, but there is no explicit link and no
|
||||
tag. §36's recommended v1 minimum — always-include for critical Canon — is built.
|
||||
|
||||
Conflict detection between two Canon sources (§42) is **not** implemented. Two
|
||||
Canon sources that disagree are both retrieved and both framed as Canon.
|
||||
|
||||
### Scope metadata (§45)
|
||||
|
||||
`invariant / initial / descriptive / historical` is **not** implemented. §45
|
||||
itself says explicit current-state precedence may be sufficient for v1, and that
|
||||
is what was built: the authoritative state is emitted after the imported
|
||||
sections and the knowledge rule states in words that an imported file was
|
||||
written before the story ran, so where the two disagree the state is right.
|
||||
|
||||
### Failure and observability (§57, §58)
|
||||
|
||||
Import is one transaction: a failure leaves no source, no passages and no index
|
||||
rows, and never touches the reader's file. Retrieval is gated on
|
||||
`index_state = "ready"`, so even a hypothetical partial commit would be inert
|
||||
rather than wrong. The lexical and semantic halves report separately, per source
|
||||
and per campaign, because "the vectors failed" and "the index failed" have
|
||||
different consequences and only one of them stops the library working.
|
||||
|
||||
### Search UI (§62) and chunk editing (§63)
|
||||
|
||||
Neither is implemented; both are explicitly optional here. The source inspector
|
||||
shows the full text and every passage, which §62 accepts as adequate.
|
||||
|
||||
Reference in New Issue
Block a user