Files
interactive-story/backend/app/knowledge/inject.py
T
JesseMarkowitzandClaude Opus 5 480414efe0 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
2026-09-06 15:40:13 -04:00

267 lines
11 KiB
Python

"""M7: fitting retrieved knowledge into the prompt, and saying what it cost.
`retrieval.py` decides which passages are worth offering. This module decides
how many of them the prompt can actually afford, renders them with the framing
their class carries, and produces the provenance record the Insights panel and
the acceptance tests read.
It is pure. It takes a `retrieval.Result`, a budget and a token counter, and
returns text — no database, no session, no clock. That is what lets
`context/builder.py` import it without the import cycle a fuller dependency
would create, and it is why the whole budget arithmetic is testable without a
campaign.
## The pressure rules
`CONTEXT-AND-MEMORY.md` §29-31 and §37-40 of the design ask for four different
behaviours under pressure, and they are four different mechanisms here:
always-included Canon protected. Counted with the system block, before
any history is chosen. If it cannot fit alongside
the other protected sections and the reply reserve,
the turn fails with `ContextOverflow` rather than
sending a prompt known to overflow.
retrieved Canon bounded, and first in line for the retrieved budget.
Reference bounded, and capped at a share of it, so Reference
can never crowd out Canon.
Inspiration capped smallest, filled last, dropped first.
Every one of those is spent out of `KNOWLEDGE_SHARE` of what is left after the
protected context and the reply reserve are subtracted, so none of it can reach
the current state, the reader's input, the narrator rules or the output reserve.
Whatever is not spent returns to the story history rather than being lost.
## Rendering
Each passage arrives labelled with the file it came from, its heading trail and
its index, because that label is the provenance the reader inspects and it is
also what lets a narrator say where something came from. Hidden passages carry
`[narrator only]` on that same line — in the passage, not only in a preamble at
the top of the section, because a passage is read where it sits.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Callable
from . import classes
from .records import Candidate, Result
#: Share of the non-protected budget that retrieved knowledge may spend.
#:
#: Story cards already take up to 40% (`CARD_BUDGET_SHARE`), and the history is
#: what is left. A third is enough for several passages at the chunker's
#: typical size and leaves the majority of the window to the story itself,
#: which is the thing the reader came for.
KNOWLEDGE_SHARE = 0.33
#: What each class may take of the knowledge budget. Canon may take all of it;
#: the other two are capped so that they cannot, whatever they score.
CLASS_SHARE = {
classes.CANON: 1.00,
classes.REFERENCE: 0.50,
classes.INSPIRATION: 0.25,
}
#: A ceiling on always-included Canon, as a share of the whole context budget.
#:
#: `always_include` is the one place a reader can put unbounded text into every
#: prompt, and it must not be allowed to consume the whole context window
#: (`IMPORTED-KNOWLEDGE-DESIGN.md` §32, `CONTEXT-AND-MEMORY.md` §29). It does
#: not fail silently either: what does not fit is
#: reported as dropped, with its token cost, in the same record everything else
#: appears in.
ALWAYS_SHARE = 0.20
#: The order classes are filled in, highest authority first.
FILL_ORDER = (classes.CANON, classes.REFERENCE, classes.INSPIRATION)
@dataclass
class Section:
label: str
text: str
@dataclass
class Plan:
"""A retrieval result, priced and ready to be cut to a budget."""
result: Result
count_tokens: Callable[[str], int]
#: Sections for the system block: the untrusted-data rule and the Canon
#: this campaign has marked as always in force.
protected: list[Section] = field(default_factory=list)
protected_tokens: int = 0
_always_used: list[Candidate] = field(default_factory=list)
_always_dropped: list[Candidate] = field(default_factory=list)
_live_used: list[Candidate] = field(default_factory=list)
_live_dropped: list[Candidate] = field(default_factory=list)
_budget: int = 0
_spent: int = 0
def plan(
result: Result, count_tokens: Callable[[str], int], context_budget: int
) -> Plan:
"""Prices the protected half: the framing rule and always-included Canon.
Called before the builder knows how much history it can afford, because the
answer depends on this.
"""
ready = Plan(result=result, count_tokens=count_tokens)
if not result.candidates and not result.suppressed:
return ready
always = [c for c in result.candidates if c.always_include]
others = [c for c in result.candidates if not c.always_include]
# The rule is emitted whenever anything at all will be shown, including when
# only always-included Canon survives. A framed section with no frame is the
# failure mode this section exists to prevent.
if not always and not others:
return ready
rule = classes.KNOWLEDGE_RULE
if any(c.visibility == classes.HIDDEN for c in result.candidates):
rule = f"{rule}\n{classes.HIDDEN_RULE}"
ready.protected.append(Section(classes.SECTION_RULE, rule))
if always:
cap = max(0, int(context_budget * ALWAYS_SHARE))
lines: list[str] = []
spent = 0
for candidate in always:
rendered = render(candidate)
cost = count_tokens(rendered) + count_tokens("\n\n")
if spent + cost > cap:
ready._always_dropped.append(candidate)
continue
lines.append(rendered)
spent += cost
ready._always_used.append(candidate)
if lines:
body = "\n\n".join([classes.ALWAYS_FRAMING] + lines)
ready.protected.append(Section(classes.SECTION_ALWAYS_CANON, body))
ready.protected_tokens = sum(count_tokens(s.text) for s in ready.protected)
return ready
def select(ready: Plan, available: int) -> list[Section]:
"""Fills the retrieved-knowledge budget out of `available`. Returns sections.
`available` is what the context builder has left for everything elastic, so
only `KNOWLEDGE_SHARE` of it is spendable here — the remainder belongs to
the story history and is left untouched.
Classes are filled in authority order, each against its own cap and against
what is left. A passage that does not fit is recorded as dropped rather than
dropped silently: a reader asking "why is that not in the prompt?" gets
"there was no budget for it", with the number.
"""
ready._budget = budget = max(0, int(available * KNOWLEDGE_SHARE))
candidates = [c for c in ready.result.candidates if not c.always_include]
if not candidates or budget <= 0:
ready._live_dropped.extend(candidates)
return []
separator_cost = ready.count_tokens("\n\n")
sections: list[Section] = []
spent = 0
for classification in FILL_ORDER:
members = [c for c in candidates if c.classification == classification]
if not members:
continue
cap = min(budget - spent, int(budget * CLASS_SHARE[classification]))
lines: list[str] = []
used = 0
for candidate in members:
rendered = render(candidate)
cost = ready.count_tokens(rendered) + separator_cost
if used + cost > cap:
ready._live_dropped.append(candidate)
continue
lines.append(rendered)
used += cost
ready._live_used.append(candidate)
if lines:
body = "\n\n".join([classes.CLASS_FRAMING[classification]] + lines)
sections.append(Section(classes.CLASS_SECTIONS[classification], body))
spent += used
ready._spent = spent
return sections
def render(candidate: Candidate) -> str:
"""One passage as the narrator sees it: a provenance line, then the text.
The label is not decoration. It is what makes a claim in the prompt
attributable — the difference between the narrator reading a fact and the
narrator reading a fact *from a file the reader imported and classified* —
and it is the same identification the inspector shows, so the two agree.
"""
parts = [candidate.filename or candidate.title or "imported source"]
if candidate.heading_path:
parts.append(candidate.heading_path)
parts.append(f"passage {candidate.chunk_index + 1}")
label = " · ".join(parts)
if candidate.visibility == classes.HIDDEN:
label = f"{label} {classes.HIDDEN_MARKER}"
return f"[{label}]\n{candidate.text}"
def report(ready: Plan) -> dict:
"""What the Insights panel and the tests read about this turn's knowledge.
Everything needed to answer F05 and F06 for imported material: which source,
which file, which class, which visibility, which passage, what it scored on
each path and combined, how it was found, what it cost, and what was
considered and set aside.
This dict is written into the turn's context snapshot, and the rendered text
goes with it. That is deliberate, and it is what
`IMPORTED-KNOWLEDGE-DESIGN.md` §49-50 requires: a turn's evidence must
survive the source being deleted, so the record holds the text rather than a
pointer to a row that can go away.
"""
result = ready.result
return {
"used": [_used(c, ready) for c in ready._always_used + ready._live_used],
"dropped": [
dict(_record(c), reason="over the knowledge budget")
for c in ready._always_dropped + ready._live_dropped
],
"suppressed": [
dict(_record(c), duplicate_of=c.duplicate_of) for c in result.suppressed
],
"terms": result.terms,
"considered": result.considered,
"generated": result.generated,
"rejected": result.rejected,
"semantic_floor": result.semantic_floor,
"semantic_calibrated": result.semantic_calibrated,
"embedding_model": result.embedding_model,
"semantic_used": result.semantic_used,
"semantic_note": result.semantic_note,
"scan_truncated": result.scan_truncated,
"budget": ready._budget,
"spent": ready._spent,
"protected_tokens": ready.protected_tokens,
}
def _record(candidate: Candidate) -> dict:
return candidate.as_record()
def _used(candidate: Candidate, ready: Plan) -> dict:
"""A used passage, with the text that was actually supplied."""
rendered = render(candidate)
return dict(
_record(candidate),
text=candidate.text,
rendered=rendered,
prompt_tokens=ready.count_tokens(rendered),
)