Journal
Status: Phase 1 shipped (2026-05-23). Phase 1.1 review fixes landed 2026-05-25 — multi-instance regen lock, single MaxEntries cap, REST status codes, GET /journal fan-out parallelized, fire-and-forget bound to host shutdown, /regenerate rate-limited, parser truncation salvage, configurable MaxEvalTokens, category persistence. See "Phase 1.1 — what landed" below. The Living Lorebook (Cast & places, save to a lorebook, continue with this cast, make a character) has shipped since, in October 2026: see its note under Living Lorebook. Phase 0 trust hardening landed 2026-08-08 (from docs-internal/archive/completed-audits/chat-engine/JOURNAL_FEATURE_REVIEW_2026-08-08.md): strict eval no-op contract, on-summary covered-window eval, human-edit authority, unique regen-lock tokens + lease renewal, staged/atomic regeneration, content-free logging — see "Phase 0 hardening — what landed". Run ledger + honest activity status (JRN-09) and index alignment (JRN-15) landed 2026-08-10 (63fe18e4); the Story State surface — header/phone-chip/Who-drawer entry points and the task-first editor (JRN-12/13, Slice A) — shipped 2026-08-12 (42fc37c4), spec and verification in docs-internal/archive/delivered/chat-engine/JOURNAL_SLICE_A_SURFACE.md. Phase 2+ planned — see "Out of Phase 1".
Overview
The Journal is an always-on persistent context system that maintains structured state about the ongoing story. Unlike memories (past events recalled by search) or lorebooks (static reference data matched by relevance), the journal tracks living state that is always injected into the prompt.
More importantly, the journal is a living lorebook -- it doesn't just track one-liner state, it extracts and evolves full character cards, location profiles, and world knowledge directly from the narrative. Characters you meet get auto-generated profiles that grow richer over time. Locations you visit accumulate detail. The journal essentially writes its own lorebook entries from what happens in the story, and these entries can be materialized into actual lorebook entries for reuse across conversations.
Three layers:
| Layer | What it tracks | Scope | Example |
|---|---|---|---|
| State Facts | Basic ongoing truths | Conversation-wide | "The party is on a quest to find the Crystal of Dawn" |
| Character Progressions | Full evolving character profiles | Per-NPC / per-character | Elara: appearance, personality, abilities, relationship to player, history of interactions |
| Location Progressions | Full evolving location profiles | Per-location | Shadowkeep: description, layout, hazards, inhabitants, what the party has done there |
All journal content is always included in the prompt (not search-gated), making it the system of record for "what is true right now."
Problem
Current gaps
Memories are episodic and search-based. They capture what happened, but:
- Not always recalled (depends on search relevance to current message)
- No structured organization (flat list of recalled events)
- No distinction between "still true" and "historical" -- a memory of "the party entered Shadowkeep" doesn't tell the AI whether they're still there
Facts (Discord-only, not implemented for web) are user-level, not story-level:
- Tied to Discord users, not conversation narratives
- No character-specific or location-specific structure
- Not automatically updated from the narrative
Trackers (proposed) handle discrete named values but not narrative-level state:
- Good for "HP: 72" or "Time: Day 3"
- Not suited for "Elara's opinion of the player has shifted from suspicion to grudging respect after the events at the bridge"
Lorebooks are static reference data created upfront by the character creator:
- Don't grow or evolve from the narrative
- A lorebook entry for "Elara" contains what the creator wrote, not what happened in your conversation
- NPCs the story invents on the fly (the tavern keeper, the goblin chieftain) have no lorebook entries at all
What's needed
A system that automatically builds and evolves structured knowledge from the narrative -- character profiles that grow richer as you interact, location entries that accumulate detail as you explore, and the ability to graduate this living knowledge into reusable lorebook entries.
Proposed Design
Journal Structure
Journal (per conversation)
├── State Facts
│ ├── "The party is searching for the Crystal of Dawn"
│ ├── "Current party: Player, Elara (ranger), Grimjaw (dwarf)"
│ └── "The Shadow King's forces are gathering in the north"
│
├── Character Profiles (living character cards)
│ ├── Elara
│ │ ├── Profile: { appearance, personality, abilities, role, secrets... }
│ │ ├── Relationship: "Trusted companion after cave rescue"
│ │ └── History: ["Initially suspicious", "Bridge battle", "Cave rescue", ...]
│ ├── Grimjaw
│ │ ├── Profile: { gruff dwarf, twin axes, searching for brother... }
│ │ ├── Relationship: "Loyal, hired for gold but stays out of duty"
│ │ └── History: ["Met at tavern", ...]
│ └── The Shadow King
│ ├── Profile: { ancient lich, commands undead, rules Shadowkeep... }
│ ├── Relationship: "Unknown antagonist"
│ └── History: ["First mentioned by village elder", ...]
│
└── Location Profiles (living location cards)
├── Shadowkeep
│ ├── Profile: { five-floor dungeon, dwarven-built, now undead-infested... }
│ ├── State: "Floors 1-3 explored, bridge on 2 destroyed, boss on 5 undefeated"
│ └── History: ["Entered through secret passage", "Cleared floor 1", ...]
├── Millhaven Village
│ ├── Profile: { small farming village, friendly elder, near forest... }
│ ├── State: "Safe, allied. Elder owes a favor."
│ └── History: ["Arrived seeking info", "Defended from wolves", ...]
└── The Northern Pass
├── Profile: { mountain pass, only route north, rumored dangerous... }
├── State: "Unexplored"
└── History: ["Mentioned by Grimjaw", ...]
State Facts
Simple declarative statements about the current story state. Always injected.
JournalFact
├── ConversationId
├── Content "The party is searching for the Crystal of Dawn"
├── Category "quest" | "party" | "world" | custom
├── IsActive true (false = historical, not injected but preserved)
├── CreatedAt
└── UpdatedAt
Key behavior:
- Always in context (not search-gated)
- Can be marked inactive when no longer true (replaced by updated fact)
- Limited count to manage token budget (e.g., max 10-15 active facts)
- Updated by the AI or manually by the user
Character Profiles (Living Character Cards)
Character profiles are auto-generated and continuously evolving character cards built from the narrative. When the AI introduces an NPC, the evaluation call extracts everything it can about that character and creates a profile. As the story progresses and reveals more, the profile grows richer.
JournalCharacterProfile
├── ConversationId
├── CharacterName "Elara"
├── Aliases ["the ranger", "Princess Elara", "the Lightbringer"]
├── ProfileJson Structured character data (see below)
├── RelationshipState "Trusted companion after cave rescue"
├── Entries[] Progression history
│ ├── Content "Grudging respect after bridge battle"
│ ├── CreatedAt
│ └── MessageId (which message triggered this update)
├── IsActive true
├── CreatedAt
└── UpdatedAt
ProfileJson structure (grows over time):
{
"appearance": "Tall, lean build. Dark hair kept short. Wears green ranger's cloak, carries an oak longbow.",
"personality": "Distrustful of outsiders but fiercely loyal once trust is earned. Dry sense of humor. Hates confined spaces.",
"abilities": "Expert tracker and archer. Knows herb lore. Can speak with birds.",
"role": "Ranger, party scout",
"background": "From the Northern Reaches. Exiled princess (secret).",
"goals": "Find the Crystal of Dawn to lift the curse on her homeland.",
"secrets": "She is the exiled princess of the Northern Reaches.",
"notable_items": "Oak longbow (named 'Whisper'), silver locket"
}
Not every field exists from the start. When Elara is first mentioned, the profile might only have:
{
"appearance": "A ranger in a green cloak",
"role": "Suspicious stranger at the tavern"
}
Over 20 messages of interaction, the evaluation call fills in personality, abilities, background, and secrets as the narrative reveals them. The profile is always the latest, most complete picture of who this character is.
Key behavior:
ProfileJson+RelationshipStateare always injected (the AI's working knowledge of this NPC)Entriesare the progression history, NOT always injected (too verbose)- History available for recall and for tracking how the relationship evolved
- Aliases help the evaluation call recognize the same character across name variations
- Profile fields are additive -- new information enriches existing fields, doesn't replace unless contradicted
Location Profiles (Living Location Cards)
Same pattern for locations. When the party arrives somewhere, the evaluation call creates a location profile from what the narrative describes. As they explore, the profile grows.
JournalLocationProfile
├── ConversationId
├── LocationName "Shadowkeep"
├── Aliases ["the dungeon", "the ancient fortress"]
├── ProfileJson Structured location data (see below)
├── CurrentState "Floors 1-3 explored, bridge on 2 destroyed"
├── Entries[] Progression history
│ ├── Content "Cleared floor 1 goblins"
│ ├── CreatedAt
│ └── MessageId
├── IsActive true
├── CreatedAt
└── UpdatedAt
ProfileJson structure:
{
"description": "A crumbling five-floor dungeon carved into the mountainside. Built by ancient dwarves, now overrun by undead and goblins.",
"layout": "Five descending levels. Level 1: entry hall and goblin warrens. Level 2: collapsed bridge over chasm. Level 3: fungal gardens.",
"hazards": "Unstable stonework, goblin patrols, undead on lower floors",
"inhabitants": "Goblins (floors 1-3), undead (floors 4-5), The Shadow King (floor 5 boss)",
"notable_features": "Ancient dwarven murals on level 1, underground river on level 3",
"resources": "Healing mushrooms in fungal gardens, dwarven weapon cache on level 2"
}
Key behavior:
ProfileJson+CurrentStatealways injected- Profile builds as the party explores and the narrative describes new details
CurrentStatetracks what the party has done (explored, destroyed, unlocked) -- mutable per-conversation stateProfileJsontracks what the location IS (description, layout, features) -- accumulates from narrative
Prompt Injection
New Provider Key: "journal"
Provider output example:
## Story Journal
### Current State
- The party is searching for the Crystal of Dawn
- Current party: Player, Elara (ranger), Grimjaw (dwarf fighter)
- The Shadow King's forces are gathering in the north
### Characters
**Elara** (the ranger)
Appearance: Tall, lean build. Dark hair kept short. Green ranger's cloak, oak longbow 'Whisper'.
Personality: Distrustful of outsiders, fiercely loyal once trust earned. Dry humor. Claustrophobic.
Abilities: Expert tracker/archer. Herb lore. Can speak with birds.
Background: Exiled princess of the Northern Reaches (revealed during cave rescue).
Relationship: Trusted companion after cave rescue.
**Grimjaw** (the dwarf)
Appearance: Stocky, heavily scarred. Braided beard. Twin hand-axes.
Personality: Gruff exterior, secretly sentimental. Protective of the party.
Abilities: Veteran fighter. Knows dwarven history and stonework.
Background: Searching for his brother who vanished in Shadowkeep.
Relationship: Loyal, hired for gold but stays out of duty now.
### Locations
**Shadowkeep**
Description: Five-floor dungeon carved into the mountainside. Dwarven-built, now overrun by undead and goblins.
Layout: L1 entry/goblins, L2 collapsed bridge, L3 fungal gardens, L4-5 undead/boss.
State: Floors 1-3 explored. Bridge on L2 destroyed. Boss on L5 undefeated.
**Millhaven Village**
Description: Small farming village near the forest edge. Friendly elder Brenn.
State: Safe, allied. Elder owes a favor.
Maintain consistency with these established facts and character profiles.
Token budget: Journal content is always injected, so it must stay concise. The system enforces:
- State facts: limited to N active facts (configurable, default ~10)
- Character profiles: compact format, key fields only (not full prose paragraphs)
- Location profiles: compact format, description + current state
- Total journal injection has a soft token cap (configurable)
- When budget is tight, profiles are compressed (drop least-relevant fields first: secrets, background, notable_items)
Update Mechanism
Journal updates can happen through:
1. Evaluation LLM call (primary mechanism)
After each AI response, a separate LLM call (shared with tracker evaluation) identifies state changes:
- New character encountered? Add a character progression.
- Location changed? Update location state.
- Quest milestone? Update relevant state fact.
The story LLM is never asked to produce structured journal output -- it writes pure narrative. The evaluation call runs async after the response streams to the user, using the same TrackerLlm config (cheap/fast model). Since tracker evaluation and journal evaluation both analyze the same AI response, they can share a single evaluation call that extracts both tracker updates and journal changes in one pass.
2. Summarization hook
When conversation summarization runs, the summary output includes journal updates. The summarization prompt asks the LLM to identify what changed during the summarized segment:
Based on the events summarized:
- Which state facts have changed?
- How have character relationships evolved?
- What location states were affected?
This is a natural fit since summarization already processes narrative content.
2a. Scene-Aware Summarization (future enhancement)
The current summarization system triggers based on message count (e.g., every 30 unsummarized messages). This is a poor fit for storytelling -- a fixed window may split a scene in half, creating a memory that covers the first half of a battle and another that covers the second half. Memories should ideally correspond to scenes: coherent narrative units with a beginning, middle, and end.
Scene transition detection via the evaluation call:
Since the tracker/journal evaluation call already analyzes every AI response, it can also detect scene transitions -- moments where the narrative context shifts significantly:
- Location change (party moves from tavern to forest)
- Time skip ("the next morning...", "three days later...")
- Major cast change (half the party leaves, new group arrives)
- Narrative break (flashback ends, dream sequence, chapter boundary)
The evaluation call would output a scene_transition flag alongside its normal tracker/journal extractions:
{
"tracker_updates": { ... },
"journal_updates": { ... },
"scene_transition": {
"detected": true,
"type": "location_change",
"from": "The Rusty Anchor tavern",
"to": "The northern forest road",
"note": "Party departed after receiving the map"
}
}
How this changes summarization:
Instead of summarizing every N messages, the summarization system would summarize per scene:
- Evaluation call detects a scene transition
- All messages from the previous scene boundary to now are grouped as one scene
- Summarization runs on that scene as a coherent unit
- The resulting memory is a complete scene summary ("At the Rusty Anchor, the party met Grimjaw, negotiated payment, and received the map to Shadowkeep")
Fallback: If no scene transition is detected for a long stretch (e.g., 40+ messages in one continuous scene), the system falls back to the current message-count-based summarization to prevent unbounded context growth.
Why this matters for memories: Scene-aligned memories are dramatically more useful for semantic recall. A memory of "the tavern scene" is a coherent, searchable unit. A memory of "messages 31-40" that happens to split across two locations produces fragmented, harder-to-recall context.
Status: This depends on the tracker evaluation call being implemented first. Scene detection would be an additional output from that same evaluation pass, requiring no extra LLM calls.
3. Manual user edits
Users can directly add, edit, or deactivate journal entries through the UI. This serves as a correction mechanism when the AI misinterprets events, and lets users seed the journal at conversation start.
Evaluation Prompt: Creator Control
The journal evaluation prompt is creator-configurable, not one-size-fits-all. Different creators have different expectations for how aggressively the journal extracts and evolves profiles:
- Aggressive extraction: A world-building creator wants full character cards from the first mention.
"Extract every detail: appearance, personality, motivations, speech patterns. Infer what you can from context." - Conservative extraction: A casual roleplay creator wants only what's explicitly stated.
"Only record details directly stated in the narrative. Do not infer or extrapolate." - Relationship-focused: A romance/drama creator cares most about relationship dynamics.
"Prioritize relationship state and emotional reactions. Track how characters feel about each other above physical details."
Creator testing UI:
Since every journal update records its source_message_id, creators can test and iterate on their evaluation prompts:
- Regenerate from message: Select a message and re-run the journal evaluation against it. See what profiles/facts would be extracted with the current prompt.
- Batch test: Run evaluation across a range of messages to see how profiles evolve. Useful for verifying that the extraction prompt produces the right level of detail across a full conversation.
- A/B evaluation: Compare two extraction prompts against the same message to see which produces better profiles.
- Profile preview: Show a "before/after" of what the profile looked like before and after a given message's evaluation, so creators can see exactly what each response contributes.
This follows the same pattern as tracker evaluation testing and the existing memory regeneration system.
Relationship to Other Systems
Journal vs. Memories
| Journal | Memories | |
|---|---|---|
| Content | Current state | Past events |
| Injection | Always on | Search-based recall |
| Structure | Categorized (facts, characters, locations) | Flat episodes |
| Mutability | Updated as state changes | Immutable once created |
| Source | AI extraction + user edits | Summarization pipeline |
They complement each other. The journal says "Elara trusts the player." Memories say "In session 3, Elara and the player survived the cave collapse together." The journal is the conclusion; memories are the evidence. Fuzzy time search can surface the right memories when users ask temporal questions ("when did Elara start trusting us?"), connecting the journal's current state back to the memories that explain it.
Journal vs. Trackers
| Journal | Trackers | |
|---|---|---|
| Values | Narrative prose | Discrete named values |
| Format | Sentences/paragraphs | Key: value |
| Examples | "Elara has warmed up considerably" | relationship_elara: 7/10 |
| Best for | Qualitative state | Quantitative state |
They can coexist. Trackers handle the mechanical (HP: 72, Time: Day 3), journal handles the narrative ("Party morale is low after the ambush").
Journal vs. Lorebooks
| Journal | Lorebooks | |
|---|---|---|
| Content | Mutable, narrative-extracted | Static, creator-authored |
| Scope | Per-conversation | Per-character/shared |
| Injection | Always on (active profiles) | Relevance-searched |
| Source | Auto-generated from story | Manually created upfront |
| Growth | Evolves every message | Fixed until creator edits |
Lorebooks define the world the creator built ("Shadowkeep is a five-floor dungeon built by the ancient dwarves"). Journal captures what the story creates ("The tavern keeper Marta is a retired adventurer who lost her left hand to a dragon" -- a character the AI invented on the fly, now permanently tracked).
The journal fills the gap lorebooks can't: Lorebooks only know what the creator wrote. The journal knows what happened. For characters the AI invents, locations the story discovers, and facts the narrative establishes, the journal is the only source of structured knowledge.
Living Lorebook
The journal's most powerful capability: it is a self-writing lorebook that extracts, structures, and evolves world knowledge directly from the narrative.
How It Works
Auto-extraction: The evaluation LLM call analyzes each AI response and extracts structured data into character/location profiles. No creator input needed.
Progressive enrichment: Profiles start sparse and grow rich. First mention of an NPC might yield just a name and role. After 10 interactions, the profile has appearance, personality, abilities, secrets, and a full relationship arc.
Consistency enforcement: Because profiles are always injected, the AI stays consistent with established facts. If the journal says Elara has dark hair, the AI won't suddenly describe her as blonde. The journal is the AI's persistent memory of what it established.
User editability: The LLM will make mistakes -- wrong details, missed changes, merged characters that shouldn't be merged. Every auto-generated field is directly editable by the user. User edits take precedence over future evaluation updates (see Design Principles: User Editability).
Error transparency: When the evaluation call returns unparseable JSON, the raw response is preserved and the user is notified so they can manually apply the intended changes (see Design Principles: Error Handling).
Full lorebook generation: Journal profiles can be materialized into actual lorebook entries -- creating a real, searchable lorebook from the story's emergent content.
Profile Evolution Example
Message 3: "A ranger in a green cloak watches you from across the tavern."
{
"name": "Unknown Ranger",
"appearance": "Wears a green cloak",
"role": "Mysterious observer at tavern"
}
Message 8: "'I'm Elara,' she says, reluctantly extending her hand. 'I track things. People, mostly. You've been making noise since you arrived.'"
{
"name": "Elara",
"aliases": ["the ranger"],
"appearance": "Wears a green cloak",
"personality": "Reluctant, guarded, direct",
"abilities": "Tracking",
"role": "Ranger, potential ally"
}
Message 20: The cave rescue scene reveals more about her...
{
"name": "Elara",
"aliases": ["the ranger", "Princess Elara"],
"appearance": "Tall, lean build. Dark hair kept short. Green ranger's cloak, oak longbow named 'Whisper'.",
"personality": "Distrustful of outsiders but fiercely loyal once trust is earned. Dry humor. Claustrophobic.",
"abilities": "Expert tracker and archer. Herb lore. Can speak with birds.",
"background": "From the Northern Reaches. Exiled princess (revealed during cave rescue).",
"role": "Trusted companion, party scout",
"goals": "Lift the curse on her homeland",
"secrets": "Her exile was voluntary -- she chose to leave rather than marry the Shadow King's emissary.",
"notable_items": "Oak longbow 'Whisper', silver locket with portrait of her mother"
}
Each evaluation call updates only what changed or was newly revealed. The profile accumulates, never loses established facts.
Materialization: Journal → Lorebook
Users can materialize journal profiles into actual lorebook entries:
Per-entry materialization:
- Click "Save to Lorebook" on any character or location profile
- Creates a lorebook entry with the profile content, auto-generated keywords (name + aliases), and proper formatting
- The lorebook entry is a snapshot -- the journal profile continues evolving independently
Bulk materialization:
- "Export Journal as Lorebook" creates a full lorebook from all active profiles
- Generates one entry per character, one per location, plus state facts as an "Overview" entry
- Keywords auto-populated from names, aliases, and key terms
Use cases:
- Reuse across conversations: Materialize NPCs from one conversation into a lorebook. Start a new conversation with the same character, attach the lorebook, and those NPCs exist in the new story with their established profiles.
- Share emergent content: A user plays a long campaign, the journal builds a rich NPC directory and location guide. They materialize it into a lorebook and share it publicly -- other users can use this organically-grown world-building.
- Creator tools: Play through your own character's scenarios. The journal auto-builds NPC and location lorebooks from the narrative. Review, edit, publish. The story writes the lorebook for you.
- Character card extraction: An NPC the AI invented turns out to be compelling. Materialize their journal profile into a full character card (system prompt + personality + description). The journal has already extracted everything needed.
Interaction with Tracker-Driven Search
Journal profiles work with the roster tracker:
Roster tracker: ["Elara", "Grimjaw"]
↓
Tracker-aware search pulls lorebook entries for Elara and Grimjaw
↓
Journal profiles for Elara and Grimjaw are ALSO always injected
Result: AI has BOTH:
- Static lorebook data (creator-authored, via tracker search)
- Living journal profile (narrative-extracted, always-on)
When both exist for the same character, they complement each other. The lorebook entry has the creator's canonical definition. The journal profile has what actually happened in this conversation. The AI sees both.
When NO lorebook entry exists (AI-invented NPC), the journal profile is the only source. This is the key value -- characters the story creates on the fly get the same structured knowledge treatment as characters the creator defined upfront.
Deduplication: Base Entry Informs Journal Evaluation
When a lorebook entry exists for a character that also has a journal profile, the evaluation call needs to be aware of the canonical lorebook entry. Without this, the journal might drift from or contradict the creator's established lore.
How it works:
The evaluation prompt includes the base lorebook entry (if one exists) alongside the current journal profile, with explicit instructions:
Existing lorebook entry for "Elara" (creator-authored, canonical):
"Elara is a ranger from the Northern Reaches. Distrustful of outsiders
but fiercely loyal once trust is earned. Expert tracker and archer."
Current journal profile for "Elara" (narrative-extracted, evolving):
{ "appearance": "Green cloak, oak longbow", "personality": "Guarded, direct" }
Instructions: Build on the base entry, do not contradict it. The lorebook
entry defines who this character IS. The journal profile tracks what has
been REVEALED and what has CHANGED through the narrative. Add new details
the narrative reveals. Update relationship state. Do NOT change established
traits unless the narrative explicitly shows a change (e.g., character
development, betrayal, transformation).
Matching lorebook entries to journal profiles:
The system matches by name and aliases:
- Journal profile has
CharacterName: "Elara"andAliases: ["the ranger", "Princess Elara"] - Search bound lorebooks for entries whose keywords match any of these names
- If a match is found, include it as the "base entry" in the evaluation prompt
Conflict resolution:
- The lorebook entry is the base truth for established facts (appearance, abilities, background the creator wrote)
- The journal profile is the narrative truth for in-conversation developments (relationship changes, revealed secrets, character growth)
- If the narrative genuinely contradicts the lorebook (character development, plot twist), the journal profile can diverge -- but the evaluation should flag the contradiction, not silently overwrite
Entity Salience Scoring
Every profile tracks a salience score that determines how much detail is injected into the prompt. Salience is computed from two signals:
- Recency: How recently the entity was referenced in the conversation (exponential decay)
- Frequency: How often the entity appears across the conversation's history (total mention count)
salience = (recency_weight × recency_score) + (frequency_weight × frequency_score)
Both scores are normalized to [0,1]. The combined salience determines the entity's injection tier (see Tiered Injection Strategy).
When salience updates:
- After each evaluation call, the system updates
last_referenced_atand incrementsmention_countfor any entity the evaluation identified as present in the latest exchange - Salience is recomputed at prompt build time, not stored -- it's a function of current state
Why this matters: The journal is always-on, but context windows are finite. Without salience scoring, 15 tracked characters would all get full profiles injected, consuming thousands of tokens on NPCs the player hasn't interacted with in 50 messages. Salience ensures the token budget goes to entities that matter right now.
Incremental Extraction
The evaluation LLM call should produce diffs, not full rewrites. Each evaluation receives the current profile and outputs only what changed:
// ✓ GOOD - Evaluation output: only changed/new fields
{
"character_updates": [
{
"name": "Elara",
"changed_fields": {
"personality": "Distrustful of outsiders but fiercely loyal once trust is earned. Dry humor. Claustrophobic.",
"secrets": "Her exile was voluntary -- she chose to leave rather than marry the Shadow King's emissary."
},
"relationship_state": "Trusted companion after cave rescue",
"progression_note": "Revealed her royal heritage and the reason for her exile"
}
]
}
// ✗ BAD - Full profile rewrite every message
{
"character_updates": [
{
"name": "Elara",
"full_profile": {
"appearance": "Tall, lean build...",
"personality": "Distrustful...",
"abilities": "Expert tracker...",
// ... repeating everything unchanged
}
}
]
}
Benefits:
- Token savings: Extraction calls are cheaper when the output is just the delta
- Meaningful diffs:
profile_diff_jsoninjournal_character_entriescontains exactly what changed, making the progression timeline useful - Merge safety: Applying a diff to the existing profile is less likely to accidentally drop fields than replacing the whole object
- Conflict detection: When a diff changes a field that the user manually edited, the system can flag the conflict rather than silently overwriting
Evaluation prompt structure:
Current profile for "Elara":
{ "appearance": "...", "personality": "...", ... }
Base lorebook entry (canonical, do not contradict):
"Elara is a ranger from the Northern Reaches..."
Latest exchange:
[user message + AI response]
Output ONLY fields that changed or were newly revealed.
If nothing changed for this character, omit them entirely.
Inter-Entity Relationships
Character profiles should track relationships to other entities, not just the player. Inter-NPC dynamics are critical for narrative consistency -- "Grimjaw and Elara argue about the plan" only works if the AI knows their dynamic.
relationships_json field on character profiles:
{
"Grimjaw": "Grudging respect. Elara finds him reckless but trusts his combat instincts.",
"The Shadow King": "Deep hatred. He destroyed her homeland.",
"Millhaven Village": "Feels protective. Reminds her of home."
}
Key design decisions:
- Relationships are bidirectional in storage but independently described -- Elara's view of Grimjaw may differ from Grimjaw's view of Elara. Each profile stores its own perspective.
- Relationships can reference both characters AND locations (Elara's connection to Millhaven is narratively important)
- The evaluation call extracts relationship updates when interactions between entities are observed
- Relationships are injected only for entities in the Full injection tier (see Tiered Injection Strategy) to avoid token bloat
Relationship to relationship_state: The existing relationship_state field tracks the entity's relationship specifically to the player character. relationships_json tracks relationships to everything else. Both are maintained independently.
Tiered Injection Strategy
The journal uses entity salience to determine how much detail to inject per profile, solving the token budget problem:
| Tier | Criteria | Injected Fields | Approx Tokens |
|---|---|---|---|
| Full | In current scene (roster tracker) OR salience > 0.8 | All profile fields + relationships + current state | ~200-400 |
| Summary | Salience 0.4-0.8 (referenced recently or frequently) | Name, role, appearance, personality, relationship to player | ~80-150 |
| Minimal | Salience 0.1-0.4 (active but not recent) | Name, role | ~10-20 |
| Omitted | Salience < 0.1 or inactive | Not injected (still in DB, recoverable) | 0 |
Tier assignment flow:
1. Compute salience for all active profiles
2. Override: any entity in the roster tracker → Full tier (regardless of salience)
3. Apply tier thresholds to remaining entities
4. Calculate total token estimate
5. If over budget: demote lowest-salience entities one tier until within budget
6. Format and inject
Example prompt output with tiers:
## Story Journal
### Current State
- The party is searching for the Crystal of Dawn
- The Shadow King's forces are gathering in the north
### Characters
**Elara** (the ranger) [Full]
Appearance: Tall, lean build. Dark hair kept short. Green ranger's cloak, oak longbow 'Whisper'.
Personality: Distrustful of outsiders, fiercely loyal once trust earned. Dry humor. Claustrophobic.
Abilities: Expert tracker/archer. Herb lore. Can speak with birds.
Background: Exiled princess of the Northern Reaches (voluntary exile).
Relationship: Trusted companion after cave rescue.
Relationships: { Grimjaw: grudging respect, Shadow King: deep hatred }
**Grimjaw** (dwarf fighter) [Summary]
Appearance: Stocky, heavily scarred. Braided beard. Twin hand-axes.
Personality: Gruff exterior, secretly sentimental.
Relationship: Loyal, stays out of duty.
**The Shadow King** [Minimal]
Role: Ancient lich antagonist, commands undead from Shadowkeep.
### Locations
...
The [Full], [Summary], [Minimal] tier labels are NOT included in the actual prompt -- they're shown here for illustration only.
Settings for tier thresholds:
| Key | Default | Description |
|---|---|---|
Journal.FullTierThreshold |
0.8 |
Minimum salience for full profile injection |
Journal.SummaryTierThreshold |
0.4 |
Minimum salience for summary injection |
Journal.MinimalTierThreshold |
0.1 |
Minimum salience for minimal injection |
Journal.RecencyWeight |
0.6 |
Weight of recency vs frequency in salience |
Journal.FrequencyWeight |
0.4 |
Weight of frequency vs recency in salience |
Design Debates
Two architectural choices have outsized impact on cost, reliability, and UX. Neither has a free lunch — the tradeoffs are documented here so the eventual implementation is a deliberate pick, not a default.
Debate 1: Per-Message Evaluation vs. Per-Summarization Update
The question: when does the journal actually run its extraction pass?
Option A — Per-message evaluation. A separate eval LLM call fires after every assistant response (the model already proposed for tracker evaluation), and journal updates piggyback on the same call.
Pros:
- Profiles stay current in real time. The character the AI just introduced is in the journal before the next user message, so the very next response is already consistency-checked against it.
- Scene-transition detection (see §2a) needs a per-message signal anyway — co-locating journal extraction is free once that call exists.
- Salience scoring (recency × frequency, see §Entity Salience Scoring) wants
last_referenced_atupdated per message. Per-summarization granularity smears that signal. - The infrastructure pattern already exists in the codebase: SummarizationStageBase.cs:55-66 fires fire-and-forget post-LLM
Task.Runbackground work without blocking the stream. Journal eval would slot in as a siblingIPostLlmStageat a laterOrder.
Cons:
- Cost. One extra LLM call per turn. For a 200-message conversation, that's 200 eval calls vs. ~6 summarization-coupled calls (at default 30-message summarization windows). Even on a cheap
TrackerLlmmodel, the multiplier hurts free-tier economics. - Noise. Most messages don't change the journal — "the goblin swings, you parry" produces no character/location update. The eval call still runs, still costs tokens, still risks a bad JSON parse.
- Token bloat in the eval prompt. Per-message eval has to ship the current profile + the latest exchange. If 8 entities are tracked, that's the full living state injected into every eval — cheap model or not, those tokens add up.
- Cost. One extra LLM call per turn. For a 200-message conversation, that's 200 eval calls vs. ~6 summarization-coupled calls (at default 30-message summarization windows). Even on a cheap
Option B — Per-summarization update. Journal extraction runs only when the summarization stage fires (every N unsummarized messages, or scene-aligned per §2a). The summarization prompt itself is extended to emit journal deltas alongside the summary + keywords.
Pros:
- One call, two outputs. Summarization already reads the conversation segment and is already JSON-shaped (
SummarizationLlmService.ParseResponse). Extending its output schema is nearly free compared to a second eval call. - Naturally scene-coherent. Summarization windows already correspond (or will, once §2a lands) to narrative segments. Journal updates arrive at meaningful moments, not every message.
- Cheap. Roughly 1/30th the calls of Option A.
- One call, two outputs. Summarization already reads the conversation segment and is already JSON-shaped (
Cons:
- Latency to journal freshness. A character introduced in message 31 isn't in the journal until summarization fires at message 60 (or whenever the next window closes). For 29 messages, the AI has no structured handle on them — consistency relies entirely on the recent-history window.
- No real-time salience.
last_referenced_atandmention_countcan't be maintained at message granularity without a separate cheap pass — so the Tiered Injection Strategy loses precision. - No place for scene-transition detection. §2a requires a per-message signal. If journal extraction is per-summarization but scene detection is per-message, two separate eval paths exist anyway — the cost saving evaporates.
- Worse failure mode. A bad JSON parse on summarization loses both the summary and the journal delta for a 30-message window. Today,
ParseResponsedegrades to "treat whole response as raw summary text" on parse failure — which is fine for a summary but means no journal update for that entire window.
Recommendation: Per-message evaluation, but only when the tracker evaluation call is already running (gated behind Trackers.EvaluationEnabled). The cost argument falls apart the moment tracker eval is in place — journal extraction is then a marginal output, not an extra call. Without trackers, journal updates piggyback on summarization. The hybrid is the right default; the polemic only matters if the platform decides to ship the journal before trackers.
Debate 2: Structured Tool-Use vs. Freeform JSON Output
The question: how does the eval LLM tell us what changed?
Option A — Freeform JSON in the response body. The eval prompt instructs "output JSON with this shape", the model produces a string, the service parses it. This is what every existing JSON-shaped LLM call in the codebase does today:
SummarizationLlmService.ParseResponse— strips markdown code fences, handlessummaryas string-or-object, acceptskeywordsas strings or{keyword|name|value|text}objects, falls back to "raw text = summary" on parse failure.AI Tasks
ChatTaskRunner— same pattern. The JSON is in the message body and the runner is responsible for being forgiving.Pros:
- Works on every provider, today. Anthropic / OpenAI / Google / OpenRouter / Custom / StrictOpenAI — every
ILlmClientinCore/LLM/Providers/speaks "string in, string out". No per-provider plumbing required. - Cheap models work fine. GPT-4o-mini / Claude Haiku / Gemini Flash all produce passable JSON for simple shapes when the prompt is explicit and one-shot examples are provided.
- Graceful degradation is already a codebase pattern. A malformed response can be preserved verbatim, surfaced to the user (see §Living Lorebook step 5), and manually applied — no silent data loss.
- Easier creator testing. Eval prompts are plain strings; the creator-control UI (§Evaluation Prompt: Creator Control) can show the raw model output and let the creator see exactly what the prompt produced.
- Works on every provider, today. Anthropic / OpenAI / Google / OpenRouter / Custom / StrictOpenAI — every
Cons:
- Failure modes are real. Trailing commas, unescaped quotes inside character names ("the dwarf's brother"),
nullvs.""vs. omitted-field confusion, markdown code-fence wrappers,"Here's the JSON: { ... }"preambles. Every malformed response is either a heuristic-parser win or a dropped update. - Schema drift. Adding a new field (e.g.
relationships_json,voice_pattern) requires updating the prompt and trusting the model to use the new shape. No compile-time guarantee. - Per-field validation is post-hoc. Length caps, enum constraints (e.g.
RelationshipState ∈ {hostile,wary,neutral,friendly,loyal}), alias deduplication — all happen in C# after the parse, not at the model boundary.
- Failure modes are real. Trailing commas, unescaped quotes inside character names ("the dwarf's brother"),
Option B — Native tool/function-calling. Define update_character_profile(name, changed_fields, relationship_state, ...) as a tool the eval model can call. The provider returns a structured object the platform deserializes directly.
Pros:
- No JSON parsing. Provider SDKs hand back a typed object. Trailing commas and code-fence preambles cease to be possible.
- Schema-enforced. Required fields, enums, max-length, regex — all declarable in the tool schema. The model literally can't return a malformed
relationship_state. - Multi-update is a sequence of tool calls. "Three characters changed" becomes three discrete
update_character_profilecalls in one turn — easier to audit, easier to attribute to source messages, easier to reject one update without losing the others. - Token-cheaper at scale. No "output a JSON object with the following keys..." preamble in the prompt; the schema lives in the tool definition.
Cons:
- Not wired in this codebase. A
find tool_choice|response_format|json_schemaacrossCore/LLM/Providers/returns one hit (OpenRouter's response_format), andILlmClient.GetCompletionAsyncreturns a flatContent: string. Adopting tool-use means extending the LLM client interface, every provider implementation, andLlmRequestto carry tool definitions and surface tool-call results. That's a cross-cutting change before journal extraction can ship a line. - Provider coverage is uneven. Anthropic and OpenAI have first-class tool use. Google GenAI has function-calling but with quirks. Local / OpenRouter / Custom providers vary — some users' configured
TrackerLlmmodel might not support tool calls at all. Falling back to JSON-mode for unsupported providers means both paths have to exist. - Creator testing UX gets harder. The "show me what the eval produced" view has to render tool-call payloads, not just a string. The A/B-prompt comparison flow now compares two schemas, not two free-form outputs.
- Schema rigidity fights the "profile fields are open-ended" design. §Profile schema evolution (Open Question 6) leaves the door open to letting the AI decide which keys to extract. Strict tool schemas close that door.
- Not wired in this codebase. A
Recommendation: Freeform JSON, with the forgiveness patterns the codebase already proves out. The journal eval payload is shallow (a list of character updates, a list of location updates, a few flat fact strings) — well within the band where careful prompting + a forgiving parser is reliable. Defer tool-use until either (a) the platform standardizes on tool-capable providers across the board, or (b) the existing JSON path produces a measurable malformed-response rate that justifies the cross-cutting refactor. When tool-use is eventually adopted, the natural first target is the whole eval call (trackers + journal + scene transitions), not journal alone — adopting it for one consumer doesn't pay for the abstraction.
Hedge: ship freeform with profile_diff_json always preserving the raw model output alongside the parsed result. If a future migration to tool-use happens, the corpus of "what models actually returned" is the evaluation set for "did the tool-call rewrite regress anything?"
Phase 1 — Entries-Only Slice
The full design above is the long-term target. Phase 1 ships only the "always-on lorebook summary" layer — a small set of user-curated journal entries about the current story state, always injected into the prompt, optionally maintained by an eval LLM call. No character profiles, no location profiles, no salience tiers, no materialization. Those land in later phases once Phase 1 is in users' hands.
Terminology note: the long-term design above uses the word "facts" for the simplest journal layer. Phase 1 renames the runtime concept to "journal entries" to avoid colliding with the existing Discord-only Facts feature (user-level, per-Discord-user, totally unrelated). Tables, columns, settings, API payloads, and UI copy all use "entry" / "entries" / "journal". The conceptual "State Facts" name survives in the long-term-design sections above as the category — but in code and in the UI the noun is "journal entry".
Mental model: the journal is a "game save"
The journal is conceptually closer to a save file than to a document. It captures what is true right now in this playthrough — facts that the AI needs to remember about the state of your specific story. Like a save file in a game, it's bound to the run it belongs to. That framing justifies several of the locked decisions:
- Branching doesn't copy the journal. A branch is a "what if I'd done it differently" alternate run. Save files don't follow you across alternate timelines unless the game has explicit checkpoint mechanics. Branches start with a clean slate; the user re-seeds intentionally if they want continuity.
- Sharing / publishing doesn't include the journal. Your save file is yours. A published conversation is the story (the messages), not the state of your specific run.
- No cross-conversation portability without an explicit user action. Materialization to a lorebook (Phase 2+) is the deliberate "export checkpoint" action — the user chooses when their playthrough's state graduates into reusable world data.
Shipped in Phase 1.6 — Regenerate from conversation. The journal modal has a Regenerate button (footer, left of Save/Cancel) that wipes the auto-generated entries and replays the entire conversation in fixed-size windows of message-pairs, calling the journal-eval LLM once per window. A confirm modal surfaces the destructive opt-in for manual entries ("Also wipe my manual entries", off by default — manual entries are sacred). An in-modal progress overlay shows chunk-level progress (X of Y chunks · running added / updated / skipped / failed-chunk counts) with a Cancel button.
The walk is chunked, not summary-based, by design: summaries can drop or distort details, and a regen built on top of them would propagate those errors into the journal. Replaying raw transcripts trades latency for fidelity. Each chunk runs cumulatively — chunk N reads the entries chunk N-1 wrote, so the eval can choose update-existing over add-new across the walk.
| Knob | Default | Range |
|---|---|---|
| Chunk size | 20 message-pairs | 5–60 (clamped) |
| Wipe manual entries | off | user opt-in via checkbox |
Mutual exclusion: while a regen is in flight, the per-message eval stage (PerMessage cadence) skips silently for that conversation — the regen owns journal mutations for the window. A second concurrent regen on the same conversation is rejected with a clear error. The walk continues past individual chunk-level LLM failures (each failed chunk surfaces as a parseStatus: "failed" progress event); the user sees a tally of failed chunks and can re-run.
Wire: POST /api/conversations/{id}/journal/regenerate body {chunkSize?, wipeManual?}, streams SSE events plan → chunk × N → done (or error). Implementation: WebJournalRegenerateService (web/Services), IJournalRegenLock (Core; Postgres lease table journal_regen_locks with unique per-acquisition ownership tokens + renewal — see Phase 0 hardening).
Locked decisions
| Decision | Choice |
|---|---|
| UI surface | Modal, opened from a card on the chat surface. Card is mounted in two places that open the same editor: the chat-v1 KnowledgeView (directly above the Lorebooks card) and the chat-v2 WhoDrawer World Knowledge section (above the lorebook list). Sums into the section's count badge in chat-v2. |
| Conversation scope | web_conversations.id only. No Discord parity in v1. |
| Categories | Column present in schema for forward-compat, no UI and no prompt grouping in v1 |
is_active lifecycle |
Out. Hard delete only. |
| Ordering | updated_at ASC, id ASC (least- → most-recently-touched). No user-controlled reorder. A revised entry sinks to the bottom so the freshest state reads last — both in the modal and in the prompt injector's newest-N tail-slice. (Originally created_at ASC; changed because once the journal hits its entry cap the eval only rewrites existing rows, which left the oldest row holding the newest content pinned at the top.) |
| Cap behavior | MaxEntries is editable inside the modal, not a hard block. Over-cap → eval is instructed to prefer updating an existing entry over adding a new one. User pays for the tokens; we don't gatekeep. |
| Injection position | Default mode template: immediately after the Summary content provider. Modes can override the ordering. |
| Token accounting | Journal size is returned from the same query that reads facts; rolled into the existing system-prompt budget calculation (not a separate budget). |
| Greeting / scenario seeding | Out of v1. |
| Eval call cadence | In v1, controlled by a per-conversation setting: per-message / on-summarization / off. |
| Echo cost | Deferred. Free in v1. Charging hooks in once platform-model cost work lands. |
| Sharing / publishing | Out. Journal is not included in published conversation snapshots. |
| Branching | Branching a conversation does not copy the journal. The new branch starts with an empty journal. This must be surfaced inline in the branching UI. |
| Audience tier | Owner only. No public/admin views in v1. |
| Feature toggle | Features.EnableJournal (default: true). Lives in the HowDrawer's Active Features section alongside Summaries / Memories / Lorebook / Picture entries. When off: prompt provider returns empty AND the per-message stage + on-summarization trigger both short-circuit before the LLM call. No spend on a turned-off journal. Entries remain saved — flipping back on resumes injection. Per-conversation override, defaults from a user-level preference; the runtime resolves through ?? true so an unmigrated database doesn't silently disable the feature for everyone. The toggle also respects mode support: a custom mode that omits the "journal" sub-prompt renders the row as mode-locked (same shape as the summary / lorebook gates), since the underlying content provider wouldn't run regardless of toggle state. |
| Preset assignment | New "Use for Journal" action on every LLM preset card, alongside "Use for Chat" / "Use for Summary". Resolved via JournalEvalLlm.PresetId → standard JournalEvalLlm.* keys by LlmPresetEnricher. Fallback chain: journal → summarization → chat → default built-in. Same shape as the existing summarization preset; no generation overrides (eval has hardcoded low-temperature settings). fn_clear_preset_references sweeps JournalEvalLlm.PresetId on preset DELETE so deleted presets don't dangle. (Since superseded: the per-card actions are gone — assignment is the Journal eval row of Settings → LLM → Pipeline stages, drag a preset or Assign. Chain unchanged.) |
Sub-decisions (recommendations to ratify)
A. Eval model config. Dedicated JournalEvalLlm.{Provider,Model,ApiKey,Endpoint} settings family from day one, mirroring SummarizationLlm.* and the planned TrackerLlm.*. Defaults can point at the same model the platform admin already configured for summarization, but the journal eval gets its own knobs because the workflow will diverge (tool-use migration, multi-pass extraction, etc.). Coupled defaults via documentation, decoupled config in practice.
B. Eval input window.
per-messagecadence: eval prompt receives the last user + assistant exchange plus the current list of journal entries, so the model can choose update-existing over add-new.on-summarizationcadence: journal eval runs as a separate second LLM call after the summarization call completes, not as an extended schema on the summarization call itself. Two calls keep prompts focused; entangling them means one bad parse drops both summary and journal.
C. Eval output shape. Schema:
{
"entries": [
{ "action": "add", "content": "...", "category": "LOCATION" },
{ "action": "update", "id": 42, "content": "..." },
{ "action": "append", "id": 17, "content": "..." }
]
}
appendaction (Phase 1.x). Extends an existing entry with new detail instead of replacing it. The apply layer concatenates the delta onto the target entry's current content (single-space join), under the same source guard + optimistic-concurrency asupdate. An append that would push the entry past the per-entry cap (SettingsKeys.Journal.MaxEntryChars, 4000) is skipped whole and counted as skipped: the entry stays as it was and never gains a cut-off piece of the new detail. So the model isn't appending into that wall, the eval's user content marks each entry the eval may change (eval-authored, never human-corrected) within 10% of the cap[FULL](from 3600 chars,JournalEvalContent.NearlyFullChars) with a note to consolidate it with anupdate, never append — a manual or corrected row is never marked, since that update would be skipped; a marker the model copies into its content is stripped by the parser; the note appears only when an entry is marked, and the skip still holds when a model appends anyway. Added because add/update-only kept entries atomic: to enrich an established slot the model had to re-emit the whole entry, and (with the old "single concise sentence" prompt) defaulted to spawning new one-liners instead.appendlets a slot accumulate across turns cheaply — each add/append stays one crisp sentence, the entry grows. Parsed into its own bucket (JournalEvalAppend); the salvage path recovers appends from truncated responses too. Counted as anupdateinjournal_eval_stats(it mutates an existing row). Shared concatenation/cap helper:Core/Services/Journal/JournalEvalContent.- Prompt + cap (Phase 1.x). The default prompt was rewritten to a structured, category-driven form (LOCATION / COMPANIONS / INVENTORY / RELATIONSHIPS / CONDITION / COMMITMENTS / WORLD FACTS / EVENTS), with explicit what-belongs / what-does-not lists, slot-based add-vs-update-vs-append logic, and worked examples. Entries stay one concise sentence per emission but accumulate via
append; richness comes from more categorised entries + accumulation, not long paragraphs. The eval's own per-entry cap was raised 500 → 1000 (headroom for accumulation; the old cap physically forced one-liners) and the eval-token default 4096 → 8192. One cap since 2026-10-15: the 1000 cut eval entries off well short of the 4000 the editor allows, so eval and manual entries now share one 4000-char cap (SettingsKeys.Journal.MaxEntryChars). The eval never writes a fragment against it — an over-long add/update is cut at the last word boundary at or before the cap (no ellipsis), and an append that would cross it is skipped. The word cut has a floor: if the last whitespace sits before 75% of the cap (JournalEvalContent.WordCutFloorChars, 3000), the text ends in one long unbroken run (a link, CJK prose) and is hard-cut at the cap instead, surrogate-safe — cutting at the early space would throw away most of the entry.MaxEntries × cap(default 10 × 4000) is no longer the prompt bound; the injector's 20,000-char ceiling is (see JRN-24 below). The 8192 eval-token default stays: it also sizes the eval's Echo reservation, and a rewrite of every entry at full length at once is rare — the parser salvages what a capped response completed. Both the DB seed (Journal.DefaultEvalPrompt) and the C#HardcodedFallbackPromptcarry the prompt; an idempotent migration upgrades existing DBs off either prior default without clobbering admin customisations. - What the journal keeps: standing state, the cast, and who believes what. The journal is a snapshot of what is true as of the latest message its update read. It is not a diary. Events and plot threads belong to the story's summary. The journal keeps where things stand, who is in the story, and who believes what. Its categories are LOCATION, COMPANIONS, RELATIONSHIPS, CONDITION, COMMITMENTS, INVENTORY, WORLD FACTS and BELIEFS:
- BELIEFS records something a named character believes or suspects that the story hasn't established, as that character's: "Elin believes the ferryman lied about the toll." Once the story settles it, the entry is rewritten to what is now established.
- COMMITMENTS keeps promises made between characters and the goals they took on. A known danger goes under WORLD FACTS; a feared one goes under BELIEFS.
- Never recorded: a character's fear or guess written as fact, and anything nobody in the story witnessed or was told. A sighting only one character made is her belief, not the story's fact.
- No
deleteaction. Entries that are no longer true should beupdated to reflect the new state, not deleted (history is the user's job, not the eval's). - The model is not required to quote the previous content of an
updatetarget. Before/after is logged server-side for audit.
D. Response format. Freeform JSON with provider JSON-mode constraint when supported (Phase 1.5 update). The JournalEvalLlmService sets LlmRequest.RequireJsonObject = true on every call; each ILlmClient translates that to its provider's native mechanism: OpenAI/OpenRouter/Custom/StrictOpenAI/Featherless pass response_format: { type: "json_object" }; Gemini sets responseMimeType: "application/json"; Anthropic uses the documented assistant-prefill trick (append { to the assistant turn, prepend { to the response). Providers that don't honour the flag silently ignore it. The same forgiveness patterns as SummarizationLlmService.ParseResponse — code-fence stripping, prose-preamble recovery — remain in place as belt-and-suspenders. Parse failure = log + skip the update + surface a single toast "Journal eval failed — entries unchanged". No retry, no partial application. Full tool-use is still deferred per Design Debate 2; JSON mode is the no-regret precursor.
E. Eval prompt. Mirror the summarization prompt resolution chain exactly: Mode-level JournalEvalPrompt override → settings default (Journal.DefaultEvalPrompt) → hardcoded fallback with WARNING log. No new abstraction.
F. Where the cadence setting lives. Conversation-level, defaulted from a user-level preference. Every other story-feel toggle (streaming, model, persona) is conversation-scoped — the cadence toggle joins them.
G. Token-size on journal_entries. Add char_length INTEGER GENERATED ALWAYS AS (length(content)) STORED so the system-prompt budget calc can read sizes in SQL without a per-row roundtrip. Char-count is used as a token proxy, matching whatever convention the existing budget math uses.
H. Eval-vs-manual-edit concurrency. Two layers of protection:
- Source attribution. Schema gains
source SMALLINT NOT NULL(0 = manual,1 = eval) andeval_run_id INTEGER NULL. The eval call only ever modifies entries wheresource = 1. Manual entries are sacred. - Optimistic concurrency. When the eval applies its updates, it checks each target entry's
updated_atagainst the snapshot it read at eval-start. If an entry was touched since (even by another eval), skip that update. Log the skip.
I. Modal anatomy.
- Header: "Journal — current state & established facts"
- Settings row:
MaxEntriesnumber input (defaults from settings, editable)- Cadence tri-state toggle:
per-message/on-summarization/off. Replaces a separateJournal.Enabledsetting — one control, fewer footguns.
- Entries list,
updated_at ASC(freshest-touched at the bottom). Each row: textarea + delete button. Source badge ("auto" / "you") so users can tell at a glance what the eval added vs. what they wrote. - "Add entry" button at the bottom.
- Footer: page-wide Save/Cancel per the standard form pattern, surgical updates.
J. Card preview (above Lorebooks). Shows:
- Label "Journal"
- Entry count
- Cadence indicator ("auto-updating per message" / "auto-updating on summary" / "manual")
- Click anywhere on the card opens the modal.
K. Branching warning. Inline note directly beneath the branch button on the branch dialog: "Branching does not copy the journal — the new branch will start with an empty journal." No extra confirmation click; the inline copy is the warning.
Phase 1 schema delta
Trimmed from the full design, with the v1 additions called out:
CREATE TABLE IF NOT EXISTS journal_entries (
id SERIAL PRIMARY KEY,
conversation_id INTEGER NOT NULL REFERENCES web_conversations(id) ON DELETE CASCADE,
content TEXT NOT NULL,
category VARCHAR(50), -- present, unused in v1
source SMALLINT NOT NULL DEFAULT 0, -- 0 = manual, 1 = eval
eval_run_id BIGINT NULL, -- free-form run handle; no FK in v1
source_message_id INTEGER REFERENCES web_messages(id) ON DELETE SET NULL,
char_length INTEGER GENERATED ALWAYS AS (length(content)) STORED,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS ix_journal_entries_conversation ON journal_entries(conversation_id, created_at);
No is_active column. No journal_character_* or journal_location_* tables until Phase 2. eval_run_id is a free-form BIGINT in v1; promote to a proper journal_eval_runs table in Phase 2 when the eval lifecycle needs auditing.
No new columns on web_conversations or users. Per-conversation and per-user settings ride on the existing key/value tables (08_tables_settings.sql):
web_conversation_settings.key = 'Journal.EvalCadence'— value"off" | "per_message" | "on_summarization"web_conversation_settings.key = 'Journal.MaxEntries'— value is the int as stringuser_settings.key = 'Journal.DefaultEvalCadence'— defaults applied at conversation create
Phase 1 settings
| Key | Default | Description |
|---|---|---|
Journal.DefaultMaxEntries |
10 |
Default cap for new conversations (system-wide default) |
Journal.DefaultEvalCadence |
on_summarization |
Default cadence applied to new conversations |
Journal.DefaultEvalPrompt |
(hardcoded fallback) | System-wide default eval prompt; mode can override |
Journal.EvalCadence |
(inherits Journal.DefaultEvalCadence) |
Per-conversation cadence override (off / per_message / on_summarization). Set from the Journal modal. |
Journal.MaxEntries |
(inherits Journal.DefaultMaxEntries) |
Per-conversation cap override. Set from the Journal modal. |
Features.EnableJournal |
true |
Per-conversation toggle (user-default). When off: no injection AND no eval LLM call. Surface: HowDrawer Active Features. |
JournalEvalLlm.PresetId |
'' (empty) |
LLM preset assigned to the journal eval. Empty = fall through JournalEvalLlm.* → SummarizationLlm.* → Llm.* → default built-in. Set via the Journal eval row of Settings → LLM → Pipeline stages (the per-card "Use for Journal" action is gone). |
JournalEvalLlm.Provider / .Model / .ApiKey / .Endpoint |
(inherit from SummarizationLlm.* when blank) |
Resolved by LlmPresetEnricher when JournalEvalLlm.PresetId is set; otherwise inherits from the summarization keys. |
Pipeline integration
Concrete plumbing points so the implementation lines up cleanly with existing patterns:
- New content provider:
JournalContentProvider : IPromptContentProvider,Key = "journal". Returns the bulleted entry list or empty string when no entries. - How the journal reads to the story model. A story with no prompt mode of its own (or one whose mode leaves the journal out) gets the journal under the platform's own heading, after the story so far and before the world's lore:
Story journal — current state & established facts: This is the narrator's record. A character knows only what they witnessed or were told. Journal as of message 42 — newer messages win - Mira and Raven are at the river crossing at Greyford. - Elin believes the ferryman lied about the toll.- The narrator's-record line: the story so far and the recalled memories carry it too. These three are the narrator's account, so a character never "knows" something just because it is written there.
- The journal's own first line: this says how far the journal reaches and that what happened since wins over it. "Message 42" is the message's place in the story, counted as the reader sees it. When the journal can't tell which message it was last brought up to date from, the line reads "Journal — newer messages win". This happens for a journal of your own entries, or one written before this line existed.
- A mode that writes its own journal heading keeps its own words. The journal's first line still leads the entries under that heading.
Note: the key
"facts"is already taken by the user-level Facts provider at SortOrder 350 — do not reuse.
- New post-LLM stage:
JournalEvalStageBase : IPostLlmStage.Order = 210(after summarization triggers at 200, so per-message journal eval doesn't race with summarization-triggered eval). Reads conversation cadence setting, dispatches toJournalEvalServiceon the appropriate trigger. - Hook into existing summarization stage: when cadence is
on_summarization, the summarization stage fires the journal eval call after its own LLM call completes — as a separate second LLM call, not as an extended summarization schema. Two calls keep prompts focused.
Parallelism by convention. The JournalEvalStageBase must follow the existing fire-and-forget shape of SummarizationStageBase — the heavy LLM call belongs inside a detached Task.Run(...), not awaited inside ProcessAsync. This is the convention that keeps post-LLM stages from blocking each other: each stage's ProcessAsync returns in milliseconds, and the actual LLM work runs concurrently in the background. Once tracker eval is added as a third sibling stage, all three eval calls (summarization, journal, tracker) will race to completion in parallel by default — no scheduler, no orchestration, no shared state. The pattern is parallelism-friendly only as long as no implementer breaks it by awaiting the LLM call inline.
The cost of getting this right: nothing. The cost of getting it wrong: each eval stage adds its wall-clock time to every assistant turn. Worth a code-review checklist item.
Statistics
The journal eval is an LLM call and must be instrumented like every other LLM call on the platform. Mirror the exact pattern used by messaging (27_tables_message_stats.sql) and summarization (27a_tables_summary_stats.sql + IWebSummaryStatsRepository) — no new abstraction, just the same shape applied to a new call site.
Three layers, all required for parity:
In-memory counters and timings via
IStatisticsService.JournalEvalServicerecords the same metricsSummarizationLlmServicedoes —journal_eval.api.latency,journal_eval.completed,journal_eval.errors(tagged withtype=timeout | network | provider | parse). Same pattern asSummarizationLlmService.CallLlmAsync—_statistics.RecordTiming(...)and_statistics.Increment(...)calls bracket the LLM invocation.Per-call DB row in
journal_eval_stats. One row per eval LLM call. Survives fact edits and conversation deletes (stats are independent of the data they describe). Mirror ofweb_summary_stats:CREATE TABLE IF NOT EXISTS journal_eval_stats ( id BIGSERIAL PRIMARY KEY, conversation_id INTEGER NOT NULL, user_id INTEGER, -- LLM details provider VARCHAR(50) NOT NULL, model VARCHAR(100) NOT NULL, cadence VARCHAR(20) NOT NULL, -- 'per_message' | 'on_summarization' -- Token usage prompt_tokens BIGINT, completion_tokens BIGINT, total_tokens BIGINT, cache_creation_tokens BIGINT, cache_read_tokens BIGINT, -- Performance api_latency_ms INTEGER, -- Journal-specific outcome (denormalized; cheap to write, useful in analytics) entries_added INTEGER NOT NULL DEFAULT 0, entries_updated INTEGER NOT NULL DEFAULT 0, entries_skipped INTEGER NOT NULL DEFAULT 0, -- skipped due to manual-edit concurrency (decision H) parse_status VARCHAR(20) NOT NULL DEFAULT 'ok', -- 'ok' | 'fallback' | 'failed' -- Error tracking error_type VARCHAR(50), error_message TEXT, -- Timestamps created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX IF NOT EXISTS idx_journal_eval_stats_created_at ON journal_eval_stats (created_at); CREATE INDEX IF NOT EXISTS idx_journal_eval_stats_conversation_id ON journal_eval_stats (conversation_id); CREATE INDEX IF NOT EXISTS idx_journal_eval_stats_provider_model ON journal_eval_stats (provider, model, created_at); CREATE INDEX IF NOT EXISTS idx_journal_eval_stats_user_created ON journal_eval_stats (user_id, created_at) WHERE user_id IS NOT NULL;New repository:
IJournalEvalStatsRepository/JournalEvalStatsRepository, mirroringWebSummaryStatsRepository.JournalEvalService.CallLlmAsyncinserts the row in atry/finallyso failed calls still produce a stats row witherror_typeanderror_messagepopulated.The
cadence,entries_added/updated/skipped, andparse_statuscolumns are the journal-specific additions over the summary-stats shape. They make "is the eval actually doing useful work or just burning tokens?" answerable in SQL without joiningjournal_entrieshistory.Aggregation function + registered metric. New SQL function
fn_stats_journal_evals(scope, scope_id, granularity, from_ts, to_ts, dimension)indatabase/v1/functions/70_stats_functions.sql, following the existingfn_stats_messages/fn_stats_summariessignature exactly. Allowed dimensions:provider,model,cadence,parse_status.New entry in
DefaultStatsMetrics.Build:new StatsMetric( Key: "journal_evals", SqlFunction: "fn_stats_journal_evals", AllowedScopes: new HashSet<StatsScope> { StatsScope.Global, StatsScope.User, StatsScope.Creator }, AllowedDimensions: new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "provider", "model", "cadence", "parse_status" }, Anonymization: new StatsAnonymizationPolicy(), Description: "Per-call statistics for journal eval LLM invocations."),This makes journal eval volume / latency / token spend / parse-failure rate visible in the same analytics surfaces that already render messaging and summarization metrics — admin dashboards, creator analytics (Pro tier), per-user "my stats". No new analytics UI; the metric just appears wherever stats metrics are listed.
What this gives us:
- Cost visibility. Per-conversation and per-user token spend on journal eval, broken out from summarization and the main LLM call. Critical when we eventually charge Echoes for the eval.
- Quality signal.
parse_status = 'failed'rate over time tells us whether the freeform-JSON gamble (Debate 2) is holding up. A rising rate is the trigger for the tool-use migration discussion. - Usefulness signal.
entries_added + entries_updatedvs. total calls — if 80% of evals produce no change, the per-message cadence is wasting calls and we should reconsider the trigger heuristics. - Provider/model A-B. Same dimensions as messaging stats, so a creator (or admin) can compare journal eval cost/quality across models the same way they compare main-message cost.
Why a dedicated JournalEvalService (not AI Tasks)
The eval call is a structured stateful workflow we expect to grow in specific directions — tool-use migration (Debate 2), multi-pass extraction (Phase 2 character profiles), conflict resolution against base lorebook entries, salience-aware prompt truncation. AI Tasks is built for one-shot stateless evaluation (moderation passes, content checks, keyword matches) where the runner is fundamentally interchangeable. Journal eval is the opposite — the workflow itself is the product, not the prompt.
Concretely:
- AI Tasks would force every Phase 2 evolution to be a new task row + a runner change. We'd outgrow the abstraction by the second slice.
JournalEvalServicemirrorsSummarizationLlmServicein shape — same prompt resolution chain, same forgiving JSON parser, same fire-and-forget invocation pattern. It's a known-good shape with room to grow.- Settings family follows suit:
JournalEvalLlm.{Provider,Model,ApiKey,Endpoint}matching theSummarizationLlm.*andTrackerLlm.*(planned) pattern. Reuse ofSummarizationLlm.*from earlier draft is overruled — the eval is structurally different enough to deserve its own knobs from day one. Defaults can point at the same model.
Journal.Enabled, Journal.AutoUpdate, Journal.UpdateOnSummarization, Journal.MaxCharacterProgressions, Journal.MaxLocationProgressions, and the entire salience/tier setting block from the long-term design are not in v1. They land with the entity profile work in Phase 2+.
Phase 1.1 — what landed
After Phase 1 shipped, a full feature review surfaced concerns that were addressed in a follow-up slice:
- Postgres-backed regen lock. The Phase 1 in-memory
ConcurrentDictionarycouldn't see across instances; a regen on instance A wouldn't block the per-message eval on instance B. Promoted to ajournal_regen_lockstable with a 30-minute lease (fn_acquire_journal_regen_lock/fn_release_journal_regen_lock/fn_is_journal_regen_locked). PgBouncer transaction-mode pooling ruled outpg_advisory_lock(session-scoped, dies on connection return) andpg_advisory_xact_lock(would pin a backend for the multi-minute walk), so a row-based lease is the correct primitive here. - Single MaxEntries cap. Phase 1 had two parallel knobs (
Journal.MaxEntriesandJournal.MaxJournalTokenschar budget) — the entry-count one was a no-op at the prompt injector. Dropped the char budget;Journal.MaxEntriesis now the single user-facing cap, enforced at write time too so the eval can't growjournal_entriespast the user's limit even if the model emits adds forever. Per-entry length is bounded separately: one 4000-char cap for manual and eval-authored entries alike (SettingsKeys.Journal.MaxEntryChars). Eval entries had their own smaller cap until 2026-10-15 (500, then 1000), which cut them off short of what the editor allows. Prompt size is bounded byMaxEntriestogether with the injector's 20,000-char ceiling (JRN-24), not byMaxEntries × per-entry capalone. - Configurable max output tokens. The eval LLM call was hardcoded at
MaxTokens = 1024and routinely truncated on real journals. Now resolves throughJournal.DefaultMaxEvalTokens(user default) → 4096 fallback (raised to 8192 since, see Prompt + cap above). A per-conversationJournal.MaxEvalTokensread first was never writable and was removed in 2026-10. - Truncation salvage in the parser. When the LLM hits its output limit mid-array,
JournalEvalParserno longer drops the whole turn — it walks the entries array body, finds balanced{…}blocks (quote-and-escape aware), parses each independently, and recovers everything before the cutoff. Partial recovery surfaces asparse_status = 'fallback'; complete failure stays as'failed'. - REST status codes.
POST /entrieswas returning 200 (should be 201);DELETE /entries/{id}was returning 200 + JSON body (should be 204 No Content). Fixed./regenerateroute registration changed from expression-body to block-body lambda to avoid ASP0016 silently droppingResults.Empty. - Preset metadata leak closed.
ResolveJournalEvalModelAsyncwas callingpresetRepo.GetByIdAsync(presetId)without scoping to the requesting user — a user could store any integer inJournalEvalLlm.PresetIdand the diagnostics block would resolve and return another user's private preset's Name/Provider/Model. NewGetByIdForUserOrSystemAsyncenforces owner-OR-system scope. - GET /journal parallelized. Modal-open used to do up to ~12 sequential DB round-trips (cadence resolution + max-entries resolution + 4-step preset chain, all uncached). Now does 4 parallel reads (entries + bulk settings dict + conv view + feature state) + 1 final preset lookup; the preset chain reads from the in-memory settings dict instead of issuing per-step queries.
- Fire-and-forget bound to
IHostApplicationLifetime.ApplicationStopping. Per-message and on-summarization evalTask.Runblocks now respect host shutdown so a Railway redeploy can abort in-flight eval LLM calls instead of waiting minutes for them to drain. Per-request CT is intentionally NOT used — the user closing the tab shouldn't kill a background eval that's already eating its own LLM budget. /regeneraterate-limited. 2/min + 10/hr per user. The regen lock prevents concurrent regens for the same conversation but not back-to-back ones, and each regen is ~turns/chunkSizeLLM calls; tight caps are the cost-control fence.- WhoDrawer chat-v2 surface uses the shared
<JournalCard>instead of an inline copy (the inline version had silently dropped the'info'cadence-badge variant foron_summarization). - Regenerate SSE call routed through
fetchWithAuthso a just-expired access token gets a silent refresh + retry instead of surfacing as a "Regenerate failed: 401" toast. - Composite index on
journal_eval_stats(conversation_id, created_at)forfn_stats_journal_evalscreator-scope per-conversation date-range scans. - Endpoint tests covering ownership 404, OCC 412 with current-snapshot body, status codes, settings cadence guard, MaxEntries range guard, and a bonus production bug the new tests caught:
ParseExpectedUpdatedAtcombined mutually-exclusiveDateTimeStylesflags (RoundtripKind | AssumeUniversal) and threwArgumentExceptionon every non-empty input — everyPUT /entries/{id}call was 500'ing. Now usesRoundtripKindwithAssumeUniversalfallback for clients that strip theZsuffix. categorycolumn wired through. The LLM was already emitting"category": "LOCATION"/"COMPANIONS"/"RELATIONSHIPS"in real eval responses; we were silently dropping it.JournalEvalAdd.CategoryandJournalEvalUpdate.Categorynow plumb through tojournal_entries.category(cap 50 chars, null when absent). Phase 2's grouping/profile work can read this column without backfilling.
Phase 0 hardening — what landed (2026-08-08)
A deep technical review (docs-internal/archive/completed-audits/chat-engine/JOURNAL_FEATURE_REVIEW_2026-08-08.md)
found six P0 defects that made saved story state silently lossy or destructible. All six —
plus three adjacent fixes — landed as one hardening slice:
- Strict eval no-op contract (JRN-01). The ONE accepted no-op is the exact
{"entries": []}the prompt demands. Whitespace/empty completions (the reasoning-model failure signature), objects missingentries, wrong-typeentries, and non-empty arrays from which zero valid operations survive are allparse_status='failed'now — the watermark stays open, the exchange is retried (carry-forward / rerun), and nothing is billed. Previously these were recorded as success and the exchange was permanently skipped. - On-summary cadence covers its whole interval (JRN-19).
on_summarization(the default) used to evaluate only the current exchange off the pipeline context and then advance the watermark past the entire summary interval — durable state introduced early/mid-interval never reached the journal. Both cadences now share the carry-forward watermark window machinery: on-summary evaluates every complete exchange since the watermark (from the start of the conversation for the first eval, capped at 20 exchanges), reading persisted messages via the shared hybrid-beat projection. Failures record the resume floor, keeping the window open. - Human corrections gain authority (JRN-20).
journal_entries.user_edited_atseparates authority from origin (source): an owner edit stamps it atomically in the same UPDATE, and the eval's SQL clause (AND source = 1 AND user_edited_at IS NULL) plus the in-memory applier guard refuse to update/append any human-corrected row. "AI-created, human-corrected" stays auditable; the DTO exposesuserEditedAtfor the badge work (P1). - Regen lock is genuinely exclusive (JRN-02). Ownership tokens are unique per ACQUISITION
(
machine:pid:guid), not per process — a second same-process acquire is rejected instead of silently re-granted, release/renew fire only for the exact holding token, and the regenerate walk renews its lease between chunks (aborting, without publishing, if renewal proves the lease was stolen). Live-Postgres tests cover acquire/renew/steal/stale-release. - Regeneration is staged and atomic (JRN-03). The walk no longer wipes the live journal up
front. Rebuilt entries land as staged rows (
journal_entries.pending_run_id), invisible to every read;fn_publish_journal_regenswaps them live in one transaction only when EVERY chunk succeeded. A failed chunk aborts the walk (a partial rebuild never replaces a complete journal), and failure/cancel/crash paths discard staged rows (plus an orphan sweep under the lock). The watermark advances only on a published run.wipeManualnow deletes manual rows only inside the publish — never before success. - No story content in application logs (JRN-04). The eval service's raw-response
Infolog, the regen transcript preview, and the parser's parse-failure log are metadata-only (lengths, statuses, token counts). The parser deliberately does not log theJsonExceptionobject —JsonReaderException.Messageembeds the raw invalid literal. The verbatim artifact for non-ok parses lives only onjournal_eval_stats.raw_response. A log-privacy test plants a marker in model output and asserts it never reaches a captured log line. - Rerun uses the clinical beat (JRN-22). The single-turn rerun read raw assistant prose
while every other eval path read the hybrid beat; it now shares
HybridExtraction. - 412 returns the authoritative row (JRN-21). The entry-update conflict response re-reads after the failed conditional update instead of echoing the endpoint's own pre-conflict read.
- Zero-turn regenerate reports the real count (JRN-23). The terminal event carries the post-operation live count (preserved manual rows included), not a hardcoded zero.
P1 trust tranche — what landed (2026-08-09)
The review's "one truthful journal form" slice (JRN-05/06/07/08/10/14-form/24):
- Batch save (JRN-05).
PATCH /api/conversations/{id}/journalapplies one Save — entry deletes, OCC-checked updates (stamping user authority), creates idempotent per client-generated id, and the journal's settings (INCLUDINGFeatures.EnableJournal) — in ONE transaction viafn_apply_journal_batch(lock → validate → all-or-nothing apply). Response is a discriminated Shape-B outcome:okcarries the fresh payload + clientId→id map;conflictmeans NOTHING was written and carries each losing row's authoritative current value. The editor keeps the user's drafts on conflict and REBASES (a concurrently-deleted row's draft converts to a new entry — user text is never discarded). The old fan-out of parallel per-row requests is gone. Cache note: the batch's settings ride inside the SQL transaction and bypassCachedConversationSettingsRepository's write path — the endpoint explicitly callsInvalidateResolvedSettingsCacheafter an ok batch. Found live: without it, the response itself (and the pipeline'sEnableJournalgate) served pre-save values for a full TTL window. - One form contract (JRN-06). The enable toggle is staged in the same draft as cadence/max/entries — Save commits it, Cancel reverts it. Rebuild and Rerun are disabled while the form is dirty (an explicit "save or cancel first" title), and the rebuild moved out of the primary footer into a Maintenance section.
- Truthful status (JRN-07). The payload carries server-computed injection counts
(
injection.savedCount/injectedCount) produced by the SAME selection rule the prompt provider runs. The card rendersOff — N saved, none sent/N of M sent with every message; the editor header shows the same truth; "Max entries" is now "Entries in context". - Category + provenance (JRN-08). Update/append persist the eval's category
(COALESCE — omitted category preserves the stored one); the API/TS expose
categorysourceMessageId; rows render category chips and eval-origin rows with a user edit badge as "Auto · corrected by you".
- Injection budget (JRN-24, v1).
WebJournalContentProvider.MaxInjectedChars(20k) bounds total injected characters: newest-first, whole entries only, shared selector with the endpoint counts. Promotion to a per-section prompt-planner budget is the durable follow-up. - Accessibility + responsive (JRN-10 / JRN-14 form portion). The card is no longer a role="button" container nesting a real button — "Open journal" and "Rerun" are sibling buttons; entry rows have unique accessible names; the toggle is labelled; the settings grid stacks at the mobile breakpoint.
Still open from the review: JRN-09 (run/chunk ledger), JRN-11's frontend-component
coverage, JRN-12/13 (Story State IA + editor reframe), JRN-14 visual snapshots,
JRN-15/16/17, JRN-18 (living-lorebook substrate); see the review doc's status header.
(Update 2026-09-29: JRN-09 and JRN-15 have since landed (63fe18e4, 2026-08-10) and JRN-12/13 shipped as Slice A (42fc37c4, 2026-08-12) — see the status line at the top.)
Still on the WIP side of Phase 1.1
These bits are forward-designed in the schema but unwired in code — touching them needs more design than a follow-up review slice:
eval_run_idruns table. The column exists onjournal_entries(free-formBIGINT, no FK) but every caller passesnull. Promote to a realjournal_eval_runstable when the eval lifecycle needs auditing (cancelled vs. completed runs, per-run token cost rollup, "show me which run added this entry"). Likely paired with the analytics / observability work in Phase 2.- Mode-level prompt override.
JournalEvalLlmRequest.ModePromptOverrideis threaded through toJournalEvalLlmService.ResolvePrompt, butWebJournalEvalServiceandWebJournalRegenerateServicealways passnull. Wiring a mode's ownJournal.EvalPromptsetting through requires a smallModePromptService.Resolve("journal_eval_prompt", mode)lookup and isn't a journal-internal change — it's a mode-system change. Land it alongside the next mode-subprompt configuration surface. - Per-entry "delete" action. Phase 1 deliberately excludes a delete-by-id action from the eval prompt — the design preference is that obsolete state gets UPDATED to reflect the new reality rather than DELETED outright. Revisit only if Phase 2's living-lorebook work surfaces a genuine "this NPC died and shouldn't be in the journal at all anymore" case the update-pattern can't model cleanly.
Out of Phase 1
For absolute clarity, these are the long-term-design features that are explicitly not part of the first slice:
- Character profiles, location profiles, progression history entries
- Salience scoring, tiered injection, relationship maps
- Materialization to lorebook entries
- Greeting / scenario seeding
- Scene-aware summarization (depends on tracker eval)
- Cross-conversation persistence
- Discord parity
- Published-conversation snapshots
- Public / admin audience tiers
- Echo-charging the eval call
Phase 2 picks up the next slice once Phase 1 has shipped, been used, and produced enough real eval-call output to design the profile schema against actual data.
Database Changes
-- Journal state facts
CREATE TABLE journal_facts (
id SERIAL PRIMARY KEY,
conversation_id INTEGER REFERENCES web_conversations(id),
content TEXT NOT NULL,
category VARCHAR(50),
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
source_message_id INTEGER REFERENCES web_messages(id)
);
-- Journal character profiles (living character cards)
CREATE TABLE journal_character_profiles (
id SERIAL PRIMARY KEY,
conversation_id INTEGER REFERENCES web_conversations(id),
character_name VARCHAR(200) NOT NULL,
aliases_json TEXT, -- JSON array: ["the ranger", "Princess Elara"]
profile_json TEXT NOT NULL, -- JSON object: { appearance, personality, abilities, ... }
relationship_state TEXT, -- Current relationship to player
relationships_json TEXT, -- JSON object: { "Grimjaw": "grudging respect", "Millhaven": "feels protective" }
mention_count INTEGER DEFAULT 0, -- Total times referenced in conversation (frequency signal)
last_referenced_at TIMESTAMPTZ, -- When entity was last referenced (recency signal)
is_active BOOLEAN DEFAULT TRUE,
materialized_lorebook_entry_id INTEGER REFERENCES lorebook_entries(id), -- if exported
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE journal_character_entries (
id SERIAL PRIMARY KEY,
profile_id INTEGER REFERENCES journal_character_profiles(id),
content TEXT NOT NULL, -- What changed ("Revealed her royal heritage")
profile_diff_json TEXT, -- JSON of fields that changed
source_message_id INTEGER REFERENCES web_messages(id),
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Journal location profiles (living location cards)
CREATE TABLE journal_location_profiles (
id SERIAL PRIMARY KEY,
conversation_id INTEGER REFERENCES web_conversations(id),
location_name VARCHAR(200) NOT NULL,
aliases_json TEXT, -- JSON array: ["the dungeon", "the fortress"]
profile_json TEXT NOT NULL, -- JSON object: { description, layout, hazards, ... }
current_state TEXT, -- What the party has done here
mention_count INTEGER DEFAULT 0, -- Total times referenced in conversation (frequency signal)
last_referenced_at TIMESTAMPTZ, -- When entity was last referenced (recency signal)
is_active BOOLEAN DEFAULT TRUE,
materialized_lorebook_entry_id INTEGER REFERENCES lorebook_entries(id), -- if exported
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE journal_location_entries (
id SERIAL PRIMARY KEY,
profile_id INTEGER REFERENCES journal_location_profiles(id),
content TEXT NOT NULL,
profile_diff_json TEXT, -- JSON of fields that changed
source_message_id INTEGER REFERENCES web_messages(id),
created_at TIMESTAMPTZ DEFAULT NOW()
);
UI Considerations
Chat Side
- Journal panel in chat sidebar (collapsible)
- Sections for Facts, Characters, Locations
- Character profiles shown as mini-cards (expandable to full detail)
- Location profiles shown as cards with state indicator
- Inline editing of any entry or profile field
- Add/deactivate entries manually
- Visual indicator when journal was auto-updated after a message (highlight changed fields)
- "Save to Lorebook" button on each character/location profile
Conversation Start
- Option to seed journal from a greeting/scenario
- Greetings could include starter journal entries (initial state facts, starting location, known NPCs)
- Import profiles from a lorebook to pre-populate the journal
History View
- Expandable progression history per character/location
- Timeline showing when entries were added/changed
- Diff view showing what changed in each profile update
- Link back to the message that triggered each entry
Materialization UI
- "Export Journal as Lorebook" in conversation settings
- Select which profiles to include
- Preview generated lorebook entries before creating
- Choose target lorebook (new or existing)
Settings
New settings under Journal.*:
| Key | Default | Description |
|---|---|---|
Journal.Enabled |
true |
Enable/disable journal system |
Journal.MaxActiveFacts |
10 |
Maximum active state facts |
Journal.MaxCharacterProgressions |
10 |
Maximum tracked characters |
Journal.MaxLocationProgressions |
10 |
Maximum tracked locations |
Journal.AutoUpdate |
true |
AI auto-updates journal after responses |
Journal.UpdateOnSummarization |
true |
Update journal during summarization |
Journal.IncludeHistory |
false |
Include progression history in prompt (expensive) |
Journal.FullTierThreshold |
0.8 |
Minimum salience for full profile injection |
Journal.SummaryTierThreshold |
0.4 |
Minimum salience for summary injection |
Journal.MinimalTierThreshold |
0.1 |
Minimum salience for minimal injection |
Journal.RecencyWeight |
0.6 |
Weight of recency in salience scoring |
Journal.FrequencyWeight |
0.4 |
Weight of frequency in salience scoring |
Open Questions
Evaluation frequency:Moved to Design Debate 1. Current recommendation: per-message when tracker eval is on, per-summarization otherwise.Extraction format:Moved to Design Debate 2. Current recommendation: freeform JSON with forgiving parsing, mirroring the existingSummarizationLlmService.ParseResponsepattern.Greeting integration: Should character greetings ship with starter journal entries? This would let scenario-based conversations begin with pre-populated state. Overlaps with the Package feature.
Cross-conversation journal: Should journal state persist when starting a new conversation with the same character? Could be a "continue story" vs. "fresh start" option. Materialization into a lorebook is one path (explicit, user-controlled). Auto-carry is another (implicit, could be surprising).
Profile identity / alias resolution: The evaluation call needs to recognize that "the ranger", "Elara", and "Princess Elara" are the same character. The
aliasesfield helps, but the evaluation call must also detect new aliases and merge references. How aggressive should merging be? False merges (treating two different characters as one) are worse than false splits (creating duplicate profiles).Token budget enforcement:Resolved -- see Tiered Injection Strategy. Entity salience scoring (recency × frequency) determines injection tier (Full / Summary / Minimal / Omitted). Roster tracker overrides to Full tier. Soft token cap with automatic demotion when over budget.Profile schema evolution: As the evaluation call discovers new types of information, should the profile schema be fixed (predefined fields like appearance, personality, etc.) or open (any key-value the AI decides to extract)? Fixed is more structured and predictable. Open is more flexible but harder to display in UI.
Materialization freshness: When a journal profile is materialized into a lorebook entry, should the lorebook entry auto-update when the journal profile evolves? Or is it a snapshot? Auto-sync blurs the line between journal and lorebook. Snapshot is simpler but drifts.
Character card extraction: Could a compelling NPC profile be materialized not just as a lorebook entry but as a full character entity (with system prompt, greeting, etc.)? "I met this NPC in my story, now I want to chat with them independently." This is a powerful creator tool but significantly more complex than lorebook entry materialization.
Scene transition sensitivity: The scene-aware summarization system needs to distinguish between meaningful scene transitions and minor location shifts. A character walking from the tavern bar to the tavern backroom is not a scene change. A character leaving the tavern to travel to the forest is. The evaluation prompt needs to be tuned for narrative granularity, not spatial granularity -- and this may need to be creator-configurable (some stories have rapid scene cuts, others have long continuous scenes). False positives (too many scene breaks) produce fragmented memories; false negatives (missed breaks) produce bloated multi-scene memories. False negatives are probably less harmful since the fallback message-count summarization catches them eventually.