Files
interactive-story/planning/CONTEXT-AND-MEMORY.md
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

35 KiB

Adventure Storyteller — Context and Memory

Status: v1.0 — aligned to Phase 0B findings
Purpose: Define what information is supplied to the narrator on each turn, how long-term memory works, and how authority, lineage, retrieval, summaries, and imported knowledge interact.

1. Design Goal

The language model should never be expected to remember an entire long-running story by itself.

The application should construct a bounded context for every narrator turn using:

  • durable narrator rules,
  • campaign canon,
  • current authoritative state,
  • branch-safe summaries,
  • relevant older story memories,
  • relevant imported local knowledge,
  • recent active-lineage turns,
  • the user's current input.

The full campaign history remains stored locally even when only a subset is sent to Ollama.

The core rule is:

The application decides what the narrator is allowed to rely on; the model does not decide what counts as canon.

2. Context Layers

The narrator context should be assembled from distinct layers.

Recommended order:

1. System / narrator rules
2. Campaign profile
3. Authoritative canon and world rules
4. Current authoritative narrative state
5. High-level campaign / arc summary
6. Relevant older story memories
7. Relevant imported local knowledge
8. Recent active-lineage turns
9. User's current input

Not every layer must appear on every turn.

Each layer should have:

  • explicit authority,
  • source provenance,
  • token budget,
  • branch/lineage rules where applicable.

3. Authority Levels

The narrator must distinguish between authoritative and suggestive information.

Recommended authority hierarchy:

Level 1 — Explicit Campaign Canon

Highest authority.

Examples:

  • FTL does not exist.
  • Mara is Edrin's sister.
  • Magic cannot resurrect the dead.
  • The story takes place in 1892.

Sources:

  • campaign setup,
  • user-authored canon documents,
  • manual canon corrections.

If narration conflicts with Level 1 canon, Level 1 wins.

Level 2 — Accepted Story Facts / Current State

Facts established by accepted active-lineage story history.

Examples:

  • Aldric currently possesses the silver key.
  • Mara has already met the protagonist.
  • The eastern bridge was destroyed.
  • The Persephone is docked at Ceres Station.

These are authoritative unless later invalidated or corrected.

Level 3 — Accepted Historical Events

Important events that occurred earlier on the active lineage.

Examples:

  • Mara warned Aldric not to trust Captain Vale.
  • The crew discovered a signal beneath Europa's ice.
  • Aldric promised to return before sunrise.

These are historical truth for the active story.

Level 4 — Derived / Heuristic Memory

Useful inferred information that may help continuity but must not be treated as hard canon.

Examples:

  • Mara seemed nervous when Captain Vale arrived.
  • Aldric probably distrusts the city guard.
  • The abandoned station may be dangerous.

The prompt should identify these as inference or interpretation.

Level 5 — Imported Reference Material

Supporting local information.

Examples:

  • medieval tavern construction,
  • orbital mechanics reference notes,
  • technical description of fusion drives,
  • historical clothing references.

Reference material may guide detail and plausibility but does not override campaign canon.

Level 6 — Imported Inspiration Material

Lowest authority.

Examples:

  • public-domain fantasy passages,
  • science-fiction stories,
  • descriptive prose samples,
  • atmosphere/style excerpts.

Inspiration can influence tone, imagery, pacing, or ideas.

It must never be treated as proof that something exists in the current story world.

4. Authority Conflict Rule

When two context items conflict:

higher authority wins

Example:

Campaign Canon:

FTL travel does not exist.

Imported Reference:

A fictional source describes warp drives.

Narrator behavior:

Do not introduce warp drive as established technology.

The reference may still inspire descriptive language if relevant, but cannot override canon.

5. Pretrained Model Knowledge

The local language model contains pretrained knowledge that cannot be erased.

The application should instruct the narrator:

Pretrained knowledge may help with language, general plausibility, and invention, but it is not authoritative story canon.

The narrator must not silently import:

  • named characters,
  • locations,
  • technologies,
  • factions,
  • magic systems,
  • plot facts

from unrelated outside works unless the campaign context explicitly establishes them.

The application cannot guarantee perfect suppression of pretrained knowledge, but it can make authority boundaries explicit and inspectable.

6. Current Authoritative State

Every turn should include the minimum current state necessary for continuity.

Potential categories:

  • current location,
  • current scene,
  • characters present,
  • active relationships,
  • possessions,
  • important conditions,
  • active story threads,
  • unresolved facts,
  • current organization/faction relationships,
  • world constraints relevant to the scene.

The state context should be concise and structured.

Do not dump the entire database into every prompt.

7. State Selection

State should be selected based on relevance.

Always include:

  • protagonist identity,
  • current location,
  • current scene,
  • key current conditions,
  • globally critical canon rules.

Conditionally include:

  • nearby characters,
  • relevant items,
  • related factions,
  • thread-specific facts,
  • location-specific rules,
  • technology/magic constraints relevant to the action.

8. Recent History

Recent active-lineage turns should normally be included verbatim.

Purpose:

  • local conversational continuity,
  • dialogue coherence,
  • immediate action continuity,
  • writing rhythm.

Recommended policy:

  • include as many recent turns as fit within the recent-history token allocation,
  • prefer complete turn boundaries,
  • never include abandoned/disposable future history,
  • preserve speaker/role metadata.

The exact number of turns should be token-based rather than fixed.

9. Rolling Summary

Older active-lineage material should be compressed into summaries.

A rolling summary should contain:

  • major events,
  • current goals,
  • important discoveries,
  • relationship changes,
  • unresolved threads,
  • durable consequences.

A summary should not preserve every stylistic detail.

Important rule:

A summary is derived data, not authoritative history.

The original transcript remains the source of truth.

10. Summary Scope

Potential summary levels:

Campaign Summary

Very compressed overview of the story so far.

Arc / Chapter Summary

More detailed representation of a recent story segment.

Turn-Range Summary

Derived from a bounded range of turns.

Recommended v1:

  • one campaign-level rolling summary,
  • optional turn-range/chapter summaries if inherited architecture supports them cleanly.

11. Summary Lineage Safety

Every summary must be associated with the history it summarizes.

If the user restores or diverges before part of that source history:

  • the invalid portion must not be reused,
  • unaffected ancestral summaries may remain valid,
  • new summaries should be created for the new continuation.

A summary from abandoned history must never leak into active context.

As implemented (M6)

Lineage safety here has two halves, and the M6 review found that having only the first is not enough.

The row must be eligible. A summary is a row with a coordinate, exactly as a memory is: branch_id and depth name the last node it covers, source_start/source_end the stretch. Eligibility is one question — is that coordinate on the active, head-capped lineage? — answered by lineage.Path.clause, the same chokepoint every read of the story goes through. Undo, Redo, Save Point restore and divergence all fall out of that without a rule of their own.

The input must be eligible too. Summary generation is seeded only from a summary that is itself valid on the current head-capped lineage (summaries.current). Where none is, the new line starts from no previous summary.

The second half was missing in the first M6 implementation and E03 failed because of it: the summariser seeded itself from adventures.story_summary, a campaign-global column with no lineage, so after a divergence it was handed the abandoned line's prose and asked to update it. The row it produced was correctly anchored to the new branch and therefore looked lineage-safe while its sentences described a story the reader had left. Anchoring the output is not enough; the input has to be scoped by the same rule.

Abandoned summaries are retained, never deleted, and become eligible again if the reader returns to the line that produced them.

adventures.story_summary remains, as a reader-facing convenience only: the Plot panel edits it and the export bundle carries it. It is a mirror of whichever summary is currently eligible — kept in step when one is written and when the head moves — and nothing authoritative may read it. A summary the reader types is recorded as a row anchored at the position they typed it at, so it behaves like any other.

12. Story Memory

Long-term story memory should retrieve important older information that is not present in recent history or current summary.

Examples:

  • a promise made 80 turns ago,
  • a minor character encountered much earlier,
  • the origin of an item,
  • a clue from a distant chapter,
  • a prior argument between two characters.

Memory exists to restore specific detail that broad summaries may omit.

13. Memory Types

Recommended memory categories:

Event Memory

Something happened.

Example:

Turn 42: Mara hid a letter beneath the hearthstone.

Character Memory

Important information about a character.

Example:

Captain Vale strongly dislikes being touched unexpectedly.

Relationship Memory

A meaningful interaction or relationship change.

Example:

Aldric broke his promise to Mara.

Discovery Memory

A clue or learned fact.

Example:

The silver key bears the same symbol as the old abbey crypt.

Promise / Commitment Memory

Future-relevant obligation.

Example:

Aldric promised to return before dawn.

Location Memory

Important prior detail about a place.

Heuristic Memory

Interpretive information that may be useful but is not hard canon.

14. Memory Authority

Every memory should carry an authority classification.

Examples:

accepted_story
current_state
heuristic

The narrator should be told which memories are:

  • factual,
  • inferred,
  • uncertain.

This avoids turning guesses into canon.

As implemented (M6)

Two values, accepted_story and heuristic, on Memory.authority. The application classifies, not the model: memorybank.classify_authority reads the memory's own text for hedging ("seemed", "appeared to", "probably"), so an extractor cannot promote a guess by asserting it confidently. The prompt marks a heuristic memory [inferred] and says in words that such lines are interpretation rather than established fact.

Retrieval never writes state. A memory of either authority is something the narrator is shown; the only path to an authoritative change remains the M5 typed event pipeline (ADR 013).

15. Memory Creation

Memories may be generated after accepted turns.

Potential pipeline:

accepted turn
   |
   v
memory extractor
   |
   v
candidate memories
   |
   v
application validation / classification
   |
   v
stored memory records

Not every turn needs a permanent memory.

The memory system should favor:

  • importance,
  • future usefulness,
  • uniqueness,
  • continuity relevance.

16. Memory Retrieval

Retrieval should be local.

Potential mechanisms:

  • lexical search,
  • semantic embeddings,
  • hybrid search.

Current preference:

Hybrid local retrieval if practical.

Reason:

  • lexical retrieval is transparent and precise for names/terms,
  • semantic retrieval is useful for conceptually related old events.

Phase 0B confirmed useful local semantic memory in AI-DnD and deterministic lexical lore in ai-adventure. The selected production direction is hybrid local retrieval, implemented incrementally with a lexical path that remains usable when semantic embeddings are unavailable.

17. Embeddings

If semantic retrieval is used:

  • embeddings must be generated locally,
  • preferably through Ollama,
  • no remote embedding API,
  • embeddings are derived data,
  • embeddings must be rebuildable.

Potential local embedding model should be selected later based on actual hardware and model quality.

18. Memory Retrieval Query

The retrieval query may include:

  • current user input,
  • current scene,
  • active story thread names,
  • entities mentioned,
  • current location,
  • current goals.

Do not rely only on raw user input.

Example:

User:

I ask Mara whether she recognizes the symbol.

Retrieval query may include:

Mara
symbol
silver key
abbey crypt
prior discoveries

19. Memory Retrieval Filtering

Before ranking memories, filter by:

  • campaign,
  • active lineage,
  • allowed authority,
  • source validity,
  • enabled status.

Never retrieve memories from:

  • abandoned future paths,
  • deleted campaigns,
  • unrelated campaigns.

20. Memory Ranking

Potential ranking factors:

  • semantic similarity,
  • lexical match,
  • recency,
  • importance,
  • entity overlap,
  • story-thread overlap,
  • authority,
  • explicit user pinning.

The final ranking formula should be simple and inspectable.

As implemented (M6)

Ranking is cosine similarity against the retrieval query, plus an explicit pin. The other factors listed above — importance, lexical match, recency, entity overlap, story-thread overlap — are not implemented, and remain future work rather than something M6 delivered.

What M6 does implement, because similarity alone proved insufficient, is redundancy suppression before the final selection: see §22.

21. Memory Budget

Retrieved memories should have a bounded token budget.

Recommended behavior:

  • retrieve more candidates than will be used,
  • rerank locally,
  • include only the highest-value items that fit,
  • preserve source IDs for inspection.

22. Duplicate Suppression

Do not include the same fact repeatedly through:

  • current state,
  • summary,
  • memory,
  • imported canon.

If the current state already says:

Aldric possesses the silver key.

there is little value in also including three memories that say the same thing.

Context builder should prefer the highest-authority concise representation.

As implemented (M6)

Between memories, yes. Retrieval walks the ranked candidates and skips one that repeats a memory already chosen, keeping the highest-ranked statement of a fact and its provenance. Two rules bound it: authority is never crossed, so an inference can never suppress a record or the reverse; and the bar is high, set where measurement showed distinct facts stop appearing. The number of suppressed candidates is reported in the context record, so a memory that was considered and set aside can be told from one that was never eligible.

The threshold is a measured property of the embedding model in use, not a universal constant, and memorybank.REDUNDANT_SIMILARITY records the measurement beside the value.

The same measurement ruled out the more obvious test. Word overlap fires hardest on exactly the pair that must not be merged — "Mara promised to return before dawn" against "Aldric promised to return before dawn" shares most of its words and means something else — and is weakest on filler that plainly repeats itself. Wording is a poor proxy for sameness of fact.

Across layers, not yet. A fact can still appear in the authoritative state, in a memory and in recent history at once. That is bounded and legible, but it is not the "highest-authority concise representation" this section asks for, and it remains open.

23. Imported Knowledge Categories

Imported local files must be classified as:

Canon

Authoritative campaign truth.

Reference

Supporting factual/descriptive material.

Inspiration

Optional creative influence.

The classification must be visible and editable by the user.

24. Imported Canon

Imported Canon should be treated similarly to manually entered campaign canon.

Examples:

  • a setting bible,
  • technology rules,
  • faction descriptions,
  • map/location notes,
  • character bible.

Imported Canon may be retrieved selectively rather than fully included every turn.

25. Imported Reference

Reference material supports plausibility or detail.

Examples:

  • medieval medicine,
  • orbital mechanics,
  • 19th-century railroad practice,
  • astronomy notes.

It should be labeled in context as reference, not story truth.

26. Imported Inspiration

Inspiration should be optional and low-authority.

Potential behavior:

  • retrieve only when enabled,
  • use a small budget,
  • prefer scene/style relevance,
  • never allow inspiration to override canon.

27. Source Provenance

Every retrieved imported chunk should retain:

  • source file ID,
  • source title,
  • classification,
  • chunk ID,
  • retrieval score/method.

The prompt inspector should be able to show:

Reference used:
Orbital Mechanics Notes.md
Chunk 17

28. User-Pinned Knowledge

The user should eventually be able to force certain knowledge into context.

Examples:

  • always include this world rule,
  • include this character note for the next scene,
  • pin this reference document temporarily.

For v1, campaign canon rules may serve as the primary pinned mechanism.

A general pinning UI may be deferred.

29. Context Budget

The application must explicitly budget tokens.

Conceptual allocation:

System / narrator rules        fixed reserve
Campaign canon                 protected
Current state                  protected
Summary                        medium reserve
Retrieved story memories       bounded
Imported knowledge             bounded
Recent history                 elastic
Current user input             protected
Output generation reserve      protected

Exact percentages should be configurable or derived from model context size.

As implemented (M7, for imported knowledge)

The knowledge budget is a share of what is left after everything protected and the reply reserve are subtracted, and it is spent in authority order:

always-included Canon   protected. Counted with the system block, before any
                        history is chosen, and capped at 20% of the whole
                        context budget. 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. What does not fit is reported as
                        dropped, with its token cost.
retrieved knowledge     33% of what is left, filled Canon first, then Reference
                        (capped at half the knowledge budget), then Inspiration
                        (capped at a quarter). Whatever is not spent returns to
                        the story history rather than being lost.

So Reference and Inspiration cannot crowd out retrieved Canon, and none of the three can reach the current authoritative state, the reader's input, the narrator rules, critical Canon or the output reserve — all of which are priced before the knowledge budget exists.

Every included passage's token cost is in the context report, and so is every passage there was no budget for.

30. Protected vs Elastic Context

Protected

Should not be dropped casually:

  • system rules,
  • critical canon,
  • current state,
  • current user input,
  • output token reserve.

Elastic

Can be reduced when context is tight:

  • old recent-history turns,
  • lower-ranked memories,
  • reference material,
  • inspiration material,
  • verbose summaries.

31. Context Reduction Order

When the prompt is too large, recommended removal order:

  1. lowest-ranked inspiration chunks,
  2. lowest-ranked reference chunks,
  3. lowest-ranked heuristic memories,
  4. low-importance accepted memories already reflected elsewhere,
  5. oldest recent-history turns,
  6. compress or shorten summaries,
  7. trim noncritical state detail.

Do not drop:

  • critical narrator rules,
  • hard campaign canon needed for the scene,
  • current user input,
  • core current state.

32. Output Reserve

The context builder must leave space for narrator output.

It should not fill the entire model context window with input.

Recommended behavior:

  • reserve a configurable maximum response budget,
  • add safety margin,
  • fail gracefully if protected context alone is too large.

As implemented (M6)

context_token_budget is the whole window, so the reply is subtracted from it before any history is selected:

available for history = context_token_budget
                      - (system, canon, state, summary, memories, user input)
                      - (max_output_tokens + 64)

The 64-token margin covers the separators added after budgeting and the drift between the app's tokenizer and the serving model's; it is fixed rather than proportional because what it absorbs does not scale with the budget.

When the protected part alone does not fit, build_context raises ContextOverflow naming both figures and what to change, and the turn reports that as a failed turn. It does not build a prompt it knows will overflow.

Before M6 nothing was reserved: the builder spent the entire budget on input and left the reply to fit in whatever the endpoint had left.

33. Context Snapshot

Every narrator generation should preserve enough information to reconstruct the effective prompt.

At minimum record:

  • context component IDs,
  • rendered text or reproducible form,
  • token counts,
  • ranking scores,
  • model/settings,
  • active branch/head.

This allows debugging.

34. Prompt Inspector

The UI should eventually allow the user to inspect:

  • narrator rules,
  • current state,
  • summary,
  • retrieved memories,
  • imported knowledge,
  • recent history,
  • total token usage.

This is particularly important when the narrator behaves unexpectedly.

35. User Override

The user should be able to manually correct context-driving data.

Examples:

  • fix canon,
  • disable a bad memory,
  • disable a knowledge source,
  • correct a character record,
  • mark a heuristic memory as wrong.

The system should not force the user to manipulate raw embeddings or SQL.

36. Memory Correction

If a stored memory is wrong:

Potential actions:

  • delete/disable memory,
  • downgrade authority,
  • correct text,
  • replace with authoritative fact.

Corrections should preserve provenance when practical.

37. Memory vs Fact

Important distinction:

Fact

Structured authoritative assertion.

Memory

Retrievable narrative representation.

Example:

Fact:

Mara knows the location of the key.

Memory:

During the tavern conversation, Aldric accidentally revealed where the key was hidden.

The memory may provide richer narrative context.

The fact provides concise state authority.

38. Memory vs Summary

Summary

Broad compression of a range of story history.

Memory

Specific retrievable detail.

They solve different problems and should coexist.

39. Memory vs Imported Knowledge

Story Memory

Comes from this campaign's accepted history.

Imported Knowledge

Comes from user-supplied local material.

Story memory must be lineage-aware.

Imported knowledge is normally campaign-wide and not branch-specific.

40. Knowledge Retrieval Query

Imported-knowledge retrieval may use:

  • current scene,
  • entities,
  • user input,
  • active story threads,
  • campaign genre/profile.

Example:

Scene:

The crew is approaching Europa.

Potential reference retrieval:

  • radiation environment,
  • orbital dynamics,
  • ice crust,
  • local campaign technology rules.

41. Canon Retrieval

Canonical material should not rely solely on similarity search.

Critical canon rules may need:

  • always-on inclusion,
  • entity-linked retrieval,
  • tag-based retrieval,
  • explicit rule triggers.

Example:

FTL does not exist.

This should not disappear just because the current user input does not semantically resemble "FTL".

As implemented (M7)

A Canon source may be marked always_include. Its passages are supplied on every turn whatever the scene is, in their own protected section framed as standing rules of the world. The flag is Canon's alone — it bypasses relevance entirely, and asserting unranked Reference on every turn would spend a protected budget on material that establishes nothing — and it is enforced both ways: a source reclassified away from Canon loses the flag.

Always-included Canon does not set the relevance floor for the passages that had to earn their place, because it did not earn its own; letting it do so would let one standing rule silence everything the scene actually turned up.

Entity-linked and tag-based retrieval are not implemented. Entity names do reach the query — it is built partly from the authoritative state, so the characters and places in play are among the search terms — but there is no explicit link from a source to an entity, and no tags. Deferred.

42. Global Canon

Some canon should always be active.

Examples:

  • setting era,
  • hard technology constraints,
  • magic existence/nonexistence,
  • narrator/player-control rules,
  • protagonist identity.

Global canon should remain small.

43. Conditional Canon

Other canon may be retrieved when relevant.

Examples:

  • details of a distant city,
  • a faction's internal structure,
  • a specific ship subsystem,
  • an NPC's background.

44. Character Knowledge

Potential future refinement:

The narrator may need to distinguish:

  • objective world truth,
  • what the protagonist knows,
  • what an NPC knows.

This is useful for secrets and mystery stories.

For v1, support at least:

  • objective canon/state,
  • optional knows relationships/facts where important.

A full separate-mind simulation like Sonder Engine is not required.

45. Secrets

Secrets should not automatically be shown to the player-facing prose merely because they exist in authoritative state.

The narrator can know secrets necessary to run the story.

The prompt architecture may need separate labels such as:

GM-only canon
player-known facts
character-known facts

This should be considered in v1 if the selected base supports it cheaply.

46. Spoiler-Safe Context

The application must distinguish:

narrator knowledge

from:

text that should be revealed to the user.

The narrator may receive hidden information while being instructed not to reveal it until narratively appropriate.

This is a prompt discipline requirement.

As implemented (M7)

Source-level, and treated as prompt discipline exactly as this section says. A source marked hidden is retrieved and supplied to the narrator like any other, and two things mark it: the passage itself carries [narrator only] on its provenance line, and the knowledge rule in the system block says what that means — the protagonist does not know it, must not be told it, must not act on it, and a direct question about it is answered from what the protagonist actually knows.

The marker travels on the passage rather than only in the preamble because a passage is read where it sits. Per-chunk visibility is deferred (§69 of IMPORTED-KNOWLEDGE-DESIGN.md asks only for source level in v1).

"Hidden" is about the protagonist, not about the person running the campaign: the source is fully readable in the knowledge panel.

47. Story Style Memory

Some user preferences may be durable within a campaign:

  • preferred prose length,
  • dialogue density,
  • violence level,
  • descriptive richness,
  • pacing,
  • point of view.

These should live in campaign configuration rather than be inferred repeatedly from history.

48. Temporary Direction

User out-of-character direction may be:

  • one-turn only,
  • scene-level,
  • durable campaign guidance.

The UI should eventually distinguish these.

Example:

For this scene, keep the pacing tense and fast.

should not necessarily become permanent campaign canon.

49. Memory Extraction Timing

Possible strategies:

Every turn

Simple but potentially expensive.

Threshold/batch

Extract after several turns.

Selective

Only when state extractor flags something important.

Recommended initial approach:

Reuse the selected base's proven mechanism if it is local and correct; otherwise perform lightweight extraction after each accepted turn and allow later optimization.

50. Summary Generation Timing

Possible triggers:

  • token threshold,
  • number of turns,
  • scene/chapter boundary,
  • manual request.

Recommended:

  • automatic token/turn threshold,
  • preserve source lineage.

51. Failure Handling

If memory extraction fails:

  • accepted story turn remains valid,
  • no corrupted memory should be stored,
  • retry can occur later.

If summary generation fails:

  • story continues,
  • older direct history may temporarily remain longer,
  • failure must not corrupt authoritative state.

If embedding generation fails:

  • lexical retrieval should remain possible if implemented.

Derived-memory failures must not block story persistence.

52. Offline Operation

All context and memory operations must work locally.

Permitted v1 data flow:

Local browser
  -> local application
  -> local SQLite/files
  -> local Ollama

No:

  • remote vector DB,
  • remote embedding API,
  • cloud search,
  • automatic web retrieval.

53. Context Construction Example

User input:

I ask Mara whether she recognizes the symbol on the key.

Possible assembled context:

SYSTEM
You are the narrator...
Do not override canon...

GLOBAL CANON
Magic is rare.
The dead cannot be resurrected.

CURRENT STATE
Location: Crooked Lantern Tavern
Aldric possesses the silver key.
Mara is present.
Mara trusts Aldric cautiously.

STORY SUMMARY
Aldric is searching for Edrin...

RELEVANT STORY MEMORIES
[Accepted event] Turn 38: Edrin's desk contained the silver key.
[Accepted discovery] Turn 51: The key bears a symbol matching the abbey crypt.
[Heuristic] Mara appeared uneasy when the abbey was mentioned.

REFERENCE
Source: Abbey Notes.md
The symbol is historically associated with...

RECENT HISTORY
...

USER
I ask Mara whether she recognizes the symbol on the key.

54. Context Construction Example — Science Fiction

User:

Can the Persephone reach Europa before the storm hits?

Context:

GLOBAL CANON
FTL does not exist.
Persephone uses a fusion torch drive.

CURRENT STATE
Persephone is departing Ceres Station.
Fuel reserve: established as limited.
Crew has detected a radiation storm.

REFERENCE
Orbital Mechanics.md
Relevant local transfer notes...

STORY MEMORY
Turn 112: Chief Engineer stated maximum sustained acceleration...

RECENT HISTORY
...

USER
Can the Persephone reach Europa before the storm hits?

55. What Should Not Be Sent

Avoid routinely sending:

  • entire campaign transcript,
  • all entities,
  • all imported documents,
  • abandoned branch memories,
  • irrelevant character biographies,
  • duplicate facts,
  • old low-value heuristics,
  • raw embeddings,
  • internal database metadata not useful to narration.

56. Context Debugging

If the narrator makes an unexpected choice, the system should support questions such as:

  • Which memory caused this?
  • Which canon rule was present?
  • Was the relevant fact omitted?
  • Did an abandoned branch leak in?
  • Did an inspiration passage overpower canon?
  • Was the recent-history window too short?

This is why context provenance is a first-class requirement.

57. Phase 0B Findings Applied

The selected AI-DnD base was exercised with real local Ollama embeddings and demonstrated useful lineage behavior:

  • branch-scoped memory retrieval worked,
  • a memory from a later/abandoned depth was excluded after moving the active head backward,
  • the same memory became eligible again after Redo/return to the applicable lineage,
  • switching to a different branch prevented abandoned-branch terms from appearing in the assembled prompt,
  • the context/Insights path exposes labeled prompt sections and token costs.

Planning consequences:

  1. Preserve AI-DnD's common lineage filtering/chokepoint rather than replacing memory from scratch.
  2. Make summaries explicitly lineage/turn-range anchored; never rely on a positional message watermark.
  3. Keep accepted story memory distinct from heuristic/inferred memory.
  4. Imported knowledge remains a separate subsystem; do not promote Story Cards into the knowledge store merely because they are prompt-injection primitives.
  5. Use local Ollama embeddings for semantic story memory where enabled; retain a lexical/deterministic path for imported knowledge.
  6. Context/state extraction must be tested at realistic prompt length because Phase 0B showed model protocol adherence can degrade under full application context.
  7. Derived memory/summary failure must not corrupt or roll back an otherwise valid authoritative story commit.

58. Acceptance Criteria

The final implementation must satisfy:

  • full campaign history remains stored even when not in context,
  • only active-lineage story history influences the narrator,
  • campaign canon outranks all other context,
  • accepted story facts outrank heuristic memory,
  • reference material cannot override canon,
  • inspiration cannot silently become canon,
  • old important events can be retrieved beyond the recent-history window,
  • retrieval works locally,
  • no remote embeddings/search are required,
  • abandoned branch memories do not leak,
  • moving the active head backward excludes memories derived after that head,
  • Redo/returning to the valid lineage can make those memories eligible again,
  • context remains bounded,
  • output space is reserved,
  • prompt composition is inspectable,
  • retrieved sources retain provenance,
  • summaries are lineage-safe,
  • memory failures do not corrupt authoritative story state.

59. Selected Context / Memory Design

Use a layered, authority-aware context builder:

                 PROTECTED
                    |
                    v
          System / Narrator Rules
                    +
              Global Canon
                    +
             Current State
                    |
                    v
            ----------------
                    +
       Lineage-Anchored Summary
                    +
       Relevant Story Memories
                    +
       Relevant Local Knowledge
                    +
       Recent Active-Lineage Turns
                    +
             Current Input
                    |
                    v
                 OLLAMA

Retrieval must be:

local
+ lineage-aware where derived from story history
+ provenance-preserving
+ authority-aware
+ token-bounded

The application treats context construction as a deterministic, independently testable subsystem. AI-DnD's lineage-aware memory implementation is the starting point; the project's own authority and imported-knowledge rules define the target behavior.