Aligns the inherited AI-DnD memory and context foundation with the history,
authority and state model M3-M5 established. Long stories now reach the narrator
through a bounded, lineage-safe, inspectable context rather than a growing
transcript.
This commit includes the corrective work that followed the independent review in
planning/reports/M6-IMPLEMENTATION-REPORT.md. The first implementation reported
E03 as passing and it was not; the report records that history rather than
hiding it.
What was already correct, and was kept rather than rebuilt
Memory lineage. Memories already carried (branch_id, depth) and retrieval
already filtered through the capped-path clause; the ten-step negative control
was measured passing against b7005e6 before any change here. M6 adds the
regression tests that pin it, plus provenance and authority on the result.
Summary lineage — both halves
A summary is a row carrying the coordinate of the last node it covers, and
eligibility is the same head-capped lineage clause memories use. That alone
was not enough: generation was seeded from adventures.story_summary, a
campaign-global column with no lineage, so after a divergence the summariser
was handed the abandoned line's prose and asked to update it. The row it
produced was correctly anchored and therefore looked safe while its sentences
described a story the reader had left.
Generation is now seeded from summaries.current — the same question the
context builder asks — so the input and the output are scoped by one rule.
adventures.story_summary remains a reader-facing mirror for the Plot panel and
the export bundle, kept in step when a summary is written and when the head
moves, and nothing authoritative reads it.
Retrieval redundancy
With a real embedding model, four near-identical memories crowded out the one
distinctive clue, which survived only because the default memory_top_k is 5.
Retrieval now drops a candidate that repeats one already chosen, never across
authority classes, at a threshold measured against the configured embedding
model. The clue is retrieved at top_k 5, 4 and 3. Ranking itself is unchanged;
the further factors CONTEXT-AND-MEMORY §20 contemplates remain unimplemented
and are recorded as such.
Memory authority, budgeting, observability
Memory.authority is accepted_story or heuristic, classified by the application
and marked in the prompt; retrieval never writes state. The reply is reserved
out of the context budget, and an impossible configuration fails clearly
instead of overflowing. Each derived pass records ok/idle/failed per campaign,
served by GET /adventures/{id}/derived and shown in Insights, so the M2
failure — a dead memory bank with a green suite — is visible if it recurs.
Provider-wiring tests mock no factory.
Also: two pre-existing test-suite leaks fixed; two fixtures that stored one
vector in every memory now use distinct ones, so lineage assertions stay
readable alongside redundancy suppression.
Planning: CONTEXT-AND-MEMORY, TECHNICAL-DESIGN, DATA-MODEL, V1-ACCEPTANCE-TESTS,
BUILD-MILESTONES, VERSION and planning/README updated to describe what exists,
including that a valid E03 test must regenerate a summary after diverging. The
M5 report was rotated to planning/archive/milestone-reports/. No new ADR — every
choice implements a decision the package had already settled.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PWU4gTfLYY6Qq9U7aa9Qw2
32 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.
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:
- lowest-ranked inspiration chunks,
- lowest-ranked reference chunks,
- lowest-ranked heuristic memories,
- low-importance accepted memories already reflected elsewhere,
- oldest recent-history turns,
- compress or shorten summaries,
- 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".
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
knowsrelationships/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.
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:
- Preserve AI-DnD's common lineage filtering/chokepoint rather than replacing memory from scratch.
- Make summaries explicitly lineage/turn-range anchored; never rely on a positional message watermark.
- Keep accepted story memory distinct from heuristic/inferred memory.
- Imported knowledge remains a separate subsystem; do not promote Story Cards into the knowledge store merely because they are prompt-injection primitives.
- Use local Ollama embeddings for semantic story memory where enabled; retain a lexical/deterministic path for imported knowledge.
- Context/state extraction must be tested at realistic prompt length because Phase 0B showed model protocol adherence can degrade under full application context.
- 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.