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:
JesseMarkowitz
2026-09-06 15:40:13 -04:00
co-authored by Claude Opus 5
parent a6e9c7a32b
commit 480414efe0
52 changed files with 10894 additions and 52 deletions
+98
View File
@@ -677,6 +677,59 @@ Requirements:
- permit re-indexing,
- never execute imported content.
## 24A. Imported Knowledge Tables (M7, as implemented)
Three tables, and the boundary between them is the boundary between what the
reader gave the campaign and what the machine derived from it.
```text
knowledge_sources the file, and the reader's judgements about it
id, adventure_id campaign-scoped; no branch coordinate, deliberately
title, original_filename the filename is metadata and is never a path
classification "canon" | "reference" | "inspiration"
enabled out of retrieval without being deleted
visibility "normal" | "hidden" (narrator-only)
always_include Canon only: in force whatever the scene is
content the accepted text, as decoded
content_hash SHA-256 of the normalized text; the duplicate test
byte_size, media_type
parser_version what produced the passages now on disk
chunking_version
index_state, index_detail "pending" | "ready" | "failed" — the lexical half
embed_state, embed_detail "idle" | "pending" | "ok" | "failed" — the semantic half
notes, imported_at, updated_at
knowledge_chunks derived: a deterministic function of the content
id, source_id, adventure_id
chunk_index, heading_path
text, token_count, content_hash
knowledge_embeddings derived: rebuildable, and its own table so that
id, chunk_id, adventure_id "rebuild the semantic index" is one DELETE
vector packed float32, as `memories.embedding_blob` is
model, dimensions what makes a stale vector detectable
parser_version, chunking_version, created_at
knowledge_fts a SQLite FTS5 virtual table over heading + text,
keyed by chunk id. Not describable in SQLAlchemy
metadata, so it is attached to `knowledge_chunks`
as a DDL hook and travels with it.
```
**Only the first two columns of a source are not derivable**: its content and
its classification. Everything else about a source is metadata describing one of
those two, and everything in the other two tables is rebuilt from the content by
a deterministic chunker. That is what lets the export carry the source alone
(§29) and what makes a reindex safe.
There is deliberately **no branch coordinate** anywhere here. An imported file is
campaign source material and does not become a different file because the story
forked (`CONTEXT-AND-MEMORY.md` §39). The rule that abandoned story content must
not reach the prompt is met at the *query* instead: the retrieval query is built
from the head-capped lineage and the authoritative state at the position being
read, never from the uncapped action table. A future knowledge record *derived*
from story history would need a coordinate; M7 introduces no such record.
## 25. Retrieval Record
Every turn should record which memories or knowledge chunks were supplied to the narrator.
@@ -696,6 +749,30 @@ This lets the prompt inspector answer:
> Why did the narrator know this?
### As implemented (M6 for memories, M7 for imported knowledge)
There is no `retrieval_record` table. The record lives in the turn's own context
snapshot, which every turn already stores, and it carries the **rendered text**
alongside the identifiers:
```text
context_snapshot.knowledge
used[] source_id, title, filename, classification, visibility,
chunk_id, chunk_index, heading_path, always_include,
mode ("lexical" | "semantic" | "hybrid" | "always"),
lexical, semantic, cosine, score, tokens,
text, rendered, prompt_tokens
dropped[] the same, plus why there was no budget for it
suppressed[] the same, plus the passage it repeated
terms, considered, floor, budget, spent
semantic_used, semantic_note, scan_truncated
```
Carrying the text rather than a foreign key is the whole point. A separate table
of ids would turn every historical turn's evidence into dangling references the
moment a source were deleted, and §49-50 of `IMPORTED-KNOWLEDGE-DESIGN.md`
require the opposite: a turn must go on being able to say what it was given.
## 26. Prompt Snapshot
```yaml
@@ -789,6 +866,27 @@ with identical turns can be being read at different positions and no import can
tell which. An export written before the field existed is opened at its retained
tip, which is the position such a file recorded.
**M7 added the imported knowledge library**, by the same rule and no other. The
bundle carries each source's content, classification, enabled state, visibility,
always-include flag, title, filename, notes, import timestamp and content hash —
everything the reader chose, and one derived value whose only purpose is to be
checked against what arrived. It carries no passages, no FTS rows and no
vectors: those are a deterministic function of the content, and the import
rebuilds the passages and the lexical index before it returns, so an imported
campaign is searchable immediately with no reindex step. Vectors rebuild
separately against whatever embedding model *this* machine has, which is the
right answer and the reason exporting them would have been the wrong one.
A source that fails to rebuild is recorded as failed rather than refusing the
import: by that point the story, its tree, its head and its Save Points are
already written, and the index is the cheap half. A malformed *knowledge section*
— an unknown classification, missing content — does refuse the import, because a
campaign whose imported Canon quietly did not arrive is a campaign whose narrator
has stopped being told the rules, with nothing to notice.
A bundle written before M7 has no knowledge section and imports with an empty
library, which is what such a campaign had.
## 30. Deletion vs Archival
The system must distinguish: