Trackers
Status: Phase 1 SHIPPED (2026-05-30) — create → bind → eval → inject → maintain → inline-edit is live end-to-end (web only). Shipped since (each has its callout below): typed values (2026-05-31); T1, trackers that pin lorebook entries (2026-09-03); P1, trackers on a package (2026-09-04); C1, the package cast and its roster (2026-09-10); T2, a reader's own trackers on a story (2026-10-29: the writing app's Who drawer; on chat. in Story settings → About since 2026-11-07, c3652c2af); built-in trackers every web story gets with no setup: Place and Time, on by default (2026-10-31, 85b45a467), and Outfit, Position, Condition, Trust and Affection, off by default, each with its own switch under Built-in trackers in the feature settings (2026-11-10, 143de5ffb); Game Time headers on summaries and memories, read from the built-in Time tracker (the Game Time option of the time-header settings; the default stays no header); and a token figure that warns past 32,000 tokens, beside the count ceiling (raised to 40), which stays the only refusal (2026-11-07). Still planned: T3 (public tracker pages, sharing, publishing, favorites and tags) and the rest of the Phase 2+ vision. Everything below the Phase 1 header that isn't the Phase 1 spec or marked shipped is that vision. See the "Phase 1 — SHIPPED" callout under the Phase 1 header for exactly what landed and where the implementation diverged from this spec. The Journal Phase 1 ship (journal_entries, JournalEvalService, JournalEvalStageBase, JournalEvalLlm.*, Features.EnableJournal, journal_eval_stats + fn_stats_journal_evals, chunked-walk regenerate) was the canonical precedent for the tracker eval surface; Trackers Phase 1 extracted the shared eval rail (Core/Services/Eval/*, EvalPostLlmStageBase) from it. Earlier 2026-05-11 reconcile still applies.
Overview
A tracker is a named value that is tracked during a conversation. Unlike lorebook entries (static reference data) or memories (past events), trackers represent the current state of things right now -- mutable information that changes as the story progresses.
Trackers fall into two broad categories:
- Specific values -- quantitative or structured state. A percentage (HP: 72%), a count (Gold: 340), a bounded number (Reputation: 6/10), a time stamp (Game Time: Day 3, Morning). These have clear data types and often have ranges or constraints.
- Keyword values -- qualitative state described by named terms. A location (Shadowkeep, Level 2), characters present in the scene (Elara, Grimjaw), an inventory of items (Iron Sword, Dungeon Key), a quest stage (Act 2). These are identifiers -- words or phrases that can also serve as search signals into lorebooks.
Both categories share the same core mechanism: a value is stored per message, evaluated by a separate LLM call after the story response, and carried forward across the conversation. The difference is in how the value is typed, validated, and -- critically -- how it interacts with lorebooks.
Trackers also serve as a persistent search signal for lorebook injection. Because tracker values are always current and always injected, they can drive lorebook searches independently of what was recently said in conversation. A location tracker keeping "Shadowkeep, Level 2" continuously pulls Shadowkeep-related lorebook entries even if the last 10 messages were about cooking dinner. A character roster tracker listing "Elara, Grimjaw" continuously pulls NPC information for those characters as long as they're in the scene.
Currently, tracker values are stored as freeform JSON on messages and summaries, with active tracker names stored as a JSON array on conversations. This proposal elevates trackers into a proper entity with definitions, types, lorebook linkage, and prompt injection.
Design intent (north star)
The AI-roleplay community already runs trackers by hand — they stuff [HP: 72/100]-style state blocks into the system prompt or a jailbreak and ask the story model itself to maintain them inline. This works badly: it splits the model's attention between writing prose and bookkeeping, the format leaks into the narrative, and a single bad turn silently corrupts the state with no way to notice or fix it.
Trackers give that practice programmatic support while fixing its two structural flaws:
Separate the bookkeeping from the prose. The story model does one job — write the conversation. It receives tracker state as read-only context and is never asked to emit structured updates. State extraction is a separate, guaranteed evaluation pass (its own LLM call, its own cheap model, its own prompt) that runs after the response. The story stays clean; the state stays maintained; neither degrades the other.
Inject tracker state as a
usermessage, never a system/assistant message. This is a load-bearing decision, not a detail. Models echo patterns they see in system and assistant turns — give the story model a[HP: 72/100]block in the system prompt and it will start reproducing that block in its own output. Models treatuserturns as input they respond to, not a template to copy. So the current-state block is attached to (or inserted immediately before) the last user message. See Two-Part Injection Design § Part 1 and the Phase 1 locked decision on injection.
Everything else in this doc — the entity model, lorebook coupling, character groups, conditional entries — is downstream of these two ideas. When a design decision is ambiguous, resolve it in favour of (a) keeping the story thread clean and (b) making the eval pass reliable and correctable.
Tracker Visibility
Trackers are hidden by default on every message. The user sees the story; the trackers work silently in the background, driving lorebook injection and maintaining state without cluttering the conversation view.
This is intentional. Most of the time, users don't need to see that HP dropped from 72 to 65, or that the location changed from Level 2 to Level 3. The AI already knows -- the tracker values are injected into the prompt context. The narrative reflects the state naturally.
Two-Layer Visibility Controls
Tracker visibility uses a two-layer system: a master toggle in the How drawer and per-message detail expansion on individual chat bubbles.
Layer 1: Master Toggle (How Drawer)
The How drawer (alongside streaming and model settings) has a conversation-level on/off switch for tracker visibility. When enabled, all assistant messages show a collapsed tracker bar below the message content. When disabled, all tracker bars are hidden.
This is the primary control -- a single click to reveal or hide tracker state across the entire conversation. The toggle state is stored on the conversation (persists across sessions).
Two primary use cases:
Debug -- the creator or user wants to verify that the evaluation LLM is extracting values correctly. "Did it actually track that my HP went down?" Turn the toggle on, scroll through messages, see the tracker values at each point. Satisfied? Toggle off.
Fix -- something went wrong. The AI hallucinated a location change, or missed that a character left the scene. Show trackers, find the message where the error happened, edit the value. The corrected value carries forward from that point. Toggle off when done.
Layer 2: Per-Message Detail (Chat Bubble Context Menu)
When the master toggle is on, each assistant message shows a collapsed tracker bar -- a thin, subtle bar below the message content displaying tracker values in compact form:
HP: 72 | Location: Shadowkeep L2 | Time: Day 3, Morning | Party: Elara, Grimjaw
The collapsed bar shows all visible tracker key:value pairs on a single line, pipe-separated. It's designed to be scannable at a glance without disrupting the reading flow.
Expanding a message's trackers: Right-click (or long-press on mobile) on any message bubble shows a context menu with "Show tracker details" / "Hide tracker details". Expanding a specific message reveals the full tracker state for that message:
- Each tracker on its own line with its full label and value
- Numeric trackers show a mini progress bar (e.g.,
HP: ████████░░ 72/100) - List trackers show items as individual tags/chips
- Enum trackers show the selected value highlighted among all options
- Changed values are highlighted -- if a tracker value changed from the previous message, the new value is visually marked (e.g., bold, accent color, or a delta indicator like
Location: Shadowkeep L2 → L3) - Edit button on each value -- clicking opens inline editing for that tracker value on this message. The corrected value carries forward from this point.
The context menu option is available regardless of whether the master toggle is on. This lets users inspect a single message's tracker state without turning on the global view -- useful for a quick spot-check.
Visual Design
┌─────────────────────────────────────────────────┐
│ The goblins attack! Elara nocks an arrow as │
│ Grimjaw raises his twin axes. The fight is │
│ brief but brutal — you take a slash across the │
│ arm before Grimjaw cleaves the last goblin. │
├─────────────────────────────────────────────────┤
│ HP: 58 │ Location: Shadowkeep L3 │ Day 3, Morn │ ← collapsed tracker bar
└─────────────────────────────────────────────────┘
↓ expanded (via context menu) ↓
┌─────────────────────────────────────────────────┐
│ The goblins attack! Elara nocks an arrow as │
│ ... │
├─────────────────────────────────────────────────┤
│ ♥ Hit Points ████████░░░░ 58/100 (was 72) ✎│
│ 📍 Location Shadowkeep L3 (was L2) ✎│
│ 🕐 Game Time Day 3, Morning ✎│
│ 👥 Party [Elara] [Grimjaw] ✎│
└─────────────────────────────────────────────────┘
The collapsed bar uses the tracker's InjectionMode to determine formatting: compact mode trackers show abbreviated key:value, full mode trackers show the full label. The bar is styled as a subtle, low-contrast element that doesn't compete with the message content -- same visual weight as a timestamp.
Per-Tracker Visibility
Beyond the global toggle, individual trackers have an IsVisible flag on their definition. A tracker with IsVisible: false is hidden from both the collapsed bar and the expanded view, even when the master toggle is on. Visibility is a property of the reader's view, never of the story's prompt (director (b7), 2026-11-25, on a user report the owner forwarded): a hidden tracker is evaluated, injected and sent to the story's model legs exactly as a shown one — Classic's history, the Hybrid director's history and the head of the reader's turn, the writer's call, the eval, the summary timeline. What stays visibility-bound is the reader's side: the reader's own writes (a scene direction's targets, an effect landing on a snapshot) and every read served to the reader or to an agent acting for them (the owner's reads, the observation reads). This is useful for internal tracking state that drives lorebook injection but has no meaningful display value for users -- implementation details that would confuse more than help.
A hidden tracker is a hidden mechanism of the story (owner, Relay eod-519, 2026-11-25): "a thing the story tracks but would disclose too much of the actual story / mystery to the user." The story's models get it every turn. The reader doesn't see it unless they ask.
Revealing hidden trackers (as built, eod-519)
For debugging, the owner asked for a chat. control saying "and show x hidden trackers". It is built on the scene (chatConsole HiddenTrackers.tsx, under the scene's trackers in the desktop margin and the phone's sheet):
- Folded by default: "and 2 hidden trackers". A note under it says, in words a phone shows too, that they are kept out of the scene so they don’t give away what’s ahead. It shows only when the story has a hidden tracker: with none, there is nothing to show. A count the server hasn't given yet reads as none.
- Pressed: the hidden trackers' values in the reply the scene stands on, each drawn as the scene draws a tracker, under a note: the story reads them every turn either way, and showing them changes nothing. Before a story's first snapshot, each shows where it starts. While they are shown and the scene moves to a newer reply, that reply's values are read. A read that gets no answer says so, with Try again.
- Pressed again ("Hide them"): folded. The toggle is local to that view. It is not a setting and is not saved. Nothing it does reaches a prompt: the story's model legs get hidden trackers whether or not they are shown (de9d70975). The rows are read-only, and the scene's editor still lists only visible trackers. The inline edit and the scene save still refuse a hidden key (F-24).
- Where the values travel. The owner's ordinary reads still cut hidden trackers (T2, What the owner is served). The reveal uses two owner-only reads in
ConversationsEndpoints.TrackerBindings.cs, and they are the only way a hidden tracker's name or value reaches the reader:GET /api/conversations/{id}/trackers/hiddenreturns{ count }and names nothing. It is read with the definitions.GET /api/conversations/{id}/trackers/hidden/values?messageId=returns the hidden definitions in the creator's order, plus that reply's snapshot cut to the hidden keys only. It is read on the press.- Another account's story, a deleted one and an unknown id get the family's not-found body, byte for byte the same. A reply of another story is not found.
- Who may reveal: the story's owner, in their own story (the decision, by the owner's "for debugging").
- A reader of a shared or published story never gets the reveal: those reads stay
ShownTrackers.SnapshotJson's, and the reveal reads answer them not found. - Staff see a reported story through the moderator transcript, which deliberately shows what readers see. A staff reveal there is not built (Open Questions 16).
- A reader of a shared or published story never gets the reveal: those reads stay
- RPG and VN (owner: "let this be directed by the UI, just make sure the backend uses it correctly"):
- Both run the web turn (
WebChatTurnService), so their models get hidden trackers as Classic and Hybrid do. - Their consoles show only server-cut reads: the RPG sheet (
RpgSheetBuilder.Readskips hidden trackers) and the owner's message reads. - An RPG story's reveal reads answer with none: its hidden sheet is never served (eod-433). A VN run never reaches them: the chat family's gate answers it with the family's not-found, as it does every
/api/conversations/{id}route (VisualNovelChatFamilyGate), and the handler would answer none too. - A VN run's Hybrid turn runs the web turn; a scripted VN turn calls no model at all.
- Both run the web turn (
- The report that started it was a false positive. Junica's report said the Hybrid director didn't get the full trackers in the user message. de9d70975 traced and pinned it against the real web turn, with a live repro (services and the mock LLM): with a tracker hidden, the turn-2 director and the writer both get its line. Only the story's Trackers feature switch, turned off, sends no tracker block, and the report matches that switch.
Proof of Concept: Game Time Tracker
The Game Time tracker is the ideal first implementation -- it's the simplest tracker type (freeform, no linked lorebook, no list) and it plugs directly into existing infrastructure that's already waiting for it.
Why Game Time First
- Simplest value type: Freeform text, no validation, no linked lorebook. Pure state tracking.
- Existing infrastructure is ready:
tracker_jsonon messages already stores tracker values per messagetracker_start_json/tracker_end_jsonon summaries already capture state across summary boundariesActiveTrackersJsonon conversations already stores active tracker names
- Immediate value for memories and summaries: The memory and summarization systems already have a
IncludeTimeHeadersetting with a"gametime"option that's stubbed but unimplemented:SummaryContentProviderBase.cs:59→// "gametime" => future implementationWebMemoryContentProviderformats time headers but only supports real time- With a game time tracker, both systems can display in-world time instead of real dates
What "gametime" Unlocks for Memories
Currently, when Memory.IncludeTimeHeader is set to "realtime", recalled memories show:
[Jan 15, 2026]
The party entered Shadowkeep and fought goblins on the first floor.
[Jan 16, 2026]
Elara joined the party after the cave rescue.
With a game time tracker, setting IncludeTimeHeader to "gametime" would show:
[Day 1, Morning]
The party entered Shadowkeep and fought goblins on the first floor.
[Day 2, Evening]
Elara joined the party after the cave rescue.
This is far more meaningful for narrative-driven conversations. The AI can reason about story chronology ("that happened two days ago in game time") rather than real-world dates that have no narrative significance. Combined with fuzzy time search, game time headers also enable temporal memory recall -- when a user says "what happened 2 days ago?", the system can resolve that against game time and find the right memories.
How It Works (PoC Scope)
The game time tracker for PoC doesn't need the full tracker entity system. It can work with the existing freeform infrastructure:
1. Tracker activation and value storage (already exists):
- Conversation has
ActiveTrackersJson: ["gametime"] - Each message has
tracker_json: {"gametime": "Day 3, Morning"} - Summaries have
tracker_start_json: {"gametime": "Day 3, Morning"}andtracker_end_json: {"gametime": "Day 3, Evening"}
2. Prompt injection (new, minimal):
- Add game time value to the system prompt as read-only context (e.g.,
"Current game time: Day 3, Morning") - No extraction instructions in the story prompt -- the story LLM just writes narrative
3. Tracker evaluation (new, separate call):
- After the story response completes, fire a separate LLM call to extract the updated game time
- Uses the
SummarizationLlmconfig (orTrackerLlmwhen that exists) -- a cheap model is fine for this - Evaluation prompt: current game time + AI response + hint ("track in-world time progression")
- Parse the JSON response, store in
message.tracker_json - Carry forward to
summary.tracker_end_jsonwhen summarization runs
4. Summary time headers (fill existing stub):
SummaryContentProviderBase.FormatSummary: whentimeHeaderMode == "gametime", readtracker_start_jsonfrom the summary and extract thegametimevalue- Format as
[Day 3, Morning]instead of[Jan 15, 2026]
5. Memory time headers (fill existing stub):
WebMemoryContentProvider.FormatMemories: same logic -- when mode is"gametime", read tracker state from the memory's summary metadata- Recalled memories show game-time context
PoC Scope vs. Full Feature
| Aspect | PoC (Game Time) | Full Feature |
|---|---|---|
| Tracker definition | Hardcoded "gametime" key | Entity with DB table, types, config |
| Value type | Freeform only | Freeform, numeric, enum, list |
| Linked lorebook | No | Yes (with always_on_summary on entries) |
| Character groups | No | Superseded — the cast lives on the package (package-cast.md); no standalone entity |
| Character binding | No (manually activated per conversation) | Yes (characters and packages declare trackers) |
| Package integration | No | Full (package_tracker_bindings, trackers_locked, greeting overrides) |
| Provider key | Inline injection, no formal provider | Full "trackers" provider in ContextKeys.cs |
| Evaluation LLM | Uses SummarizationLlm fallback | Dedicated TrackerLlm.* settings (standalone stage, not combined with Journal) |
| Evaluation call | Single tracker, simple prompt | Multi-tracker, type-validated, structured output |
| Admin | No | IAdminTrackerRepository, admin endpoints, content area permission |
| Sharing | No | EntityPermission system, Hub discovery |
| UI | Minimal display in chat | Full sidebar panel, timeline, forge editor |
| Memory integration | Game time headers on memories/summaries | Same, plus all tracker types |
The PoC validates the core loop (inject state → story LLM writes narrative → separate evaluation extracts changes → store → use in memories) without building the full entity system. Once proven, the entity system, lorebook linking, and roster features layer on top.
Current State
What exists today
| Layer | What's there | Where |
|---|---|---|
| Database | conversation_trackers table (separate entity with trackers_json TEXT column). Linked from web_conversations via trackers_id FK. Exposed as active_trackers_json through the conversation view join. |
07_tables_conversations.sql |
| Database | tracker_json column on web_messages stores a JSON object of tracker values per message |
07_tables_conversations.sql |
| Database | tracker_start_json / tracker_end_json on summaries capture state across summary boundaries |
10_tables_memory.sql |
| Database | trackers_locked flag on packages table. Commented-out package_tracker_bindings table waiting for the trackers table to exist. |
21_tables_packages.sql |
| Model | ConversationView.TrackersId + ActiveTrackersJson, WebMessage.TrackerJson, WebSummary.TrackerStartJson/TrackerEndJson |
Core models, ConversationView.cs |
| Pipeline | IPipelineContext.InputTrackerJson / OutputTrackerJson fields exist but are not read/written by any provider. No provider key registered in ContextKeys.cs. |
IPipelineContext.cs, ContextKeys.cs |
| Settings | Memory.IncludeTimeHeader and Summarization.IncludeTimeHeader settings exist. SummaryContentProviderBase.FormatSummary carries the explicit stub (// "gametime" => future implementation, line ~59). WebMemoryContentProvider.FormatMemories does not branch on mode at all yet — it only checks for "none" vs anything-else, treating any non-none value as include-time. Both providers need the gametime case wired before a Game Time tracker can drive headers. The option is already exposed (knowledge review, 2026-09-29): TimeHeaderOptions in SettingsDefaults.cs offers Game Time to users today, and choosing it silently behaves as Real Time (memories) or as no special handling (summaries). The public docs now say it is listed but not available yet; when this PoC lands, wire both providers and drop that line from features/summaries.md / features/memories.md — or, if the PoC slips, hide the option (a stored gametime value keeps working as today). |
SettingsKeys.cs, SettingsDefaults.cs, SummaryContentProviderBase.cs, WebMemoryContentProvider.cs |
| UI | No tracker management, no display | — |
What's missing
- Tracker entity definition (name, type, initial value, display format) — the
trackerstable - Character-level tracker bindings (character defines which trackers it uses) —
character_tracker_bindingstable - Package-level tracker bindings — uncomment and activate
package_tracker_bindingsin21_tables_packages.sql - Provider key
"trackers"inContextKeys.cs+IPromptContentProviderimplementation - Fill gametime stub in
SummaryContentProviderBaseandWebMemoryContentProvider - Tracker-aware lorebook search (tracker values as persistent search signal)
- Linked lorebooks (tracker → lorebook binding for targeted injection)
always_on_summarycolumn onlorebook_entriesfor presence-aware injection- List-type trackers for character rosters
- AI extraction of tracker values from responses (standalone post-LLM stage — see Risk #5 for why this is not combined with the Journal eval)
- Admin repository (
IAdminTrackerRepository) and admin API endpoints - Entity permissions (follow existing
EntityPermissionpattern for sharing) - UI for managing tracker definitions and viewing tracker state (Forge + chat sidebar)
- History/timeline view of tracker changes
Proposed Design
Tracker as an Entity
A tracker definition describes what is being tracked and how it behaves.
Tracker
├── Name "Game Time"
├── Key "gametime" (unique within character scope)
├── Description "Tracks the in-world time of day and date"
├── InitialValue "Day 1, Morning"
├── ValueType freeform | numeric | enum | list
├── EnumValues (if enum) ["Morning", "Afternoon", "Evening", "Night"]
├── NumericRange (if numeric) { min: 0, max: 100 }
├── DisplayFormat (optional) "Day {day}, {time}"
├── ExtractionHint "Look for time references in the narrative"
├── InjectionMode full | compact (default: full)
├── Scope conversation | character | package (default: character — same set lorebooks use, see scope refactor note at top)
├── LinkedLorebookId (optional) FK to lorebooks - drives lorebook search
├── LinkedCharacterGroupId (optional) FK to character_groups - drives presence-aware character injection
├── IsVisible true (shown in UI sidebar)
├── OwnerId FK to user
├── IsPublic false
└── Timestamps
ValueType options:
| Type | Use case | Example |
|---|---|---|
freeform |
Any text value, AI decides format | Location: "The abandoned castle's eastern tower" |
numeric |
Bounded number, can display as bar | HP: 85/100 |
enum |
Fixed set of values | Time of Day: Morning / Afternoon / Evening / Night |
list |
Multiple items, each a separate search signal | Roster: ["Elara", "Grimjaw", "Shadow King's Scout"] |
The list type is key for character rosters and inventory -- each item in the list acts as an independent search term against linked lorebooks.
InjectionMode controls how verbose the tracker's value is when injected into the story LLM prompt:
| Mode | Behavior | Example output |
|---|---|---|
full |
Human-readable label + value, one line | - Location: The abandoned castle's eastern tower |
compact |
Minimal key: value, no prose | Location: eastern tower |
compact is designed for scenarios where many trackers are active simultaneously. A character with 8-10 trackers (HP, mana, gold, location, roster, inventory, quest, weather) can easily spend 200+ tokens just on the "Current state:" block in full mode. Switching numeric and enum trackers to compact reduces this significantly:
Full mode (all trackers): Compact mode (numeric/enum trackers):
- Game Time: Day 3, Morning gametime: Day 3, Morning
- Location: Shadowkeep, Level 2 location: Shadowkeep, Level 2
- Hit Points: 72 out of 100 HP: 72/100
- Mana: 45 out of 80 mana: 45/80
- Gold: 340 coins gold: 340
- Reputation: 6 out of 10 rep: 6/10
- Roster: Elara, Grimjaw roster: Elara, Grimjaw
- Inventory: Iron sword, 3 health inventory: Iron sword, Health potion x3,
potions, dungeon key Dungeon key
For list-type trackers, compact comma-joins the items on a single line. For numeric trackers, it uses the bare value/max format. The story LLM doesn't need prose to understand HP: 72/100.
Default is full because it reads more naturally and is fine for 2-4 trackers. Creators with tracker-heavy experiences should switch most trackers to compact.
Character-Level Binding
Characters define which trackers are relevant to their experience:
CharacterTrackerBinding
├── CharacterId
├── TrackerId
├── OverrideInitialValue (optional, character-specific starting value)
├── SortOrder (display ordering in UI)
└── IsRequired (always active, can't be toggled off)
When a user starts a conversation with a character, the character's bound trackers are automatically activated with their initial values. Users can optionally add/remove non-required trackers.
Package Integration
Packages are the primary creative unit -- they bundle character, mode, lorebooks, and configuration into a deployable experience. Trackers integrate with packages as a first-class binding:
PackageTrackerBinding
├── PackageId
├── TrackerId
├── OverrideInitialValue (optional, package-specific starting value)
├── SortOrder (display ordering)
└── IsRequired (always active, can't be toggled off)
Infrastructure already exists: The packages table has a trackers_locked flag, and a package_tracker_bindings table is stubbed (commented out) in 21_tables_packages.sql, waiting for the trackers table to be created.
How packages activate trackers:
- When a user starts a conversation from a package, the package's bound trackers are automatically activated.
- If
trackers_locked = TRUE, the user cannot add/remove trackers -- the package author controls the tracker set entirely. - If
trackers_locked = FALSE, the user can add/remove non-required trackers beyond what the package provides. OverrideInitialValueon the package binding takes precedence over the character binding's override, which takes precedence over the tracker's ownInitialValue. This allows the same tracker to start with different values in different packages.
Reading a package's trackers (as built, F180, owner's answer on Relay eod-323). A tracker is not published on its own. A reader sees a package's trackers as chips on its Inside tab, and a public tracker's chip opens its details, read through the package under the package's own audience rule (account-only, adults-only, the package opened as its page opens it, the tracker bound to it and public; every refusal the same not-found). The reader gets what it keeps, how it moves, where the package starts it, whether the story shows it, and who made it. Never the bookkeeper's prompt (extraction hint, example values, injection mode), and nothing of a linked lorebook: a tracker fed by a lorebook says so without naming the book or its entries. A hidden tracker keeps its values, range, format and start from the reader; it shows only what kind of thing it keeps. A private tracker's chip is named only.
Greeting-level overrides: Greetings within a package can further override tracker initial values for specific scenarios. A package might have a "Start at the tavern" greeting that sets location: "The Rusty Tankard" and roster: ["Innkeeper Bran"], while a "Start in the dungeon" greeting sets location: "Shadowkeep, Level 1" and roster: ["Elara"]. (As built, greeting start values S1–S2: a character greeting's values live in character_greetings.tracker_json, and a package's per-greeting values in package_greeting_bindings.tracker_json — each a JSON object mapping tracker keys to starting values. The tracker_overrides_json name below is superseded.)
Two-Part Injection Design
Tracker integration into the LLM pipeline is split into two completely separate parts with different purposes, different prompts, and different models.
Part 1: Story Pipeline Injection (Read-Only Context)
The story LLM receives tracker state as read-only context so it knows the current world state while writing narrative. It is never asked to output structured tracker updates -- the AI stays in character.
Critical design decision: inject as a user message, not a system message. Tracker state is attached to the last user message only (appended or as a separate user-role message immediately before the user's actual message). This prevents the story LLM from mimicking the tracker format in its response -- LLMs tend to echo patterns from system messages and assistant messages, but treat user messages as input context they respond to, not patterns they reproduce.
Message history as seen by story LLM:
[system] Character system prompt, persona, mode...
[assistant] Previous story response...
[user] Current tracker state: ← injected, user role
- Game Time: Day 3, Morning
- Location: Shadowkeep Dungeon, Level 2
- HP: 72/100
- Roster: Elara, Grimjaw
[user] *I draw my sword and charge at the goblins* ← actual user message
What's injected:
- Current tracker values formatted per
InjectionMode(full/compact) - No extraction instructions, no
[TRACKERS]blocks, no format requirements - No description of how trackers work -- just the current state as factual context
- Linked lorebook entries and character group members' system prompts for present items (injected in the system prompt area via the
"trackers"provider, separate from the user-message state block)
What's NOT injected:
- Tracker definitions, types, or constraints (the story LLM doesn't need to know HP has a range of 0-100)
- Extraction hints (those are for the evaluation LLM only)
- Any instruction to output tracker data
The provider key is "trackers" (added to ContextKeys.cs). The TrackerContentProvider handles two injection targets:
- System-level: linked lorebook entries and character group content for present items (via standard provider output)
- User-message-level: the compact state block attached to the last user message (via a separate injection mechanism, not the standard provider output)
Part 2: Tracker Evaluation (Separate LLM Call)
Tracker evaluation runs as a completely separate LLM call after the story response is complete. This is not part of the story pipeline -- it's a post-processing step with its own prompt, its own model, and its own purpose.
Why separate:
| Concern | Inline extraction | Separate evaluation call |
|---|---|---|
| Story quality | AI must break character to emit structured data | AI writes pure narrative, never breaks character |
| Extraction reliability | Format compliance varies by model | Dedicated call with structured output, can use a model good at JSON |
| Model choice | Must use the same (often expensive) story model | Can use a cheaper/faster model -- this is a data extraction task, not creative writing |
| Latency | Extraction is part of the response stream | Runs async after response streams to user -- user sees the response immediately |
| Token cost | Extraction instructions consume tokens in every story prompt | Evaluation prompt is compact and targeted |
| Failure isolation | Bad extraction corrupts the response | Evaluation failure is silent -- tracker values carry forward unchanged, story is unaffected |
Evaluation prompt inputs (all four are required):
- Last tracker state — the current values from the previous message's
tracker_json(or initial values if first message) - Last user message — what the user said/did (provides intent context for state changes)
- Last assistant message — the story response (the primary source of state changes)
- Tracker definitions with extraction hints — describes each tracker's key, type, constraints, and how to evaluate changes
You are a state tracker. Given the previous state, a user action, and
the narrative response, determine what values changed.
Return ONLY a JSON object with updated values. Omit unchanged values.
Previous state:
{
"gametime": "Day 3, Morning",
"location": "Shadowkeep Dungeon, Level 2",
"hp": 72,
"roster": ["Elara", "Grimjaw"],
"inventory": ["Iron sword", "Health potion x3", "Dungeon key"]
}
Tracker definitions:
- gametime (freeform): Track in-world time of day and date progression
- location (freeform): Track the current location in the narrative
- hp (numeric, 0-100): Track hit points. Decrease on damage, increase on healing
- roster (list): Track named characters actively present in the scene.
Add when they appear, remove when they leave.
- inventory (list): Track items the player possesses
User message:
"I draw my sword and charge at the goblins"
Assistant response:
"Elara nocks an arrow as the goblin patrol rounds the corner. Three
of them, armed with rusty blades. 'Stay behind me,' Grimjaw growls,
raising his twin axes. The fight is brief but brutal — you take a
slash across the arm before Grimjaw cleaves the last goblin in two.
As the dust settles, Elara notices a stairway leading down. 'Level
three,' she whispers. You pocket a healing potion from the goblin
leader's belt."
Expected response:
{
"location": "Shadowkeep Dungeon, Level 3",
"hp": 58,
"inventory": ["Iron sword", "Health potion x4", "Dungeon key"]
}
The evaluation model only returns changed values. Unchanged trackers (gametime, roster) are omitted and carry forward.
Why the user message matters for evaluation: The user's action provides critical intent context. If the user says "I drink a health potion" but the assistant's narrative doesn't explicitly mention HP numbers, the evaluation LLM can still infer that HP should increase. Without the user message, the evaluation would have to rely solely on the narrative — which may be vague about mechanical effects.
Evaluation flow:
1. Story LLM generates response (user sees it streaming)
2. Response completes, stored as web_message
3. Tracker evaluation fires async:
a. Build evaluation prompt from:
- Previous message's tracker_json (or initial values)
- The user's message text
- The assistant's response text
- Active tracker definitions with extraction hints and type constraints
b. Send to Tracker LLM (separate config, cheap model)
c. Parse structured JSON response
d. Validate against type constraints (numeric ranges, enum values)
e. Store updated values in message.tracker_json
4. UI updates tracker display (tracker bar refreshes)
Tracker LLM Configuration
New settings mirroring the SummarizationLlm.* / JournalEvalLlm.* pattern:
| Setting | Default | Description |
|---|---|---|
TrackerLlm.Provider |
(falls back to SummarizationLlm, then Llm) | LLM provider for tracker evaluation |
TrackerLlm.Endpoint |
(falls back) | Custom endpoint |
TrackerLlm.ApiKey |
(falls back) | API key |
TrackerLlm.Model |
(falls back) | Model for evaluation |
Fallback chain: TrackerLlm → SummarizationLlm → Llm. If no tracker-specific LLM is configured, it uses the summarization LLM (already likely a cheaper model). If that's not configured either, falls back to the main LLM.
This is a structured extraction task -- a small, fast, cheap model is ideal. The evaluation prompt is short (current state + response text + hints), and the output is a small JSON object. Models that handle structured output well (even ones not great at creative writing) are perfect here.
Async Execution and Failure Handling
The evaluation call runs after the story response streams to the user:
User sends message
↓
Story LLM streams response → user sees response immediately
↓
Response complete, stored in DB
↓
Fire-and-forget: tracker evaluation
├── Success → update message.tracker_json, store evaluation log, refresh UI
├── Parse failure → store raw response in evaluation log, notify user, carry forward previous values
└── Total failure → store error in evaluation log, carry forward previous values
Failure is safe: If the evaluation LLM is down, slow, or returns garbage, tracker values simply don't update. The story response is already delivered. The next message will use the last known good values. No data loss, no user-visible error.
JSON parse failure: When the evaluation returns unparseable JSON, the raw LLM response is stored alongside the message and the user is notified with a non-intrusive indicator on the tracker sidebar. The user can view the raw response (often the LLM produced useful text that just wasn't valid JSON), manually apply the intended changes, or dismiss. See Design Principles: Error Handling for full details.
User editability: All tracker values are directly editable by the user. The evaluation call is a convenience, not the authority -- the user can always correct mistakes, override extracted values, or manually set state. See Design Principles: User Editability.
Retry: Unlike story generation (where the user is waiting), evaluation can retry once silently on transient failures. If both attempts fail, carry forward.
Evaluation Prompt: Creator Control
The evaluation prompt is not hardcoded -- creators control it through the tracker's ExtractionHint and through a broader evaluation prompt template configurable per character or package. Different experiences demand different extraction behavior:
- A tactical RPG creator wants precise numeric extraction:
"Track HP as an integer. Deduct exactly the damage described. If ambiguous, estimate conservatively." - A freeform roleplay creator wants loose narrative tracking:
"Track location as a general description. Don't over-specify -- 'somewhere in the forest' is fine." - A character card creator might want aggressive profile extraction for journal:
"Extract every physical detail, personality trait, and relationship signal you can find."
Testing & Debugging Tools
Getting tracker extraction right requires iteration. Creators need to tune ExtractionHints, test different scenarios, and diagnose when evaluation produces unexpected results. Users need to understand why a tracker changed and fix it when it's wrong. This section covers the tools for both audiences.
For Creators: Tuning ExtractionHints
Prompt preview (Forge):
In the Forge tracker editor, a "Preview evaluation prompt" button shows the fully assembled evaluation prompt — the exact text the evaluation LLM will receive. This includes the template, all tracker definitions, types, constraints, and hints. Creators can see what the LLM sees and adjust hints accordingly.
Regenerate from message:
In a conversation with tracker visibility on, the expanded tracker detail view for any message has a "Re-evaluate" button. This re-runs the evaluation call against that specific message using the current tracker definitions and hints (not the ones that were active when the message was originally evaluated). The flow:
- Creator updates an ExtractionHint in the Forge
- Goes back to the conversation, finds a message where extraction was wrong
- Clicks "Re-evaluate" on that message
- Sees the new extraction result alongside the stored one
- Can accept (overwrite stored values) or dismiss
This is the core iteration loop: tweak hint → re-evaluate → compare → repeat. Creators don't need to replay the whole conversation to test a hint change.
Batch re-evaluate:
In the conversation's tracker history/timeline view, a "Re-evaluate range" action lets creators select a range of messages and re-run evaluation against all of them with current hints. Results are shown as a diff: what was stored vs. what the new hints produce. Useful for validating that a hint change improves extraction across multiple scenarios without introducing regressions elsewhere.
A/B evaluation:
In the Forge, a "Test hint" panel lets creators run two different ExtractionHint variants against the same message side-by-side. Input: select a conversation + message, provide hint A and hint B. Output: both extraction results compared in a diff view. Lets creators fine-tune wording without guessing.
Evaluation log:
Every evaluation call stores its raw input and output alongside the message (not just the parsed tracker values). Creators can inspect:
- The full evaluation prompt that was sent
- The raw LLM response (before JSON parsing)
- Which values were extracted, which were carried forward, which failed validation
- Parse errors or type validation failures
This is accessible from the expanded tracker detail view on any message via an "Evaluation log" link.
For Users: Understanding and Fixing Tracker State
Tracker bar + details (chat bubbles):
The two-layer visibility system (see Tracker Visibility) is the primary debugging surface. When something feels off in the narrative, the user toggles trackers on and scans the collapsed bars to find where state diverged. Expanding a specific message shows:
- Current values with change highlights (was → now)
- Edit button per value for immediate correction
Inline editing with carry-forward:
When a user edits a tracker value on message N, the corrected value carries forward to all subsequent messages. The system doesn't re-evaluate subsequent messages — it simply replaces the stored value at message N and marks it as user-edited. Subsequent messages that were evaluated against the old value retain their stored evaluations, but the effective tracker state for prompt injection uses the corrected value chain.
This means: edit the value where it went wrong, and everything after it sees the correction. Simple, predictable, no cascading re-evaluation.
Tracker history / timeline:
A conversation-level view showing all tracker value changes over time as a timeline:
- Each row is a message where at least one tracker value changed
- Shows: message number, timestamp, which trackers changed, old → new values
- Color-coded: green = AI-evaluated, blue = user-edited, red = evaluation failed (carried forward)
- Click any row to jump to that message in the conversation
This is the "big picture" view for understanding tracker progression across a long conversation. Useful for debugging drift ("HP has been slowly decreasing every message even in peaceful scenes") and for recap after returning to a conversation.
Context menu: "Why did this change?"
On any changed value in the expanded tracker detail view, a "Why?" link shows the evaluation context for that specific change:
- The user message and assistant response that triggered the evaluation
- The ExtractionHint that was active
- The raw LLM extraction response
- Whether the value was AI-evaluated, user-edited, or carried forward from a failure
This closes the loop: the user sees a wrong value, asks "why?", sees exactly what the evaluation LLM was given and what it produced, and can either fix the value or report the issue to the creator.
Tracker-Aware Lorebook Search
This is the most impactful aspect of the tracker system. Trackers don't just display state -- they drive lorebook search, solving a fundamental limitation of the current system.
The Problem: Search Window Decay
Current lorebook search is reactive -- it builds a search query from the last N messages (MessageScanDepth). This works when conversation topics match lorebook entries, but fails when state persists beyond the search window:
Message 1: "Let's explore Shadowkeep" → Lorebook finds Shadowkeep entries ✓
Message 2: "I open the iron door" → Lorebook finds Shadowkeep entries ✓
...
Message 15: "I cook some rabbit stew" → Shadowkeep entries? Probably not ✗
Message 16: "Tell me about this room" → Which room? Where? Context lost ✗
The party is still in Shadowkeep, but the search window has moved on. The AI loses access to location-specific lore because nobody mentioned "Shadowkeep" recently.
The Solution: Tracker Values as Search Context
Tracker values are always current. By feeding them into the lorebook search query alongside recent messages, relevant entries stay in scope as long as the state holds:
Current search: concat(last N messages)
Proposed search: concat(last N messages) + concat(active tracker values)
The location tracker holds "Shadowkeep Dungeon, Level 2". Even at message 16, "Shadowkeep" is in the search query. Lorebook entries about Shadowkeep match continuously until the location changes.
This requires zero new infrastructure -- tracker values already exist, lorebook search already accepts a text query. The change is adding tracker state to the search input.
Linked Lorebooks
A tracker can optionally link to a specific lorebook, creating targeted injection. This is where keyword-type trackers become powerful: the tracked values directly drive which lorebook entries are pulled into context.
Tracker: "location"
Value: "Shadowkeep, Level 2"
LinkedLorebookId: 42 (World Geography lorebook)
When a tracker has a linked lorebook:
- The tracker value is used as a search query against that specific lorebook
- Matching entries are injected (alongside or separate from the general lorebook search)
- The linked lorebook gets priority -- its entries are guaranteed to be searched with the tracker value, not competing with recent-message relevance
When a tracker has no linked lorebook (default):
- The tracker value is still added to the general lorebook search context
- It boosts any lorebook entry that matches, across all bound lorebooks
Keyword Uniqueness in Linked Lorebooks
For tracker-driven lorebook search to work reliably, the keywords in a linked lorebook must follow strict naming conventions:
Keywords must be unique within the lorebook. When the tracker value "Elara" is searched against the NPC Directory lorebook, there should be exactly one entry that matches. If two entries share the keyword "Elara", the system can't determine which one to inject -- or worse, it injects both, wasting token budget.
Keywords must be clear and unambiguous. Tracker values and lorebook keywords need to align on specific, recognizable identifiers:
| Good keywords | Bad keywords |
|---|---|
"Elara" (character name) |
"the woman" (too generic) |
"Iron Sword" (item name) |
"weapon" (matches multiple entries) |
"Shadowkeep, Level 2" (specific location) |
"dungeon" (which dungeon?) |
"Crystal of Dawn" (quest item) |
"crystal" (ambiguous) |
Why this matters for list-type trackers: A roster tracker holding ["Elara", "Grimjaw", "Shadow King's Scout"] searches the linked lorebook with each item as a separate query. If "Scout" also matches an entry for "Scout Leader Bren", the wrong NPC info gets injected. Use full, specific names.
Character Roster
The character roster is the prime example of a list-type tracker with a linked lorebook. It tracks which characters are present in the current scene and pulls their information from a special kind of lorebook -- a character lorebook.
But the roster concept goes beyond simple presence tracking. It introduces a pattern we call Presence-Aware Character Injection -- a reusable concept that applies to any scenario where a group of entities (characters, NPCs, party members, enemies) exist within a story world, and only some of them are "active" at any given moment.
The Concept: Presence-Aware Character Injection
In many roleplay and narrative scenarios, there's a cast of characters who exist in the world. At any moment, only a subset of them are present in the current scene. The system needs to handle both states:
- Present characters need their full information injected so the AI can write them accurately -- personality, speech patterns, appearance, abilities, relationships, secrets.
- Absent characters still exist in the world. The AI should know they exist (to reference them in conversation, react to their mention, know they might return) but doesn't need their full detail.
This creates a two-tier injection model:
| State | What the AI receives | Purpose |
|---|---|---|
| Present (in roster) | Full character entry from the linked lorebook | Write the character accurately, in voice, with full context |
| Absent (not in roster, but in the lorebook) | Short always-on summary | Know the character exists, can be referenced, might appear later |
The always-on summary is a brief prompt line per character -- just enough to establish existence without consuming significant tokens. Something like:
Characters in this world (not currently present):
- Grimjaw: A veteran dwarven fighter. Currently elsewhere in Shadowkeep.
- The Shadow King: Ancient lich lord of Shadowkeep. Not yet encountered.
This prevents the AI from forgetting characters exist just because they stepped offscreen. A user can say "What do you know about Grimjaw?" and the AI can answer from the summary, even though Grimjaw's full lorebook entry isn't injected.
Always-on summary token budget: Always-on summaries are injected for ALL entries in a linked lorebook, regardless of tracker state. With a large NPC cast, this adds up: 20 characters at ~25 tokens each = 500 tokens of summaries on every message. To keep this under control:
- Global cap:
MaxAlwaysOnSummaryTokenssetting (default: 800 tokens). When the total token count of all always-on summaries exceeds this cap, the lowest-priority summaries are dropped. Priority is determined bysort_orderon the lorebook entry -- creators order entries by narrative importance, and the least important characters drop first. - Forge warning: The lorebook editor shows a live token count for always-on summaries: "15 characters × ~25 tokens = ~375 tokens (of 800 budget)." Turns amber when approaching the cap, red when exceeding it.
- Per-entry guidance: Individual summaries should be one line, ~20-30 tokens. The Forge should warn on summaries exceeding ~50 tokens ("This summary is longer than recommended. Consider shortening it to keep within the always-on budget.").
The cap applies per linked lorebook. If a character has two list-type trackers with linked lorebooks (e.g., a roster and an inventory), each gets its own 800-token budget for summaries.
Character Lorebooks: Lorebooks Linked to List-Type Trackers
A lorebook linked to a list-type tracker (such as a roster tracker) isn't a distinct lorebook type -- it's a regular lorebook whose entries leverage the always_on_summary feature. However, these lorebooks tend to differ from standard lorebooks in practice:
Entries tend to be longer. A regular lorebook entry about a location or concept might be 200-300 tokens. A character entry needs to cover personality, appearance, speech patterns, relationships, motivations, abilities, and secrets. These entries commonly run 400-800 tokens. This is acceptable because the roster tracker controls which entries are injected -- you're only paying the token cost for characters actually in the scene, not the entire cast.
Each entry is a character card. The structure mirrors what's already defined for characters in the system -- system prompt, personality, appearance, example dialogue. The difference is that these are secondary characters within a primary character's story, not top-level characters with their own conversations. They live inside a lorebook because they're part of the experience, not standalone entities.
Each character has two prompt layers:
Full entry (in the lorebook) -- the complete character card. Injected when the character is present in the scene via the roster tracker. This is the lorebook entry content itself.
Always-on summary (separate field on the lorebook entry) -- a short one-liner establishing the character's existence. Always injected for all characters in the lorebook, regardless of roster state. Keeps the AI aware of the full cast.
Lorebook Entry: "Elara"
Keywords: ["Elara", "the ranger", "Princess"]
AlwaysOnSummary: "Elara - a ranger from the Northern Reaches, skilled
with bow and tracking. Companion of the protagonist."
Content: "Elara is a ranger from the Northern Reaches. Distrustful of
outsiders but fiercely loyal once trust is earned. Skilled with
bow and tracking. Carries a longbow named 'Whisper' and a
hunting knife. Has a scar across her left palm from a blood
oath. Secret: she is the exiled princess of the Northern
Reaches, fled rather than marry the Shadow King's emissary.
Speech: direct, clipped sentences, avoids emotional language
unless pushed. Uses nature metaphors..."
Character lorebooks can have their own attached lorebooks. A character lorebook for an NPC cast might link to additional lorebooks that provide supplementary context -- a relationship map lorebook, a faction lorebook, a backstory lorebook. This enables layered world-building where character information pulls in related world context.
Keyword Requirements for Character Lorebooks
Character lorebook entries demand strict keyword discipline (see Keyword Uniqueness above). Each character entry should have:
- Primary keyword: The character's name, exactly as the evaluation LLM will track it. This is the identifier that appears in the roster tracker value.
- Alternate keywords: Titles, nicknames, or descriptors the AI might use (
"the ranger","Princess"). These help with general lorebook search but the primary keyword is what the roster tracker matches against.
The primary keyword must be unambiguous within the lorebook. Two characters cannot share a primary keyword.
Setup Example
Tracker definition:
Tracker: "roster"
Name: "Characters Present"
Key: "roster"
ValueType: list
InitialValue: ["Elara"]
ExtractionHint: "Track which named characters are actively present in
the scene. Add characters when they appear or are
introduced. Remove them when they leave or the scene
changes to a location without them."
LinkedLorebookId: 73 (NPC Directory lorebook)
NPC Directory lorebook (id: 73):
Entry: "Elara"
Keywords: ["Elara", "the ranger", "Princess"]
AlwaysOnSummary: "Elara - ranger from the Northern Reaches, companion."
Content: "Elara is a ranger from the Northern Reaches. Distrustful of
outsiders but fiercely loyal once trust is earned. Skilled with
bow and tracking. Secret: she is the exiled princess of..."
Entry: "Grimjaw"
Keywords: ["Grimjaw", "the dwarf", "old dwarf"]
AlwaysOnSummary: "Grimjaw - veteran dwarven fighter, seeking his lost brother."
Content: "Grimjaw is a veteran dwarven fighter. Gruff exterior, secretly
sentimental. Fights with twin axes. Looking for his brother who
vanished in Shadowkeep ten years ago..."
Entry: "The Shadow King"
Keywords: ["Shadow King", "dark lord"]
AlwaysOnSummary: "The Shadow King - ancient lich ruling Shadowkeep."
Content: "Ancient lich who rules Shadowkeep. Commands undead armies..."
How It Flows
Roster tracker value: ["Elara", "Grimjaw"]
Injected into prompt:
1. Always-on summaries for ALL characters (Elara, Grimjaw, Shadow King)
2. Full entries for PRESENT characters only (Elara, Grimjaw)
→ AI knows: Elara and Grimjaw are here with full detail.
The Shadow King exists but isn't in the scene.
Scene change: Grimjaw leaves, Shadow King's scout appears
→ Evaluation updates roster: ["Elara", "Shadow King's Scout"]
→ Next message:
1. Always-on summaries: still all characters
2. Full entries: Elara + Shadow King (matched via "Shadow King" keyword)
3. Grimjaw's full entry drops out (saving tokens)
The AI always has detailed information about who's in the scene. When a character leaves, their full entry stops being injected (saving tokens) but their always-on summary keeps the AI aware they exist. When someone new arrives, their full entry automatically appears.
Why this is better than alternatives:
| Approach | Token cost | Relevance | World awareness |
|---|---|---|---|
| All NPCs as always-include | High (every NPC, every message) | Low (most aren't in scene) | Full |
| NPCs via message search | Variable | Unreliable (name must be mentioned recently) | Partial (forgets offscreen characters) |
| NPCs via roster tracker | Proportional to scene + small fixed cost for summaries | Always accurate (tracks who's present) | Full (always-on summaries) |
Other Tracker + Lorebook Examples
Location → World Geography:
Tracker: location = "The Rusty Tankard tavern"
Linked lorebook: World Geography
→ Injects: Rusty Tankard entry (layout, NPCs who frequent it, menu)
Tracker changes to: "Shadowkeep, Level 2"
→ Injects: Shadowkeep entry (history, hazards, known inhabitants)
Current Quest → Quest Details:
Tracker: current_quest = "Find the Crystal of Dawn"
Linked lorebook: Quest Details
→ Injects: Crystal of Dawn entry (location hints, guardians, lore)
Quest completed, new quest: "Return to Millhaven"
→ Crystal info drops, Millhaven entry comes in
Inventory → Item Catalog:
Tracker: inventory = ["Iron Sword", "Health Potion", "Dungeon Key"]
Linked lorebook: Item Catalog
→ Injects: entries for items the player actually has
→ AI knows sword stats, potion effects, what the key opens
Character Groups
A character group is a standalone lightweight entity -- a named collection of Character entities that can be linked to a tracker. Instead of tracking character names as freeform strings matched against lorebook entries, a list-type tracker references a character group, and the tracker's value controls which members are "present" in the scene.
This solves a fundamental problem with the lorebook-based roster approach: creators shouldn't have to duplicate character information into lorebook entries. A character already has a system prompt, personality, appearance, and everything needed to inject it into a scene. Character groups let creators reuse those existing character definitions directly.
The relationship mirrors how trackers link to lorebooks: the lorebook is a standalone entity, the tracker links to it via linked_lorebook_id. Similarly, the character group is a standalone entity, the tracker links to it via linked_character_group_id.
Character Group as a Lightweight Entity
Character groups are not full publishable entities like characters or lorebooks. They don't have tags, Hub presence, publishing flow, or scheduled publish dates. They're simple named containers owned by a user:
CharacterGroup
├── Id
├── Uuid Public-facing identifier
├── CreatedByUserId Owner
├── Name "Shadowkeep NPCs", "Party Members"
├── Description Optional description
├── CreatedAt
└── UpdatedAt
No is_public, no is_deleted, no tags_*, no published_at. A group is private to its creator and reusable across their own trackers and packages. Sharing happens indirectly -- when a tracker or package that references a group is shared, the group's members are accessible in that context.
Character Group Membership
CharacterGroupMember
├── CharacterGroupId FK to character_groups
├── CharacterId FK to characters
├── AlwaysOnSummary Short one-liner for when character is absent
├── SortOrder Display ordering and summary priority
└── OverrideSystemPrompt (optional) Override the character's system prompt for this group context
Why AlwaysOnSummary lives on the membership, not the character: A character's system prompt is written for a scenario where that character is the protagonist of their own conversation. In a group context, the character is a supporting cast member -- the always-on summary needs to be written for that specific role. "Elara -- ranger companion, distrustful of outsiders" is a group summary, not something that belongs on Elara's character card.
Why OverrideSystemPrompt exists: Similarly, a character's full system prompt may be written for solo conversations ("You are Elara, a ranger..."). In a group context, the prompt may need adjustments -- third-person framing, condensed to essential traits, or focused on the character's role in this specific story. The override is optional; when absent, the character's own system prompt is used as-is.
Tracker → Character Group Link
A tracker references a character group the same way it references a lorebook:
Tracker
├── ...
├── LinkedLorebookId FK to lorebooks (existing)
├── LinkedCharacterGroupId FK to character_groups (new)
├── ...
A tracker can have both a linked lorebook AND a linked character group. This is useful when some NPCs are full Character entities (important recurring characters) while others are lorebook entries (one-off NPCs, environmental characters).
Presence-Aware Injection
The tracker's list value controls which group members are "present" in the scene:
| State | What the AI receives | Source |
|---|---|---|
| Present (in tracker value) | Full character system prompt + character's attached lorebooks become active | Character entity + character_lorebook_bindings |
| Absent (member of group but not in tracker value) | Short always-on summary only. Attached lorebooks are not searched. | always_on_summary field on the membership |
This mirrors the lorebook-based roster pattern but pulls data from real characters instead of lorebook entries.
Presence-Gated Lorebook Activation
Characters have their own attached lorebooks via character_lorebook_bindings -- world lore, backstory, faction details, abilities, etc. When a character is a member of a character group, their attached lorebooks are only active when the character is present in the scene.
Elara (character_id: 42)
Attached lorebooks:
- "Northern Reaches Lore" (geography, politics, history)
- "Ranger Abilities" (tracking, archery, survival skills)
Tracker value: ["Elara", "Grimjaw"]
→ Elara is PRESENT → her lorebooks are searched alongside the conversation's own lorebooks
→ Northern Reaches entries match when the scene touches relevant topics
Tracker value changes to: ["Grimjaw"]
→ Elara is ABSENT → her lorebooks are no longer searched
→ Northern Reaches entries stop matching (unless separately bound to the conversation)
→ Saves token budget — no point injecting Elara's world lore when she's not in the scene
Why this matters: In a story with a large cast, each character might bring 1-3 lorebooks of world-building context. If all lorebooks were always active, the search space explodes and irrelevant entries compete for the limited entry budget. By gating lorebook activation on presence, the system automatically narrows the search scope to what's narratively relevant -- the world context that the present characters bring with them.
How it works in the pipeline:
- The tracker provider reads the current tracker value (list of present character names)
- For each present character member, resolve their
character_lorebook_bindings - Add those lorebook IDs to the active lorebook set for this message's search
- Absent characters' lorebooks are excluded from the search set
- The lorebook provider searches across the combined set: conversation-bound lorebooks + present characters' lorebooks
Edge cases:
- If a lorebook is bound to both the conversation AND a character member, it stays active regardless of character presence (conversation binding takes precedence)
- If two present characters share the same lorebook, it's searched once (deduplicated by lorebook ID)
- The
linked_lorebook_idon the tracker itself (if set) is always active regardless of member presence -- it's the tracker's own lorebook, not a member's
How It Differs from Lorebook-Based Rosters
| Aspect | Lorebook-based roster | Character group |
|---|---|---|
| Data source | Lorebook entries (manually written) | Character entities (already exist) |
| Reusability | Lorebook entry is a one-off | Same character can be in multiple groups |
| Maintenance | Updating character info = editing lorebook entry | Updating character = updating the character entity (all groups get the update) |
| Discoverability | Lorebook entries are not browsable entities | Characters are browsable, shareable, have avatars and pages |
| Creation effort | Write a lorebook entry per NPC | Add an existing character to the group |
| Always-on summary | On the lorebook entry | On the group membership |
| Full detail | Lorebook entry content | Character system prompt (or override) |
| Attached lorebooks | N/A (entries don't have lorebooks) | Character's own lorebooks activate/deactivate with presence |
Both approaches coexist. A tracker can have a linked_lorebook_id AND a linked_character_group_id simultaneously. This is useful when some NPCs are full Character entities (important recurring characters worth their own page) while others are lorebook entries (one-off NPCs, environmental characters). The injection logic handles both:
- Always-on summaries from both character group members and lorebook entries (shared token budget)
- Present characters: inject system prompt (or override) for group members, inject lorebook entry content for lorebook matches
- Present group members' attached lorebooks become active for search
- Deduplication by name if a group member and lorebook entry overlap
Setup Example
Character Group: "Shadowkeep Cast" (id: 12)
Members:
- Elara (character_id: 42)
AlwaysOnSummary: "Elara - ranger from the Northern Reaches, companion."
OverrideSystemPrompt: null (use Elara's own system prompt)
SortOrder: 0
- Grimjaw (character_id: 87)
AlwaysOnSummary: "Grimjaw - veteran dwarven fighter, seeking his lost brother."
OverrideSystemPrompt: "Grimjaw is a gruff dwarven fighter. Twin axes.
Secretly sentimental. Looking for his brother
who vanished in Shadowkeep."
SortOrder: 1
- The Shadow King (character_id: 153)
AlwaysOnSummary: "The Shadow King - ancient lich ruling Shadowkeep."
OverrideSystemPrompt: null
SortOrder: 2
Tracker: "party"
Name: "Party Members"
Key: "party"
ValueType: list
InitialValue: ["Elara", "Grimjaw"]
ExtractionHint: "Track which party members are present in the scene."
LinkedCharacterGroupId: 12 (Shadowkeep Cast)
Tracker value: ["Elara", "Grimjaw"]
Injected into prompt:
1. Always-on summaries for ALL members (Elara, Grimjaw, Shadow King)
2. Full system prompts for PRESENT members only (Elara, Grimjaw)
3. Shadow King's full prompt is NOT injected (saving tokens)
Active lorebook search set:
- Conversation-bound lorebooks (always active)
- Elara's lorebooks: "Northern Reaches Lore", "Ranger Abilities" (PRESENT → active)
- Grimjaw's lorebooks: "Dwarven Clans", "Shadowkeep History" (PRESENT → active)
- Shadow King's lorebooks: "Undead Army Tactics" (ABSENT → NOT active)
Scene change: Grimjaw leaves, Shadow King appears
→ Evaluation updates: ["Elara", "Shadow King"]
→ Next message:
1. Always-on summaries: still all members
2. Full prompts: Elara + Shadow King
3. Grimjaw's full prompt drops out
4. Lorebook shift: Grimjaw's lorebooks deactivate, Shadow King's activate
→ "Undead Army Tactics" now searchable, "Dwarven Clans" drops out
Name Matching
The tracker value (a list of strings extracted by the evaluation LLM) needs to match against character members. Matching is by character name -- the tracker value "Elara" matches the character member whose character entity is named "Elara".
For robustness, the match should be case-insensitive and support the character's name as the primary match key. The ExtractionHint should guide the evaluation LLM to use exact character names from the group.
Database Schema
-- Character groups (lightweight entity — named collection of characters)
CREATE TABLE IF NOT EXISTS character_groups (
id SERIAL PRIMARY KEY,
created_by_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
uuid UUID NOT NULL DEFAULT gen_random_uuid(),
name VARCHAR(60) NOT NULL DEFAULT '',
description VARCHAR(500) NOT NULL DEFAULT '',
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Character group members
CREATE TABLE IF NOT EXISTS character_group_members (
id SERIAL PRIMARY KEY,
character_group_id INTEGER NOT NULL REFERENCES character_groups(id) ON DELETE CASCADE,
character_id INTEGER NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
always_on_summary TEXT, -- short summary for when character is absent
override_system_prompt TEXT, -- optional override for group context
sort_order INTEGER NOT NULL DEFAULT 0, -- display ordering and summary priority
UNIQUE(character_group_id, character_id)
);
-- Tracker links to a character group via FK (same pattern as linked_lorebook_id)
-- linked_character_group_id INTEGER REFERENCES character_groups(id) ON DELETE SET NULL
-- (on the trackers table)
These tables are included in the implementation map. The character_groups and character_group_members tables live alongside the tracker tables in the same migration (see the file-numbering note above — target the next free 5x_ slot, not the original 31_* which is now taken by galleries).
Conditional Entries: Tracker-Gated Lorebook Content
Conditional entries are lorebook entries that only activate when specific tracker conditions are met. Instead of relying solely on keyword/vector matching against recent messages, these entries have explicit activation rules tied to tracker state -- making them deterministic and creator-controlled.
This is a fundamental shift: regular lorebook entries are reactive (they fire when the conversation mentions something relevant). Conditional entries are state-driven (they fire when the world is in a specific state, regardless of what was just said).
Why this matters:
Trackers give the system structured, always-current knowledge about the state of the world. Conditional entries let creators build content that responds to that state. Together, they enable experiences that were previously impossible:
- Story progression: Lorebook entries that unlock as a quest advances through stages
- Arc progression: Character backstory entries that only appear after enough trust is built
- Environmental events: Location-specific content that changes based on time of day
- Party-dependent encounters: Content that activates only when specific characters are present
- World state reactions: Entries that reflect consequences of player choices tracked via state
The concept:
A lorebook entry gains optional conditions -- rules that reference tracker keys and required values. The entry only injects when ALL conditions are satisfied:
Lorebook Entry: "Shadowkeep Night Patrol"
Keywords: ["Shadowkeep", "patrol", "undead", "corridor"]
Content: "At night, Shadowkeep's undead patrol the corridors in groups of
three. They follow a predictable route: throne room → east wing →
dungeons → back to throne room. Cycle takes ~30 minutes..."
Conditions:
- location CONTAINS "Shadowkeep"
- gametime CONTAINS "Night"
Lorebook Entry: "Elara Reveals Her Identity"
Keywords: ["Elara", "secret", "princess", "identity"]
Content: "If pressed about her past at the Northern Pass, Elara will reveal
she is the exiled princess of the Northern Reaches. She chose exile
rather than marry the Shadow King's emissary..."
Conditions:
- location CONTAINS "Northern Pass"
- roster CONTAINS "Elara"
Lorebook Entry: "Act 2 - The Shadow King Awakens"
Keywords: ["Shadow King", "awakens", "undead", "army"]
Content: "The Shadow King has fully awakened. Undead armies now march across
the northern territories. NPCs react with fear. Towns are fortifying.
The Crystal of Dawn is the only hope..."
Conditions:
- story_arc = "act_2"
Lorebook Entry: "Grimjaw Opens Up"
Keywords: ["Grimjaw", "brother", "trust", "past"]
Content: "After earning Grimjaw's trust, he'll share that his brother didn't
just vanish in Shadowkeep -- he was betrayed by their father who
sold the brother's location to the Shadow King..."
Conditions:
- relationship_grimjaw >= 7
What this enables for creators:
| Pattern | Tracker conditions | Effect |
|---|---|---|
| Day/night cycle | location + gametime | Different encounters, NPC availability, shop hours |
| Story arcs | story_arc (enum tracker) | Entire lorebook sections that unlock per act/chapter |
| Quest stages | current_quest + quest_stage | Progressive quest info -- clues unlock as you progress |
| Relationship gates | relationship_X (numeric tracker) | Character backstory, secrets, romance paths unlock at thresholds |
| Party composition | roster (list tracker) | Interactions that only happen when specific NPCs are together |
| Environmental | weather, season, time | Seasonal events, weather-dependent paths, crop cycles |
| Consequence tracking | custom state trackers | "The bridge is destroyed" → all entries about the bridge reflect its destruction |
Implementation roadmap:
Phase 1: Concatenated tracker search (v1, with initial tracker release)
No changes to lorebook entries. Tracker values are appended to the search query, so lorebook entries with relevant keywords naturally match when tracker state aligns:
Tracker state: location="Shadowkeep", gametime="Night"
Search query: [recent messages] + "Shadowkeep" + "Night"
→ Entry with keywords ["Shadowkeep", "night", "patrol"] matches naturally
This is imprecise (keyword overlap can cause false positives) but requires zero lorebook schema changes and covers common cases. Creators design their keywords to align with expected tracker values.
Phase 2: Explicit conditions on lorebook entries (future)
Lorebook entries gain optional condition fields that reference tracker keys:
-- Conditions on lorebook entries (future schema)
CREATE TABLE lorebook_entry_conditions (
id SERIAL PRIMARY KEY,
lorebook_entry_id INTEGER REFERENCES lorebook_entries(id),
tracker_key VARCHAR(50) NOT NULL, -- which tracker to check
operator VARCHAR(20) NOT NULL, -- "contains", "equals", "gte", "lte", "in"
value TEXT NOT NULL, -- expected value or threshold
UNIQUE(lorebook_entry_id, tracker_key) -- one condition per tracker per entry
);
The search pipeline adds a post-filter: after keyword/vector matching returns candidate entries, check each entry's conditions against current tracker values. Entries whose conditions aren't met are filtered out before injection.
Phase 3: Condition groups and complex logic (future)
AND/OR grouping, nested conditions, "any of these trackers" patterns. Only if Phase 2 proves too limiting for real creator use cases.
Design implications for trackers:
The tracker entity design should accommodate conditional entries from the start:
Stable tracker keys: Since conditions reference tracker keys by string (
"location","gametime","story_arc"), keys must be stable identifiers. Renaming a tracker key would break conditions on lorebook entries. Thekeyfield on the tracker entity should be immutable after creation (or rename should cascade to conditions).Typed comparisons: Numeric trackers need
>=,<=comparisons (relationship thresholds). Enum trackers need exact match. List trackers need "contains" checks. Freeform trackers need substring/contains matching. The trackerValueTypedirectly determines which condition operators are valid.Tracker value visibility to lorebooks: Lorebook entries need to know which trackers exist and what keys/values are available. The Forge lorebook editor should show available tracker keys from bound characters when creating conditions.
Package integration: Packages that bundle trackers + lorebooks can pre-wire conditions. A "Fantasy RPG" package ships with a
story_arcenum tracker and lorebook entries conditioned on each arc stage -- everything works out of the box.
Search Integration Details
The lorebook search pipeline gains an additional input source:
Existing search inputs:
1. Recent messages (last N per MessageScanDepth)
2. Last assistant response (for vector embedding context)
New search input:
3. Active tracker values (all trackers, concatenated)
For linked-lorebook trackers:
- Tracker value searched against ONLY the linked lorebook
- Results injected alongside tracker values in the "trackers" provider output (keeps state + context together)
- Deduplication by entry ID against general lorebook results (tracker-linked result takes precedence)
For unlinked trackers:
- Tracker values appended to the general search query
- Boost all lorebook searches across all bound lorebooks
Budget considerations: Linked-lorebook results have their own entry budget (linked_lorebook_max_entries on the tracker definition, default 3), separate from Knowledge.MaxEntries used by the general lorebook provider. A separate budget per linked tracker prevents one tracker from consuming the entire entry allowance. Individual lorebook entries should stay under ~500 tokens for optimal search relevance and token efficiency -- see Design Principles: Token Budget.
Summarization Integration
The existing tracker_start_json / tracker_end_json on summaries already captures state boundaries. With proper tracker entities, summaries can include richer context:
Summary for messages 41-50:
Tracker changes: Game Time advanced from "Day 3, Morning" to "Day 3, Evening".
Party moved from Shadowkeep Level 2 to Level 3. HP dropped from 72 to 65
after the goblin ambush.
Timeline / History View
Since every message stores tracker_json, the UI can render a timeline showing how values changed over the conversation. Useful for:
- Debugging ("when did my HP drop?")
- Recap after returning to a conversation
- Visualizing numeric trackers as charts
Scope: Where a Tracker Definition Lives
Trackers use the same three-scope ownership model as lorebooks: conversation, character, or package. The scope says where the tracker definition is bound, not whether values persist across conversations.
| Scope | Behavior | Examples |
|---|---|---|
character |
Tracker rides with the character. Auto-activates in any conversation that uses the character, regardless of which package (if any) wraps it. | A character whose schtick is HP tracking — HP travels wherever the character goes. |
package |
Tracker rides with the package. Auto-activates in any conversation started from the package. Respects trackers_locked (see Package Integration). |
A "Fantasy RPG" package's story_arc enum, gold counter, quest_stage — none of these make sense outside the package's experience. |
conversation |
Tracker is bound to one specific conversation only — same as ad-hoc lorebooks a user adds to a single chat. Doesn't follow the character or package. | A user one-off ("I want to track my mood in this conversation only"), or a temporary tracker the user adds for an experiment. |
All three scopes use the same binding-table pattern as lorebooks:
character_tracker_bindings (character_id, tracker_id, override_initial_value, sort_order, is_required)
package_tracker_bindings (package_id, tracker_id, override_initial_value, sort_order, is_required)
conversation_tracker_bindings (conversation_id, tracker_id, priority)
A conversation auto-activates the union of:
- Its character's bindings (via
character_tracker_bindings) - Its package's bindings, if started from a package (via
package_tracker_bindings) - Any conversation-scoped trackers the user added directly from the WhoDrawer (via
conversation_tracker_bindings)
A tracker can live in any of the three binding families — same definition shape, different home. The user can pull an extra tracker into one conversation via conversation_tracker_bindings without touching the character or package definition, exactly as the lorebook flow already works.
No cross-conversation value persistence in v1
Tracker values are per-conversation (tracker_json on messages). They do not carry across conversations. The earlier design routed character-scoped persistence through a Journal commit action; Journal Phase 1 shipped as a per-conversation "game save" with no portability, and "cross-conversation persistence" is explicitly listed in Journal's Out of Phase 1 set. There is no rail to ride.
If cross-conversation continuity is needed later (relationship levels carrying between playthroughs, quest stages that don't reset), it lands as a Phase 2+ topic alongside whatever Journal materialization eventually ships — almost certainly as a deliberate "commit checkpoint" action, never automatic, never magic.
Until then: starting a new conversation re-initializes all trackers from their binding's override_initial_value (or the tracker's own InitialValue if no override). That's the whole story.
Phase 1 — Freeform / Character-Scope MVP
The full design above is the long-term target. Phase 1 ships only the smallest end-to-end slice that proves the eval rail, drawing inspiration from how Journal Phase 1 shipped (entries-only, freeform, no entity profiles). Once Phase 1 is in users' hands and producing real eval output, Phase 2 layers on typed values, lorebook linkage, the other two scopes, and the rest.
Mental model: the equivalent to Journal's "entries-only" slice
Journal Phase 1 shipped freeform text entries, per-conversation, always-on, with a manual + AI-eval mix. Tracker Phase 1 ships freeform key:value pairs, character-bound, injected into every turn, with a manual + AI-eval mix. Same eval-rail shape (sharing the bases extracted above), but a completely different data model, prompt, and user surface. Together they cover the two halves of the always-on state surface; the two evaluations race in parallel as fire-and-forget post-LLM stages.
Locked decisions
| Decision | Choice |
|---|---|
| Value type | numeric / percentage / enum / list / datetime, in addition to freeform) landed right after to avoid "do-everything" freeform trackers. value_type + per-type config (numeric_min/numeric_max, enum_values, datetime_format) on the trackers table drive the eval instruction, validation, and the chat-bar visual independently. Storage stays a flat {key:"string"} map (list = canonical JSON-array string); TrackerValueFormatter is the shared encode/decode/render. percentage is its own type (the LLM grounds on the word) and datetime is freeform-with-a-format-hint (in-world time). Deliberately deferred: per-type eval accuracy tuning (numeric drift, Risk #1) — tuned from real usage now that creators can author typed trackers. |
| Scope | character only. No package, no conversation. Skips the binding-union complexity (character + package + conversation overlay) and the package-lock UX entirely. Packages already have trackers_locked reserved on the column; that flag stays unused until Phase 2. |
| Linked lorebooks | Out. No linked_lorebook_id, no linked_character_group_id, no presence-aware injection, no always_on_summary field on lorebook entries, no character groups. The whole "tracker-aware lorebook search" arm waits for Phase 2 — once Phase 1 proves users want richer extraction, we know whether to invest in the lorebook coupling. |
| Injection | State block appended to the last user message (the Part 1 design). No system-prompt content provider in v1 since there's nothing to inject there (no linked lorebooks, no group prompts). When Phase 2 adds linked content, the WebTrackerContentProvider graduates to also emitting system-level content. |
| Eval cadence | Per-conversation tri-state setting: per_message / on_summarization / off. Same shape as Journal.EvalCadence. The on-summarization path runs as a separate second LLM call after summarization completes, matching the Journal pattern exactly. Superseded 2026-10-24: trackers are off / per_message only — the on-summarization cadence is retired (owner: "remove trackers on summary cadence, it has no sense"); see Trackers run per message or not at all in the as-built notes. |
| Eval output schema | { "trackers": { "<key>": "<new_value>", ... } } — only changed values, omit unchanged. No add/update/delete distinction (a tracker's key is its identity; setting a value is always upsert). Manual edits are sacred — the eval call only ever writes to message rows the user hasn't touched. |
| JSON-mode | LlmRequest.RequireJsonObject = true on every eval call. Each ILlmClient translates to its provider's native JSON-mode (OpenAI / Gemini / Anthropic prefill trick) — primitive already shipped for Journal Phase 1.5, no new work. |
| Source attribution | tracker_json values on messages are stored alongside source metadata (manual / eval) and an updated_at snapshot for optimistic concurrency. Eval skips updates to manually-edited tracker values, matching Journal Phase 1 decision H. |
| Feature toggle | Features.EnableTrackers (default true), per-conversation override defaulting from a user preference, resolved through ?? true. When off: no injection AND no eval LLM call. Surface: HowDrawer Active Features panel, sibling to the existing Journal toggle. |
| Mode-supports gating | REVISED 2026-05-31 — trackers are NOT mode-gated (this reverses the original "same as Journal" decision). The eval is a fully separate pass that maintains state from each tracker's own extraction hints, so it needs no mode-level sub-prompt to function. Trackers run on any mode; the toggle is always available. A mode that omits the "tracker" sub-prompt only triggers a soft UI warning ("this mode doesn't describe your trackers to the model"), never a mode-locked lock. ModeSupports.tracker is still computed but now drives that warning, not a gate. (Journal stays mode-gated — the divergence is intentional.) |
| Preset assignment | JournalEvalLlm-style settings family: TrackerEvalLlm.{Provider,Model,ApiKey,Endpoint,PresetId}. "Use for Trackers" action on every LLM preset card, alongside the existing "Use for Chat" / "Use for Summary" / "Use for Journal". Fallback chain: TrackerEvalLlm → JournalEvalLlm → SummarizationLlm → Llm → default built-in. (Since superseded: the per-card "Use for …" actions are gone — assignment is the Tracker eval row of Settings → LLM → Pipeline stages. Chain unchanged.) |
| Visibility | Master toggle on conversation (show_trackers BOOLEAN) + collapsed tracker bar below assistant messages + inline edit with carry-forward. No context menu for per-message expanded view in v1, no timeline/history view, no "Why?" link, no evaluation log UI — those land in Phase 2 after the eval is proven. Inline edit on the bar is the only correction surface; carry-forward via tracker_json chain (the existing column shape already supports this). |
| Regenerate | Out. No regenerate-from-conversation in v1. Add in Phase 1.6, mirroring the Journal Phase 1.6 chunked-walk shape exactly (it's a strict win when the eval has been wrong across many messages, but it's not v1-blocking). |
| Echo cost | Deferred. Free in v1, same as Journal Phase 1. Wire to per-call billing once platform-model cost work covers this lane. |
| Sharing / publishing | Trackers are standalone entities and can be shared via the existing EntityPermission system. Tracker values are per-conversation game-save state — not included in published conversation snapshots, exactly like Journal entries. |
| Branching | override_initial_value (or the tracker's InitialValue).fn_branch_conversation copies tracker_json per message, so a branch resumes from the branch point's state. See the SHIPPED callout. |
| Audience tier | Owner only in v1 — same as Journal Phase 1. Hub discovery and public/admin views in Phase 2. |
Out of Phase 1
For absolute clarity, these are explicitly not part of the first slice:
Numeric, enum, list value types — and everything they enable (tracker bars, chips, progress visualizations)— shipped 2026-05-31 (post-Phase-1):numeric/percentage/enum/list/datetimewith per-type chat-bar visuals (ProgressBar / Badge / chips / clock) and a sharedTrackerTypeFieldsForge sub-form. See the "Value type" row in the scope-decisions table above.packageandconversationscopes — andpackage_tracker_bindings,conversation_tracker_bindings, thetrackers_lockedflag, conversation-level add/remove from the WhoDrawer- Linked lorebooks (
linked_lorebook_id) and the entire tracker-aware lorebook search arm - Character groups and presence-aware injection (no new
character_groups/character_group_memberstables) always_on_summarycolumn onlorebook_entries- Conditional entries (lorebook entries gated by tracker state)
- Per-message expanded tracker view, timeline / history view, "Why?" context, evaluation log UI
- Regenerate-from-conversation (Phase 1.6)
- Tracker statistics surfaced in admin / creator analytics (the table + metric ship in v1, dashboards are Phase 2)
- Discord parity (web-only)
- Cross-conversation value persistence (not coming back — see Scope)
Phase 1 schema delta
-- database/v1/68_tables_trackers.sql (next free table slot after 67_tables_journal.sql)
CREATE TABLE IF NOT EXISTS trackers (
id SERIAL PRIMARY KEY,
created_by_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
uuid UUID NOT NULL DEFAULT gen_random_uuid(),
name VARCHAR(60) NOT NULL DEFAULT '',
key VARCHAR(50) NOT NULL DEFAULT '',
description VARCHAR(500) NOT NULL DEFAULT '',
initial_value TEXT,
extraction_hint TEXT,
injection_mode SMALLINT NOT NULL DEFAULT 0, -- 0=full, 1=compact
is_visible BOOLEAN NOT NULL DEFAULT TRUE,
-- Standard entity-shape columns (tags / is_public / is_deleted / timestamps)
tags_0 BIGINT NOT NULL DEFAULT 0,
tags_1 BIGINT NOT NULL DEFAULT 0,
tags_2 BIGINT NOT NULL DEFAULT 0,
tags_3 BIGINT NOT NULL DEFAULT 0,
tags_4 BIGINT NOT NULL DEFAULT 0,
tags_5 BIGINT NOT NULL DEFAULT 0,
tags_6 BIGINT NOT NULL DEFAULT 0,
is_public BOOLEAN NOT NULL DEFAULT FALSE,
published_at TIMESTAMP WITH TIME ZONE,
scheduled_publish_at TIMESTAMP WITH TIME ZONE,
is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX idx_trackers_uuid ON trackers(uuid);
CREATE INDEX idx_trackers_created_by_user_id ON trackers(created_by_user_id);
CREATE UNIQUE INDEX idx_trackers_owner_key ON trackers(created_by_user_id, key) WHERE is_deleted = FALSE;
-- Character bindings (only binding family in v1)
CREATE TABLE IF NOT EXISTS character_tracker_bindings (
id SERIAL PRIMARY KEY,
character_id INTEGER NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
tracker_id INTEGER NOT NULL REFERENCES trackers(id) ON DELETE CASCADE,
override_initial_value TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
is_required BOOLEAN NOT NULL DEFAULT FALSE,
UNIQUE(character_id, tracker_id)
);
-- Per-eval-call stats. Mirrors journal_eval_stats shape (67_tables_journal.sql lines 48-100).
-- One row per eval LLM call, inserted in try/finally so failed calls still produce a row.
CREATE TABLE IF NOT EXISTS tracker_eval_stats (
id BIGSERIAL PRIMARY KEY,
conversation_id INTEGER NOT NULL,
user_id INTEGER,
provider VARCHAR(50) NOT NULL,
model VARCHAR(100) NOT NULL,
cadence VARCHAR(20) NOT NULL, -- 'per_message' (older rows: 'on_summarization', retired 2026-10-24)
prompt_tokens BIGINT,
completion_tokens BIGINT,
total_tokens BIGINT,
cache_creation_tokens BIGINT,
cache_read_tokens BIGINT,
api_latency_ms INTEGER,
trackers_updated INTEGER NOT NULL DEFAULT 0,
trackers_skipped INTEGER NOT NULL DEFAULT 0, -- skipped due to manual-edit concurrency
parse_status VARCHAR(20) NOT NULL DEFAULT 'ok', -- 'ok' | 'fallback' | 'failed'
error_type VARCHAR(50),
error_message TEXT,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_tracker_eval_stats_created_at ON tracker_eval_stats (created_at);
CREATE INDEX IF NOT EXISTS idx_tracker_eval_stats_conversation_id ON tracker_eval_stats (conversation_id);
CREATE INDEX IF NOT EXISTS idx_tracker_eval_stats_provider_model ON tracker_eval_stats (provider, model, created_at);
CREATE INDEX IF NOT EXISTS idx_tracker_eval_stats_user_created ON tracker_eval_stats (user_id, created_at) WHERE user_id IS NOT NULL;
The tracker_json column already exists on web_messages and web_summaries (tracker_start_json / tracker_end_json) — no schema change needed for the value storage path. The conversation_trackers table likewise already exists and remains as-is in v1. show_trackers BOOLEAN joins web_conversations for the master visibility toggle. No package_tracker_bindings, no conversation_tracker_bindings, no character_groups, no linked_* columns until Phase 2.
Phase 1 settings
| Key | Default | Description |
|---|---|---|
Tracker.DefaultMaxTrackers |
40 |
The count ceiling per owner (character, package, a chat's own): misuse prevention, far above a real story's set. Past it a bind is 422 tracker_limit_reached. As built: 8 until 2026-11-07, when the owner asked for "the maximum trackers higher, instead count the tokens"; 390 moves a database still on the old seed. See The token figure below. |
Tracker.DefaultEvalCadence |
per_message |
Default cadence applied to new conversations (off / per_message). As built: seeded on_summarization until 2026-10-08, when the owner set it to every message; a one-shot heal moves a database still on the old seed. Since 2026-10-24 on_summarization is no tracker cadence at all; a second heal moved every stored copy to per_message. Unset at every layer also resolves per message. |
Tracker.DefaultEvalPrompt |
(hardcoded fallback) | System-wide default eval prompt; mode can override |
Tracker.MaxTrackerTokens |
32000 |
The suggested limit on what a set of trackers adds to every turn, in tokens (owner, 2026-11-07: "make it 32k for now and when over the limit, put only WARNING"). A warning, never a refusal. Platform-only (C# seed). The sketch's 1500 soft cap was never read; the key now means this. |
Tracker.EvalCadence |
(inherits Tracker.DefaultEvalCadence) |
Per-conversation cadence override (off / per_message; on_summarization retired 2026-10-24) |
Features.EnableTrackers |
true |
Per-conversation toggle (user-default). When off: no injection AND no eval LLM call. Surface: HowDrawer Active Features panel (sibling to Features.EnableJournal at SettingsKeys.cs:671). |
TrackerEvalLlm.PresetId |
'' (empty) |
LLM preset assigned to tracker eval. Empty = fall through TrackerEvalLlm.* → JournalEvalLlm.* → SummarizationLlm.* → Llm.* → default built-in. Set via "Use for Trackers" on any preset card. |
TrackerEvalLlm.Provider / .Model / .ApiKey / .Endpoint |
(inherit from chain) | Resolved by LlmPresetEnricher when TrackerEvalLlm.PresetId is set; otherwise inherits through the fallback chain. |
fn_clear_preset_references (database/v1/66_fn_clear_preset_references.sql) gets a new branch that sweeps TrackerEvalLlm.PresetId on preset DELETE so deleted presets don't dangle — same one-line addition that's already there for JournalEvalLlm.PresetId.
The token figure (shipped 2026-11-07)
Owner, 2026-11-07: "we also need to make the maximum trackers higher, instead count the tokens" — then "make it 32k for now and when over the limit, put only WARNING".
What bounds a set of trackers is what it costs the story, not how many it holds. Each tracker has a token figure
(TrackerTokenCost, WebChat): its line in the tracker eval's prompt, built by the eval's own renderer
(TrackerEvalLlmService.AppendTrackerLine: key, hint, the type instruction with every allowed value, the examples its
type takes, a value), plus its line in the state block the story model reads (TrackerBlockRenderer.Line). The value is a
footprint: the longest the type declares (a numeric bound's digits, 100 for a percentage, the longest enum option, a
datetime's format), the tracker's start, or a 40-character phrase for a type that declares no length, whichever is
longest. Characters become tokens by ContextBudgetEstimate.Tokens (× 2 / 7), the How drawer's and the Forge prompt
estimate's divisor. A set's figure is the sum of its trackers'. Not counted: the text a set carries once whatever its size
(the eval's instructions, the block header, the mode's tracker section), a Place tracker's known-places list, and the
repeat of each reply's block in the history.
- Where it is read. Each binding (
BoundTracker.tokenCost) and each tracker read (OwnedTracker.tokenCost) carries its figure.GET /api/creator/trackers/limitsanswers{ maxTrackerTokens, maxTrackers }. A chat's bindings read addstrackerTokens(the story's whole set: inherited, built-ins and the chat's own, what its turns carry) andmaxTrackerTokens. A character's or a package's figure counts its own bindings: the built-ins depend on each story's switches, and the binder can't remove them there. - Over the limit (
Tracker.MaxTrackerTokens, 32,000) is a warning. The bind lands. A character bind answers 200{ revision, budgetWarning: { tokens, limit, message } }(204 / 200{ revision }as before when within it), a chat bind 200{ budgetWarning }, a package save its usual body withbudgetWarning. The message names both numbers: "These trackers add about 33,456 tokens to every turn, over the suggested 32,000. Long stories may run slower or cost more." There is no refusal code for it. - The count is a ceiling against misuse.
Tracker.DefaultMaxTrackersis 40 (it was 8; 40 is what the paid dry run takes in one run). Past it a bind is 422tracker_limit_reached, atomic infn_bind_tracker_to_owner(andfn_save_package_full); a built-in never counts toward it. - The Forge shows the figure under a character's bindings and a package's trackers ("These trackers add about N tokens to every turn. Suggested limit: 32,000."), the warning in its place when over, and each tracker's figure in the bind picker. A package's line reads its trackers' figures from the caller's tracker list, and shows only when every packaged tracker is found there (never a partial sum said as fact). Bind never closes for the figure; at the ceiling it dims with the 422's sentence. No chat surface shows the figure yet: neither the writing client's Trackers card nor chat.'s Trackers this story keeps (which shows a bind's warning, §T2). The read carries it.
- Measured (the code's own formatting): a one-sentence freeform tracker ≈ 53 tokens, a bare one ≈ 29, a 0–100 number ≈ 26, a percentage ≈ 35, a six-option enum ≈ 42, a list with two examples ≈ 64. A tracker at every field's cap (500-character hint, 600 of examples, 500-character start) ≈ 607; a 500-character hint with 1,000 characters of enum options ≈ 435. A typical set of eight is a few hundred tokens; forty trackers at the caps stay under 32,000. The warning is reached by a story's whole set (character, package and the reader's own, up to three ceilings) of long trackers, or by linked lists whose lorebook has many entries.
Pipeline integration
All shapes below assume the shared base extractions in the callout above have already landed — these classes extend the shared bases rather than parallel-copy from Journal:
- Provider:
WebTrackerContentProvider : IPromptContentProvider,Key = "tracker"(addContextKeys.Tracker = "tracker"to ContextKeys.cs). Lives inserver/EchoOfDreams.WebChat/Providers/. Tracker-specific (not extracted from Journal's provider — the two providers do entirely different work). In v1 the provider returns""— actual injection happens in the message-building stage that appends the state block to the last user message (the "Part 1" design). The provider exists so the prompt-context registry knows about the key and budget accounting has a hook; Phase 2 fills itsGetContentAsyncwith linked-lorebook content. - Eval service:
TrackerEvalLlmService : EvalLlmServiceBaseinCore/Services/Tracker/. Extends the shared eval-service base (JSON-mode call, forgiving parser, stats hook). Tracker-specific: prompt construction + result application (parse the{ "trackers": { key: value } }object and write it toOutputTrackerJson). Web-side wrapperWebTrackerEvalService : ITrackerEvalServiceinWebChat/Services/. - Post-LLM stage:
TrackerEvalStageBase : EvalPostLlmStageBase<ITrackerEvalService>,Order = 220(third sibling after Summarization=200, JournalEval=210). Lives inCore/Pipeline/Stages/. The base owns the gates (feature toggle,IsRegeneration, empty-response, regen lock, fire-and-forget Task.Run); the subclass plugs inSettingsKeys.Features.EnableTrackersand the per-stage service call. The fire-and-forget invariant is the base's responsibility — subclass cannot break it. (Journal'sJournalEvalStageBasedocuments the parallelism convention at lines 11–18; once extracted, the convention is enforced in the base.) On-summarization cadence: whenRemoved 2026-10-24 (owner: "remove trackers on summary cadence, it has no sense"): the summarization trigger dispatches only the journal's on-summarization eval; trackers run per message or not at all.Tracker.EvalCadence = on_summarization, the trigger fires from inside the summarization trigger after a successful summary, alongside the existing journal trigger.- Pipeline context already supports the value path: IPipelineContext.cs:126,140 already declares
InputTrackerJson/OutputTrackerJson. Eval stage writes toOutputTrackerJson;MessageStorageStageBasealready persists both (no changes needed). - Stats:
ITrackerEvalStatsRepository/TrackerEvalStatsRepositorymirrorWebSummaryStatsRepository. Newfn_stats_tracker_evalsindatabase/v1/functions/70_stats_functions.sql+ newStatsMetric("tracker_evals", ...)inDefaultStatsMetrics.Build. Allowed dimensions:provider,model,cadence,parse_status. (Dashboards don't change in v1 — the metric is just available to whoever queries it.) - Feature toggle:
Features.EnableTrackersin SettingsKeys.cs (place next toEnableJournal). HowDrawer Active Features wiring follows the existing Journal row in HowDrawer.tsx:1217–1221.WebChatFeatureStateServiceresolves the toggle (mirror the Journal-handling path). - Context budget: add a
trackerTokensfield on the context budget response next tojournalTokens(HowDrawer.tsx:378–489). Backend zeroes it out whenFeatures.EnableTrackersis off.
Files (Phase 1 only)
Two distinct work batches: (A) Extraction prep (lands first, each as its own commit, Journal tests still green after) and (B) Tracker feature (lands on top of the extracted bases).
Batch A — Extraction prep (refactor before feature delivery):
| Layer | Extract | Status (2026-05-29 implementation pass) |
|---|---|---|
| Core | New Core/Services/Eval/EvalJsonParser.cs (refactor JournalEvalParser onto it). |
✅ Done — JournalEvalParser delegates the code-fence / preamble / balanced-object mechanics; 64 Journal parser tests green untouched + 25 new EvalJsonParserTests. Array locator parameterised by property name (was hardcoded "entries"). |
| Core | New Core/Pipeline/Stages/EvalPostLlmStageBase.cs (refactor JournalEvalStageBase onto it). |
✅ Done — non-generic abstract base with hook methods (FeatureToggleKey, ModeSupportsAsync, ShouldRunPerMessage, IsRegenActiveAsync, RunPerMessageAsync); owns the gate order + fire-and-forget invariant. Journal stage tests green untouched + 11 new EvalPostLlmStageBaseTests. Generic test doubles extracted to EvalStageTestDoubles.cs (rule-of-two — second consumer arrived). Deviation from doc: base is non-generic, not EvalPostLlmStageBase<TService> — the base references no service type, so the generic was ceremony (simplest-solution rule). |
| Core | New Core/Services/Eval/EvalLlmServiceBase.cs (refactor JournalEvalLlmService onto it). |
✅ Done — base owns the call envelope only: CallLlmAsync(provider, endpoint, apiKey, model, maxTokens, systemPrompt, userContent) builds the JSON-mode request + temp-0.2 settings provider, calls the client, records stats + billing, maps provider errors, returns EvalLlmCallOutcome(RawContent, EvalCallTelemetry). Subclass keeps settings resolution / prompt / parsing / its own metadata record (maps telemetry → JournalEvalMetadata, so WebJournalEvalService + stats insert are untouched). Hooks: StatsPrefix, FeatureLabel, virtual RecordBillingTokens (journal → JournalEvalCallContext). JournalEvalLlmServiceTests (RequireJsonObject + JournalEvalLlm→SummarizationLlm fallback chain + ResolveMaxTokens) green untouched + WebChat orchestrator tests green + 12 new EvalLlmServiceBaseTests. |
| Core (bonus — found mid-pass) | De-dup SummarizationLlmService.StripMarkdownCodeBlock onto EvalJsonParser. |
✅ Done — SummarizationLlmService had a byte-identical copy of the code-fence stripper (journal's parser docstring already credited summarization as the pattern's origin). Pointed it at EvalJsonParser.StripMarkdownCodeBlock and deleted the local copy — summarization is now the third consumer of the shared primitive, retroactively confirming the extraction wasn't speculative. Summarization tests green. (Summarization keeps its simpler raw-text fallback; it does not use the array-salvage/preamble layers — those are journal/tracker-shaped. A latent improvement, left out of scope.) |
| Database | EvalStatsRepositoryBase.cs |
❌ Skipped — not worth doing (verified by reading the code). JournalEvalStatsRepository and WebSummaryStatsRepository are each ~12 lines: RepositoryBase<object> + one ExecuteFunctionAsync mapping a feature-specific record to a feature-specific fn_insert_*. The plumbing already lives in RepositoryBase; the try/finally "insert even on failure" is in the caller (eval service); the param mapping is irreducibly per-feature (different columns, different SQL function). A <TRow> base would hold nothing and the override would be the whole method — artificial abstraction. Batch B's TrackerEvalStatsRepository is a ~12-line parallel, and that's correct, not debt. |
| WebChat | Consolidate feature-toggle resolution in WebChatFeatureStateService. |
⏭ Deferred to Batch B (premature now). The file's per-feature blocks are parallel but carry genuinely different logic (memories cascade on summaries; lorebook gates on semantic + images + has-entries). The only uniform shape is the simple subprompt-bound toggle, which today has exactly one consumer (journal). Trackers is the second — so the consolidation (if any) happens when the tracker row is added in Batch B, with both consumers in front of you. The doc itself says "the fifth consumer (trackers) is the trigger." |
| Frontend | FeatureToggleRow from HowDrawer |
✅ Already exists. FeatureRow is already the shared component — Memories / Lorebook / Picture entries / Journal all use it, and a <FeatureRow label="Trackers" state={{ kind: 'coming-soon' }}> stub already sits in HowDrawer.tsx. Batch B flips that row from coming-soon to a live toggle; no extraction needed. |
Batch A testing — extraction is only safe if it's test-guarded. An extraction's definition of done is "behavior provably unchanged," which means tests, not a green compile. Two layers, and both gate every Batch A commit (use the dotnet-blackbox-tests skill when writing any of these):
| Test layer | What | Why |
|---|---|---|
| Regression net (must stay green, behavior unchanged) | The existing Journal eval suite: JournalEvalStageBaseTests, JournalEvalLlmServiceTests, JournalEvalParserTests, WebJournalEvalServiceTests, WebJournalContentProviderTests, LlmPresetEnricherJournalFallbackTests, JournalEvalStatsRepositoryTests. |
These pin Journal's observable behavior. After each extraction commit they must pass with their assertions untouched (only mechanical edits allowed — e.g. a moved namespace). A change in intent here means the refactor changed behavior — stop and reconcile. They are the proof that "Journal now rides the shared base" didn't regress Journal. |
| New coverage on each extracted primitive | Core.Tests/Services/Eval/EvalJsonParserTests.cs (port + own the forgiving-parse cases against the standalone primitive: code-fence strip, prose-preamble strip, balanced-brace recovery, truncated-JSON salvage). Core.Tests/Pipeline/Stages/EvalPostLlmStageBaseTests.cs (the shared gate/fire-and-forget invariants — feature-toggle off short-circuits, IsRegeneration skip, empty-response skip, ProcessAsync returns before the LLM call completes — tested via a trivial fake subclass, not through Journal). Database.Tests/Repositories/EvalStatsRepositoryBaseTests.cs (try/finally insert-on-failure pattern via a fake row type). |
The whole point of extraction is that the primitive now has two consumers. It earns its own tests so a future change to the base is caught at the base, independent of either Journal or trackers. The parser and the fire-and-forget gate are pure/deterministic and the highest-value targets. |
The work order per extraction: (1) confirm the relevant Journal test(s) green on develop, (2) extract the base + refactor Journal onto it in one commit, (3) Journal tests still green, (4) add the primitive's own test file, (5) commit. Five small commits, each independently green — not one big "extract everything" commit. Note: EvalStatsRepositoryBaseTests and the fallback-chain test live in Database.Tests, which needs a live PostgreSQL instance and is the dev's manual 40-min run — don't block a commit on it locally; the Core.Tests layer is the fast gate.
Batch B — Tracker Phase 1:
| Layer | New / Modified |
|---|---|
| DB tables | New: database/v1/68_tables_trackers.sql (trackers + character_tracker_bindings + tracker_eval_stats) |
| DB functions | New: database/v1/functions/78_tracker_functions.sql (fn_upsert_tracker, fn_delete_tracker); modify 66_fn_clear_preset_references.sql to sweep TrackerEvalLlm.PresetId; add fn_stats_tracker_evals to functions/70_stats_functions.sql |
| Core | New: Pipeline/Stages/TrackerEvalStageBase.cs, Services/Tracker/{ITrackerEvalLlmService,TrackerEvalLlmService,TrackerEvalParser}.cs. Modify: ContextKeys.cs (+Tracker = "tracker"), SettingsKeys.cs (+Features.EnableTrackers, +TrackerEvalLlm.*, +Tracker.*), SettingsDefaults.cs, Entities/EntityRegistry.cs (+Tracker = 15 — next free slot; 14 is BlogPost) |
| Database | New: Interfaces/ITrackerRepository.cs, Repositories/TrackerRepository.cs, Interfaces/ITrackerEvalStatsRepository.cs, Repositories/TrackerEvalStatsRepository.cs. Modify: Services/LlmPresetEnricher.cs (add TrackerEvalLlm to fallback chain) |
| WebChat | New: Providers/WebTrackerContentProvider.cs, Services/{IWebTrackerEvalService,WebTrackerEvalService}.cs. Modify: Services/WebChatFeatureStateService.cs, Services/WebSummarizationTriggerService.cs (on-summarization cadence — removed for trackers 2026-10-24), WebChatServiceCollectionExtensions.cs (DI) |
| ServerAPI | New: Api/Endpoints/CreatorTrackerEndpoints.cs (CRUD), Api/Endpoints/TrackerEvalEndpoints.cs (per-message manual edit). Modify: Program.cs (route mounts + DI) |
| clientConsole | New: api/trackers.ts, pages/creator/TrackerFormPage.tsx, components/chat/TrackerBar.tsx. Modify: types/entities.ts (+Tracker), constants/settingKeys.ts, pages/chat-v2/components/HowDrawer.tsx (+EnableTrackers row, budget segment), pages/chat-v2/components/WhoDrawer.tsx (trackers section after Greeting, before Persona) |
| shared | Add Tracker: 15 to utils/entityTypes.ts |
| Tests | Core.Tests/Pipeline/Stages/TrackerEvalStageBaseTests.cs, Core.Tests/Services/Tracker/TrackerEvalLlmServiceTests.cs, WebChat.Tests/WebTrackerContentProviderTests.cs, WebChat.Tests/WebTrackerEvalServiceTests.cs, WebChat.Tests/WebChatFeatureStateServiceTrackersTests.cs |
What Phase 2 picks up
Once Phase 1 ships and produces real eval-call output, Phase 2 layers on (in this rough order, demand-driven):
- Numeric / enum / list value types + the validation + visualization that comes with them (HP bars, chips, enum highlights)
packageandconversationscopes +package_tracker_bindings,conversation_tracker_bindings, thetrackers_lockedUX, conversation-level add/remove from the WhoDrawer- Regenerate-from-conversation (Phase 1.6 in journal-speak — chunked walk, SSE progress, regen lock)
- Linked lorebooks (
linked_lorebook_id) and the tracker-aware lorebook search arm always_on_summaryonlorebook_entries+ character groups + presence-aware injection- Per-message expanded tracker view + timeline + "Why?" + evaluation log UI
- Conditional lorebook entries (Phase 2 of the tracker-driven lorebook story)
Cross-conversation value persistence is out of all phases until Journal materialization lands — see Scope.
Entity-surface coverage & promotion plan
Audit added 2026-05-31, after the Phase 1 ship. Trackers is a first-class entity (EntityType.Tracker = 15) but Phase 1 wired only the owner + eval-pipeline half of the standard entity surface. This section records, dimension by dimension, what a mature entity (reference: Lorebook) exposes vs what Tracker actually wires today, then sequences the work to promote Tracker to a full public entity. Most gaps are intentional Phase-1 scope (the Locked decisions say "Audience tier: owner only in v1; hub discovery and public/admin views in Phase 2") — this turns those one-liners into concrete file-level work.
Coverage snapshot (vs Lorebook)
| Dimension | Lorebook | Tracker | Where it's proven |
|---|---|---|---|
| Entity-type registration (C# + SQL + shared TS) | ✅ | ✅ | EntityRegistry.cs:214, 00_entity_registry.sql, entityTypes.ts |
| Owner CRUD (+ inline-edit PATCH) | ✅ | ✅ | CreatorTrackerEndpoints.cs, …/tracker-state |
| Soft-delete + entity-shape columns | ✅ | ✅ | 68_tables_trackers.sql |
| Owner binding UI (character) | ✅ | ✅ | CharacterTrackerBindingEndpoints.cs, CharacterTrackersSection.tsx |
| Feature toggle + settings family | n/a | ✅ | SettingsKeys.cs, settingKeys.ts |
| Eval pipeline + user-message injection | n/a | ✅ | the core feature |
| Audience-tier DTOs | ✅ 3 tiers | 🟡 owner + bound only | OwnedTracker / BoundTracker; no PublicTracker/admin tier |
| Analytics | n/a | 🟡 data only | tracker_eval_stats + fn_stats_tracker_evals + StatsMetric("tracker_evals") reachable via GET /api/creator/stats/tracker_evals; no UI |
| Package/conversation/mode binding | ✅ | 🟡 forward-designed | entity_tracker_bindings CHECK owner_type IN (0,1,4,6); only character (0) wired |
Sharing / permissions (EntityPermission) |
✅ | ❌ | SupportsPermissionsApi=false; no authorizer for 15 |
| Publish flow / moderation | ✅ | ❌ | PublishRequestsEndpoints.cs gate hardcodes >2 && !=6 → rejects 15 |
| Browse / discovery / hub | ✅ | ❌ | no BrowseTrackersAsync; the Forge "Trackers" tab is a private owner list |
| Comments | ✅ | ❌ | not in CommentsEndpoints / EntityCommentSettings maps |
| Favorites / bookmarks | ✅ | ❌ | no user_tracker_bookmarks |
| Tags (catalog + filter) | ✅ | ❌ | no TrackerTags.cs; tags_0..6 inert |
| Proposals / collaboration | ✅ | ❌ | not in EntityProposalEndpoints; blocked on permissions |
| OpenGraph / public share page | ✅ | ❌ | ViewPathTemplate=null; no /browse/tracker/{uuid} |
| Import / export | ✅ | ❌ | none |
| Changelog | ✅ | ❌ | not in CreatorChangelogEndpoints.EntityMap |
| Cover image / gallery | ✅ | ❌ (by design) | trackers carry no picture column — not planned |
| Profile dashboard sections | ❌ | ❌ | Lorebook lacks it too — not a gap vs the reference |
Promotion plan (sequenced)
Each slice is independently shippable; the dependency arrows are the only ordering constraint. Effort is rough (S/M/L).
E1 — Loose ends (S, no new surface, do anytime). ✅ SHIPPED 2026-05-31. No dependencies.
- ✅ Enforce
Tracker.DefaultMaxTrackers(seeded8). Atomic + race-free:fn_bind_tracker_to_ownerdoes count+check+upsert under a per-ownerpg_advisory_xact_lockand returns'bound'/'limit_reached'(re-bind bypasses the cap; soft-deleted trackers don't count). The endpoint resolves the cap from settings, maps'limit_reached'→ 422{error, cap}; the frontend surfaces it. This is also the owner-generic bind primitive E6 reuses (rule-of-two — built while wiring the cap). (was flagged Phase 1.1) - ✅ Changelog:
trg_tracker_changelogon thetrackerstable (entity_type 15, create/update field-diff, mirrors the lorebook trigger) +["trackers"] = (EntityRegistry.Tracker, "created_by_user_id")inCreatorChangelogEndpoints.EntityMap. Not inSharedAccessTypes(owner-only until E5). - ✅ Analytics UI:
tracker_evalssurfaced on the Creator Analytics tab via the genericuseStatsQuery//api/creator/statspath (a hook + aChartCard, inside the existing Pro gate). Zero backend work. - ⏭ Owner-gate unify → deferred to E5. The shared
RequireEntityAccesshelper is for share-token/project-member entities; Tracker's strict-owner check is already correct. Unifying belongs with E5 (when trackers gain shared access), not E1 — forcing it now would be premature abstraction. TheToResponse→MapToOwnedTrackerrename is cosmetic and skipped.
E2 — Discoverability (M). Prereq for E3. Makes the entity public-readable.
PublicTrackerDTO (server browse model +clientConsole/src/types/entities.ts) +MapToPublicTrackerhelper.BrowseRepository.BrowseTrackersAsync+ add tracker to theBrowseEndpointsentity map.EntityDefinition.Tracker→ setViewPathTemplate: "/browse/tracker/{uuid}".- Frontend
/browse/tracker/{uuid}public detail page +ItemRenderertracker card case. - OpenGraph:
OpenGraphEndpointstracker case + cf-workergetBotRewritePath/browse/tracker/{slug}.
E3 — Publish & moderation (M). Depends on E2. Lets a tracker go public.
- Make
is_publicwritable: addp_is_publictofn_upsert_tracker(or a dedicated publish function) sopublished_atis set on publish. - Restructure the
PublishRequestsEndpoints.csgate from the hardcoded>2 && !=6to a registry-driven allowlist; add Tracker. - Wire the admin moderation review path so
published_at/scheduled_publish_atbecome live (mirrors lorebook publish review).
E4 — Social (M). Each item independent; depends on E2 for public context.
- Favorites/bookmarks:
user_tracker_bookmarks(is_favorite/is_in_list, mirror11_tables_social.sql) +BookmarksEndpointswiring + afavorite_countonPublicTracker. - Comments: add
["trackers"] = EntityRegistry.TrackertoCommentsEndpoints+EntityCommentSettingsEndpointsmaps. - Tags:
TrackerTags.cscatalog + threadtags_0..6throughfn_upsert_tracker+ browse-by-tag + the editor tag selector.
E5 — Collaboration (M). Unlocks shared editing.
EntityDefinition.Tracker.SupportsPermissionsApi = true+ register anIEntityPermissionsAuthorizerfor Tracker + mountEntityPermissionEndpoints.- Add
"trackers"toCreatorChangelogEndpoints.SharedAccessTypes(non-owner access viafn_get_entity_access). - Add Tracker to the
EntityProposalEndpointsfamily (proposals forcan_contributecollaborators).
E6 — Binding expansion (L). Activates the forward-designed table. Overlaps Phase 2 item #2 ("package and conversation scopes").
- Prereq (blocking): add orphan-cleanup triggers on
entity_tracker_bindingsfor the hard-delete owner types (conversation purge viafn_purge_empty_deleted_conversations, package delete) — mirror25c_entity_proposal_orphan_cleanup.sql. The Phase 1 schema comment already names this as the gate. - Wire package / conversation / mode binding endpoints + UI. The owner-generic atomic bind primitive (
fn_bind_tracker_to_owner+ITrackerRepository.BindAsync) already exists (built in E1) — each new owner just resolves its own ownership then calls the same fn with itsowner_type+ cap; only routes + surfaces are missing. - Package
trackers_lockedlock UX; conversation-level add/remove from the WhoDrawer.
Not planned (record the decision):
- Cover image / gallery — trackers are tiny key:value definitions; no picture surface is intended. The absence is deliberate, not a gap.
- Profile dashboard sections — revisit only if trackers become a showcased entity; Lorebook doesn't have it either.
E1 (loose ends) ─ independent
E2 (discoverability) ──► E3 (publish/moderation)
└──► E4 (social: favorites/comments/tags)
E5 (permissions) ──► proposals
E6 (binding expansion) ─ gated on orphan-cleanup triggers; overlaps Phase 2 #2
Genericization design (build shared substrate while wiring Tracker)
Added 2026-05-31 from a 12-dimension entity-workflow survey. Tracker is the 2nd–4th consumer of every entity capability, so per the rule-of-two / refactor-before-feature-delivery rule, several E-slices should land their shared lever as part of wiring Tracker — not copy-paste then unify later. The entity layer is bimodal: cross-cutting capability dispatch (permissions, share-token, bookmarks repo, comments tables, proposals shell, changelog read) is already registry/string-keyed and near config-only; content-shaped logic (CRUD validation, browse SQL, publish/proposal apply CASE arms, DTO projection, tag vocabularies) is genuinely per-entity and should stay that way.
Keystone — make EntityDefinition a capability registry. SupportsPermissionsApi (auto-mounts the 5 permission routes by iterating EntityRegistry.ByType.Values.Where(d => d.SupportsPermissionsApi)) and ViewPathTemplate already prove that a flag read by a generic factory removes per-entity wiring entirely. First new flag landed 2026-05-31: SupportsPublishing — the hardcoded >2 && !=6 gate in PublishRequestsEndpoints is now EntityRegistry.CanPublish(entityType), set on Character/Mode/Lorebook/Package, behavioural-equivalence test pins it to the old allowlist (zero behaviour change). It's the template for the rest. Remaining capabilities still gated by hardcoded allowlists that should become flags on EntityDefinition: SupportsComments, SupportsBookmarks, SupportsProposals, plus ChangelogOwnerColumn / OwnerColumn strings (most owners are created_by_user_id; Package's is owner_id). Adoption is incremental and safe: add the fields defaulting false (zero behavior change), then convert one consumer at a time to read the registry instead of its local allowlist (start with the already-near-generic Comments / Bookmarks / Changelog), setting Tracker's flag as each E-slice lands. Mirror into 00_entity_registry.sql / entityTypes.ts only when a DB/frontend consumer needs it.
Per-slice call — genericize now vs. wire bespoke:
| Slice | Genericize NOW (shared lever to build) | Keep bespoke (irreducibly per-entity) |
|---|---|---|
| E1 | Unify Tracker's raw CreatedByUserId != userId check into the shared CreatorEndpointHelpers owner-gate (its divergence will force a rewrite at E5); rename ToResponse→MapToOwnedTracker; set ChangelogOwnerColumn on the Tracker registry row (read path already generic). |
CRUD field validation + UpsertAsync (no CrudEndpoints<T> factory — divergent signatures + creation side-effects make it heavier than the 5 handlers). |
| E2 | BrowseQueryBuilder + EntityBrowseConfig on EntityDefinition + generic BrowseEntityAsync(query, config) (Tracker is the 7th consumer of the identical visibility-gate + tag-filter + pagination; body drops ~60→~10 lines). |
The tracker_view DB view + the frontend card. OG: wire via the share-token switch bespoke (~80 mechanical lines) unless a 2nd new entity is in scope → then build EntityOgRow + GetEntityOgAsync. |
| E3 | ✅ SupportsPublishing flag landed — replaced the literal >2 && !=6 gate with EntityRegistry.CanPublish (flag on Character/Mode/Lorebook/Package; behavioural-equivalence test). Still to do for tracker publishing: parameterize CheckEntityOwnershipAsync against TableName + OwnerColumn; flip Tracker's flag once it has a public surface (gated on E2). |
fn_approve/reject_publish_request CASE arms (Conversation's creator-review state machine, Package's is_listed are structurally divergent). Tracker's arm is trivial — 3 lines, no content scan. Net: ~8 edit points → 3. |
| E4 | Tags: fn_entity_tag_counts generic SQL + TagCatalogRegistry (the three fn_*_tag_counts are byte-identical save table name) — highest-payoff lever in the slice. Comments/Bookmarks: the keystone flags. |
TrackerTags.cs vocabulary (content, not boilerplate); a typed user_tracker_bookmarks table (do not polymorphize — 6 entities don't justify losing FK-cascade + planner stats); one WHEN 15 arm in fn_get_entity_owner_id. |
| E5 | Proposals: SupportsProposals flag + auto-call MapProposalEndpoints from a Program.cs loop (kills a 6-line copy-paste across three files). |
fn_apply_entity_proposal ELSIF + LoadCurrentEntityFieldsAsync case + enrichment UNION ALL (per-field by nature). |
| E6 | — (no cross-entity lever; the polymorphic entity_tracker_bindings is already the generic substrate). |
Widen the owner_type CHECK + wire the owner-generic repo methods + per-owner endpoints/UI. Tracker-internal surface, not shared. |
Quick wins (already generic — do NOT over-engineer): Permissions (E5) is pure config — 2 lines in Program.cs to register an owner-only authorizer keyed to EntityType.Tracker + flip SupportsPermissionsApi / ViewPathTemplate; the system was designed for exactly this. Changelog (E1) is a one-field registry add. Comments (E4) is the flag + one SQL arm.
Over-abstraction watch (keep per-entity — a flag would be harmful): audience-tier DTOs (MapToOwned* / Public* — shapes genuinely differ; mixins IEntity/EntityRow are already the right reuse); browse *_view bodies and entity-specific gates; publish/proposal SQL CASE arms; tag vocabularies; a full CrudEndpoints<T> factory.
2026-09 extension slices (T1–T3) — locked and sequenced
T1 — Trackers as inputs: a tracker that pins lorebook entries into knowledge
Intent. A tracker stops being a read-out and starts steering the story. The creator links a tracker to one of their lorebooks; the tracker's allowed values become the names of that lorebook's entries; the entry (or entries) the tracker currently holds are always appended to the knowledge section of the story prompt, bypassing keyword / search activation entirely. This is the first concrete piece of the Linked Lorebooks / Conditional Entries arm, narrowed to the deterministic mechanism the developer asked for first — no fuzzy search against the linked lorebook, no per-entry condition rules yet.
Mechanics (what ships):
trackers.linked_lorebook_id(nullable FK →lorebooks,ON DELETE SET NULL) andtrackers.linked_lorebook_max_entries(default 3, the spec's per-tracker entry budget). Linking is allowed only for enum and list value types; the endpoint rejects it for the others.- Allowed values are derived, not copied. When linked, the tracker's effective
enum_values= the distinct names of the lorebook's enabled, non-deleted entries, read live (fn_tracker_effective_enum_values). The storedenum_valuescolumn is ignored while a link is set, so renaming an entry never strands a tracker. Everything downstream that already consumesenum_values— the eval prompt's[type: exactly one of …]line,TryNormalize's enum validation, the chat bar'sSelect, the Forge preview — sees the derived list with no per-consumer changes. - Injection. A new Core seam,
ITrackerPinnedKnowledgeSource, is consulted byLorebookContentProviderright after always-include entries. The web implementation reads the conversation's active trackers (deduped by key, first binding wins — same rule as the eval), the latest tracker snapshot, resolves each linked tracker's current value (enum → one name; list → each item) to entries by name in the linked lorebook (fn_get_lorebook_entries_by_names), caps per tracker atlinked_lorebook_max_entries, dedupes against always-include and against search, and hands them to the provider. Pinned entries are budget-exempt like always-include (a creator override, not retrieval — RETRIEVAL_BUDGET.md invariants) and render in the same## Name/ content format inside the knowledge section. Discord passes no source (web-only, like the rest of trackers). - No binding required. The linked lorebook does not have to be bound to the character or the conversation; the link is the authority (spec: "the linked lorebook gets priority"). Consequence, stated plainly: linking a private lorebook to a tracker bound to a public character exposes those entries to every user of that character — more than binding the lorebook to the character would. A bound lorebook surfaces entries only through keyword/vector activation; a linked tracker additionally ships the lorebook's entry-name index to every reader as the tracker's allowed values (the chat bar's select), and a reader may pick any of them via inline edit and have it pinned on the next turn. The Forge picker says so in its description ("Readers see the entry names as this tracker's values") — that is the point of consent.
- Forge. In the tracker editor, an enum or list tracker gains "Take values from a lorebook" (a picker over the creator's own lorebooks; shared/
can_uselorebooks are a T3 follow-up). When linked, the enum-values editor is replaced by a read-only list of the derived entry names with a link to the lorebook, and the preview's eval line shows the derived[type: exactly one of: …]. - Pictures (2026-11-10, with LOCATION_TRACKER.md Q2's fix). A pinned entry's picture is never shown from the pin: the pin reads the state before the turn's eval, so its picture would belong to the previous reply. The tracker eval's last step shows it beside the reply whose own snapshot newly names the entry (an enum's new value, a list's new item), under the turn's picture rules; staying on a value shows nothing new. Owner decision, 2026-11-10: "one time is enough". (Before, the picture showed under every reply while the value held.) See LOCATION_TRACKER.md §6 Pictures.
- Not in T1: search-boosting with tracker values (spec Phase-1 "concatenated tracker search"), per-entry condition rules, a lorebook-side "which trackers point at me" surface, keyword-based matching against the linked lorebook.
Acceptance criteria — T1
The slice is not done until every box below is verified ✅ against the running product.
User use cases — satisfiable + accessible (verify by driving the UI, not the code):
- As a creator, I can open an enum tracker in the Forge, choose one of my lorebooks under "Take values from a lorebook", save, and see the tracker's allowed values become that lorebook's entry names — reachable from Creator's Space → Trackers → edit, without insider knowledge.
- As a creator, I can do the same for a list tracker, and the chat bar then renders the tracker's current items as chips whose names are entry names.
- As a reader chatting with a character that carries a linked enum tracker, when the eval sets the tracker to an entry name, the next story prompt's knowledge section contains that entry's content — verified with the mock LLM captures (
## <entry name>present under the lorebook section) with no keyword from that entry in recent messages. - As a reader, I can inline-edit the linked tracker in the chat bar and pick from a
Selectof entry names; the next turn injects the picked entry.
Behavior:
-
GET /api/creator/trackers/{id}and the bound/conversation tracker DTOs returnenumValues= the derived entry names when linked, pluslinkedLorebookId/linkedLorebookName; the storedenum_valuescolumn is not surfaced while linked. - The eval prompt's type line for a linked tracker lists the entry names; an eval answer that is not an entry name is skipped (
trackers_skipped), an answer differing only in case is canonicalized to the entry's spelling. - A list-typed linked tracker with N items injects up to
linked_lorebook_max_entriesentries, in the tracker's item order, and the rest are dropped with a Debug log line naming the tracker. - Pinned entries appear once even when the same entry is also always-include or a search hit (dedupe by entry id).
- A linked entry's picture shows beside the reply whose snapshot newly names it, and not under the reply after it; a
reply that keeps the value shows no new picture. (Pinned by
ReplyArrivalPicturesTests; not yet driven live.) - Renaming a lorebook entry changes the tracker's allowed values on the next read; the tracker's stored value that no longer matches any entry injects nothing and the bar shows the stale value as plain text (no crash, no silent clear).
Invariants that must stay true:
- A tracker with no link behaves exactly as before this slice — enum values from
enum_values, no pinned entries, byte-identical eval prompt (pinned by the existingTrackerEvalLlmServiceTests/WebTrackerEvalServiceTests). - Always-include entries and the search budget are unchanged: pinned entries never consume
Knowledge.MaxEntries/Knowledge.TokenBudgetallowance, andcontext.AlwaysIncludeLorebookCharscounts them alongside always-include so the context stage's retrieval derivation stays honest. - Trackers off (
Features.EnableTrackers = falseon the conversation) → no pinned entries, even if a link is set. - Deleting the linked lorebook clears the link (
fn_delete_lorebookis a soft delete, so the FK'sON DELETE SET NULLnever fires on the product path — the function clearslinked_lorebook_iditself, and every read also treats a soft-deleted lorebook as "not linked"); the tracker keeps working as a plain enum with whateverenum_valuesit had (may be empty → the eval line says "one of the allowed values"). - Linking a security lorebook (admin pipeline machinery) → 404, and
fn_upsert_trackerrefuses it independently (SQLSTATE 42501) — the same guard covers a lorebook the caller does not own or has deleted. - A linked list tracker's eval line names the allowed items, and the eval keeps only items that match (canonicalized to the lorebook's spelling); the pin cap applies in the tracker's item order.
- Discord conversations are untouched (the Discord lorebook provider never consults the source).
Review round (2026-09-03, after the first "shipped" pass) — what the adversary caught and what changed: fn_delete_lorebook is a soft delete, so the FK never fired and a deleted lorebook kept deriving values and pinning entries forever (and was unfixable from the Forge, whose picker hides deleted lorebooks). Fixed at the function (clears the link) and at every read (fn_tracker_effective_enum_values, GetEntriesByNamesAsync, the three TrackerRepository projections). Security lorebooks were linkable — closed at the endpoint (ILorebookRepository.IsLinkableByAsync) and in fn_upsert_tracker. List trackers never told the eval their allowed items (DescribeType / TryNormalize ignored enumValuesJson for lists) — closed in TrackerValueFormatter. Unlinking in the Forge blanked the stored values — the picker now seeds the authored list from the derived one. The list-tracker and inline-edit use cases were driven by hand in Chrome against a probe build.
Edges:
- Linking a freeform / numeric / percentage / datetime tracker → 400 with a message naming the two supported types.
- Linking a lorebook the caller does not own → 404 (no existence leak).
- A linked lorebook with zero enabled entries → derived list empty; the eval line falls back to "one of the allowed values"; the Forge shows an empty-state hint pointing at the lorebook.
- Duplicate entry names inside one lorebook (allowed by the schema) → the derived list is distinct; injection includes every entry with that name up to the per-tracker cap, highest priority first.
P1 — Trackers on a package
Acceptance Criteria (P1)
User use cases — satisfiable + accessible (verify by driving the UI, not the code):
- As a creator, in the package builder I can drop one of my trackers onto the Story State step (any preset), see it listed with its type, remove it, and save the package — reachable from the Forge without insider knowledge.
- As a creator, the step shows my bound character's own trackers as via character so I know what state the experience will keep without re-adding them.
- As a reader on a package's public page, I can see the trackers the experience keeps under Story State.
- As a reader who starts a conversation from the package, the story-state bar shows the package's trackers after the character's on the next assistant message, and the eval keeps them current.
Behavior:
-
POST /api/creator/projects/{p}/packageswithtrackerIdsbinds them (owner_type 6) in array order; a re-save replaces the set; omitted/[] = none. -
GET …/packages/{id}(edit read) returnstrackerUuidsin binding order andtrackersLocked. - The eval prompt, the injected OOC block, the pinned-knowledge read and
GET /api/conversations/{id}/trackersall resolve character ∪ package (character first, deduped by key). - The public package detail returns
linkedTrackers(uuid, name, key, type, isPublic).
Invariants that must stay true:
- A conversation with no package behaves exactly as before (character-only set, same order).
- A package with no trackers behaves exactly as before.
- A key bound on both the character and the package resolves to the character's definition, once.
- A tracker's T1 lorebook link works when bound through a package (the pin reads the same set).
- Agent proposals' package tracker binds (
fn_apply_component_binding) coexist: a re-listed binding keeps itsoverride_initial_value/is_required.
Edges:
- Someone else's tracker (even public) in
trackerIds→ the whole save is refused (trackers_not_bindable, 403), nothing written. - More than
Tracker.DefaultMaxTrackers→ refused (tracker_limit_reached, 422). - A set over
Tracker.MaxTrackerTokens→ saved, and the answer carriesbudgetWarningwith both numbers (2026-11-07). - A soft-deleted tracker drops out of the edit read and the pipeline set; a soft-deleted package's bindings are inert.
- The compute-cost reserve for the tracker eval (
WebChatEntryPoint.HasBoundTrackers) asks the same character ∪ package question the eval does — a package-only tracker set is metered.
Known shape, stated plainly: the save is a full replacement — a caller that omits trackerIds (an old client bundle, an agent proposal's package re-apply) clears the set, exactly as lorebookIds behaves. ConversationTrackerSetResolver re-reads the conversation row once per consumer (three small reads per turn); fold it onto the pipeline context when T2 adds the conversation leg.
C1 — The package cast (own doc)
The multi-character package — supporting characters with presence-aware injection and a zero-setup roster tracker — is specified and gated in package-cast.md. It supersedes §Character Groups above and rides P1's resolver (the roster is a synthesised definition, the first leg of the union). The resolver's fourth leg, the conversation's own bindings, is T2 below.
T2 — Trackers on the conversation itself (E6, conversation owner)
Intent. A reader adds a tracker to this chat without touching the character — "the same way as journal, just above it" (developer, 2026-09-03). The polymorphic entity_tracker_bindings table, the owner-generic repo methods and fn_bind_tracker_to_owner already exist; this slice wires owner_type = 4 end to end.
Mechanics (what ships):
- Orphan-cleanup: bindings for owner types that hard-delete (conversation purge, package delete) are removed by trigger / in the purge function — the gate the Phase-1 schema comment names. Character stays soft-delete.
- The pipeline's active set for a conversation = character bindings ∪ conversation bindings, deduped by key with character first, then conversation (a reader can add a tracker, never shadow the creator's);
GetActiveForOwnerAsyncgains a conversation-aware union used by the eval, the injector, the feature-state service andGET /api/conversations/{id}/trackers. - Routes mirror the character family under
/api/conversations/{id}/trackers/bindings(list / bind / unbind / reorder), gated on conversation ownership; the tracker must be owned by the caller (shared trackers are T3). - Settings endpoint
PATCH /api/conversations/{id}/tracker-settings(Journal-shaped) writingTracker.EvalCadenceat conversation scope — the dedicated-policy row added 2026-09-03 is its DB half — returning the resolved cadence. - Chat drawer. A Trackers card directly above the Journal card in the Who drawer: bound trackers (character-bound rows shown read-only with a "from character" chip, conversation-bound rows removable and drag-orderable), an "Add tracker" picker over the reader's own trackers, and the cadence selector (
off/per message— noon summary, retired 2026-10-24) with a one-line cost hint. The HowDrawer on/off toggle stays where it is. - chat.'s Story settings (2026-11-07,
c3652c2af). On chat., the same set lives in Story settings → About, as Trackers this story keeps, after the lorebooks the story searches (owner: "Story settings / about - can we add conversation trackers here?"). Every tracker the story keeps is listed with where it comes from. The reader adds one of their own trackers in place and removes one they added; the rest show Remove dimmed with why. Reorder and the cadence stay in the Who drawer. The add form's choices come fromGET /api/conversations/{id}/trackers/choices, because chat. routes no/api/creatortracker route.
Acceptance criteria — T2
User use cases:
- As a reader in any chat, I can open the Who drawer, find Trackers immediately above Journal, add one of my own trackers to this chat, and see it in the story-state bar on the next assistant message — reachable without insider knowledge.
- As a reader on chat., I can open Story settings → About, find Trackers this story keeps after the lorebooks, add one of my own trackers to this story, remove one I added, and see the added one in the scene on the next reply — reachable without insider knowledge. (Add and remove driven live at 1280 and 390 px in
c3652c2af; the next reply's scene not yet driven.) - As a reader, I can remove a tracker I added, reorder my added trackers, and switch this chat's eval cadence to per-message; the next turn writes a snapshot.
- As a creator whose character carries trackers, a reader's additions never replace or reorder mine (character rows render first and read-only in the reader's drawer).
Behavior:
-
GET /api/conversations/{id}/trackersreturns the union (character first, conversation second, deduped by key), without any definition an author hid (key, name, start and range never reach the owner; the synthesised cast roster stays). -
PATCH /api/conversations/{id}/tracker-settings {evalCadence}persists at conversation scope; the generic settings route still refuses the key. - The eval prompt, the injected OOC block and the bar all show conversation-bound trackers in binding order after the character's. (All three read
TrackerSetUnion, whose order is unit-pinned; not yet driven through a live turn.) - Purging a deleted conversation removes its bindings; deleting a package removes its bindings. (Hard delete. A soft-deleted package or conversation keeps its rows — a restore keeps its trackers — and a soft-deleted package's are inert on read, as before.)
Invariants:
- A conversation with no conversation-level bindings behaves exactly as before (character-only set, same order).
- The 8-tracker cap (40 since 2026-11-07, The token figure) applies per owner (character cap and conversation cap are independent).
- A conversation-bound tracker is invisible to other conversations and to the character's other readers — including every surface someone other than the chat's owner reads: the published story page, the share link, the creator's publish preview and the moderator's transcript show neither its definition (key, name, enum values) nor its values, and a project member reading the tracker's owners never sees (or counts) the chat.
- A branch of the chat keeps the reader's own trackers (their order, start values and required flags), the brancher's own live trackers only.
- A tracker the author hid keeps its key a secret too: the reader's picker disables a tracker of theirs it would refuse, and neither that reason, the 409 nor the "used instead" hint names the hidden key. (The story's owner may still ask to see their hidden trackers, keys included: Revealing hidden trackers, eod-519.)
- A reader's values stay theirs after an author binds the same key: a non-owner surface drops every key the conversation binds from every snapshot, shadowed or not (residual after an unbind: see As built).
- The owner's own reads serve no hidden tracker's key, name or value: history, versions, message edit, export (its summaries' tracker timelines too), the inline edit and the scene save, the staged slot (the conversation GET, the staging, removal and roll answers), the live
eventsframe, and the agent's observation reads (transcript, setup — hidden trackers neither listed nor counted —, trajectory, story memory). No turn-event effect names one (a direction left with no effect is dropped); the stored snapshot, timelines and events stay complete. The shareable PDF prints only the shown trackers' timelines. (The one exception is the owner's own ask: the two reveal reads under Revealing hidden trackers, eod-519.) - As the story's owner, I can see that my story keeps hidden trackers and what they hold. Under the scene's trackers (the desktop margin, the phone's sheet), "and 2 hidden trackers" is folded. Pressing it shows their values in the reply the scene stands on, and "Hide them" folds them again. Nothing is written, and no prompt changes. (chatConsole
HiddenTrackers.test.tsx; tick after the live pass.) - A story with no hidden tracker shows no such control. While the count gets no answer, none shows either. (chatConsole
HiddenTrackers.test.tsx.) - Only the story's owner is served the reveal reads. Another account, a reader of a shared or published story, a deleted story and an unknown id all get the family's not-found body, byte for byte the same. A reply of another story is not found. An RPG story reveals none, and a VN run gets the family's not-found. (ServerAPI.Tests
ConversationHiddenTrackerRevealTests,VisualNovelChatFamilyGateTests.) - A hidden tracker is a reader-UI property only: every model leg of the story reads it as it reads a shown one, its value in each OOC block beside the shown trackers — the Hybrid director's beat history and the head of the reader's turn, assembled or flattened, and the writer's call included (director (b7), 2026-11-25, on a user report the owner forwarded). (Pinned by WebChat.Tests
HybridHiddenTrackerPromptTestsandWebTrackerHistoryInjectorTests; tick once they and the live Hybrid pass are green.) - A write names a tracker the reader is shown: a set on a key with no visible definition — no tracker holds it, or an author hid it — is refused by the inline edit and the scene save with one refusal (
That tracker isn't part of this story's scene.), byte for byte the same; a removal (reset) of a hidden key changes nothing and is answered as the removal of a key the snapshot doesn't hold. A staged direction left with no shown target is released by the next send, never narrated.
Edges:
- Binding a tracker whose key collides with a character-bound key → 409 with copy naming the collision (the character wins; no silent shadowing).
- Non-owner of the conversation → 404 on every bindings route; not signed in → 401.
- Cadence value outside the two (
off,per_message) → 400.
T2 — As built (2026-10-29)
Data. No new table: entity_tracker_bindings with owner_type = 4, written through the same owner-generic fn_bind_tracker_to_owner (per-owner advisory lock + Tracker.DefaultMaxTrackers cap — the conversation's own cap, independent of the character's; for owner 4 it also takes FOR KEY SHARE on the conversation row, so a purge that hasn't run yet waits for the bind, and one that already deleted the chat leaves the bind 'owner_not_found' — nothing written, the route's 404). Orphan cleanup: fn_cleanup_tracker_bindings_on_owner_delete() behind two AFTER DELETE triggers in 68_tables_trackers.sql — web_conversations (4) and packages (6). Delete only: a soft delete keeps the rows. A branch copies them (fn_branch_conversation step 8a: the brancher's own live trackers, with order, start value and required flag), beside the cadence override in the settings and the messages' snapshots; the other conversation-creating functions (11's create/migration, 47's package start, 47f's visual-novel run) start a chat from nothing and have no source bindings to carry. GetOwnersForTrackerAsync (the project pool's tracker detail) never returns owner 4 rows, not even as a count. The cadence's DB half is the dedicated-policy row in 89_enforce_setting_write_scopes.sql (unchanged but for its description).
The set. TrackerSetUnion.UnionAsync/UnionWithOwnersAsync take a required conversationId (the conversation leg, TrackerSetOwner.Conversation, appended after the package's, before the dedupe), so every reader — eval, history injector, pinned knowledge, opening snapshot, the bar's read, the PDF export, the scene direction, the inline edit, the agent's get_conversation_setup (owner label conversation) — gets the reader's trackers last and a colliding key always resolves to the author's. The package save's in-transaction union passes none. ShownTrackers.DefinitionsAsync, the one read of every surface someone other than the owner reads (the published page, the share link, the creator's publish preview, the moderator's transcript), reads the leg and drops it: the reader's own tracker decides which built-ins the story runs, and its definition and values never reach them. That read also drops every key the conversation itself binds (GetBoundTrackerKeysAsync(4, …), a deleted tracker's binding and an unbound tracker's tombstone included), even when an author's tracker or a built-in holds the same key: a snapshot records no provenance, so a value stored under that key may be the reader's — its definition, its values in every snapshot and the events naming it all go. An unbind leaves that tombstone (entity_tracker_bindings.unbound_at, 210, since 2026-10-30): every read of the bound set ignores the row, a bind removes it, a branch copies it. The cost is the public line of a built-in or author tracker on that key, on that story.
What the owner is served. The conversation's owner never gets a tracker the author hid, in their own chat either: every snapshot the owner's reads serve — the message history, a single message's edit answer, a message's versions (the read the tracker push re-reads a reply by), the JSON export, the inline tracker edit's answer and the scene save's (200 and 409) — leaves out the keys of the hidden definitions in the owner's set (the union with the conversation's leg, ShownTrackers.HiddenKeys / OwnerSnapshotJson). Every turn-event value the owner is served — a reader row's events (history, edit, versions, export), the staged slot (the conversation GET, the staging, removal and roll answers, the export's stagedEvents — the tracker set is read only when a staged record carries effects, and a roll or removal answer whose read fails serves the slot with no effects rather than failing the write) and the live events frame (IPipelineContext.HiddenTrackerKeys, set by the scene direction's resolution; a carried record with effects on a turn that never set it goes out with no effects, never raw) — loses every target and op on a hidden key, and a kind that drops once it has no effect (a direction) is dropped (OwnerTurnEventCut, Core; ShownTrackers.OwnerTurnEvents forwards; events naming no hidden key are served as the very string). A summary's tracker timeline loses a hidden tracker's chain in the export (ShownTrackers.OwnerTimelineJson) and keeps only the shown trackers' chains in the PDF (ShownTrackers.TimelineJson, the snapshot's own shown-keys cut). The agent's observation reads (ConversationObservationReadService: transcript, trajectory, story memory, setup) apply the same cuts, and the setup neither lists nor counts a hidden tracker. Writes (F-24, director ruling). The inline edit and the scene save resolve a key against the VISIBLE definitions only, and a set on any key without one — no tracker holds it, or an author hid it — is refused with one refusal (NoShownTrackerCopy), byte for byte the same, before anything is written: no read-after-write oracle, and no off-type value landing in a tracker the reader can't see (no UI path writes such a key: the bar and the scene list only visible definitions; with its definitions unreadable the bar shows the served keys read-only). A removal — the inline edit's blank, the scene save's "" — of a stale key removes it; of a hidden key it writes nothing and answers as a removal of a key the snapshot doesn't hold (a reader's row is refused in the write's own words). A staged direction whose every target was hidden or unbound since staging is never carried, so no turn consumed it and its owner could neither see nor remove it: the send that finds it releases it (fn_release_staged_directions, a whole-value match, so a direction re-staged since stays; never narrated, nothing recorded). Every other key is served as stored, a stale one included. The stored tracker_json and the state the eval carries forward stay complete; only what is served changes. Publish screening (fn_message_tracker_state_text, staff-only) still reads the full snapshot — an owner call, recorded, not this slice's. The turn's HasBoundTrackers precompute (WebTurnContextResolver) asks the conversation too, so a chat whose only tracker is the reader's own is metered.
Wire contract (ServerAPI, ConversationsEndpoints.TrackerBindings.cs and, since 2026-11-07, ConversationsEndpoints.TrackerChoices.cs; every route: the caller's own live conversation, else the family's not-found body 404; signed out 401):
| Route | Body | Answers |
|---|---|---|
GET /api/conversations/{id}/trackers/bindings |
— | 200 { bindings: [{ tracker: BoundTracker, shadowed }], inherited: [{ key, name, valueType, source: cast\|character\|package\|builtIn }], maxTrackers, takenTrackerIds, trackerTokens, maxTrackerTokens } — inherited leaves out what the author hid; shadowed = an author's owner took the key (shown or hidden) after the reader bound it; takenTrackerIds = the caller's own trackers whose key the story already tracks, a hidden one's included — ids, never the hidden key; trackerTokens / maxTrackerTokens = the story's whole set's figure and the suggested limit (The token figure) |
GET /api/conversations/{id}/trackers/choices |
— | 200 { trackers: [{ id, name, key, description }] } — every live tracker the caller made (created_by_user_id, not deleted), sorted by name ignoring case; the add form's choices on chat., which routes no /api/creator tracker route. Not filtered by the story: which of them the bind would refuse stays the bindings read's takenTrackerIds, one rule in one place. Same gate as the rest: someone else's, a deleted or an unknown conversation 404 (the family's body), signed out 401, and a 13–17 or unread account 403 adult_account_required (the host's account-state gate: the route is not on the 13+ allow-list; read from the mapping, not driven live). Read-only; added 2026-11-07 (c3652c2af) |
PUT /api/conversations/{id}/trackers/bindings/{trackerId} |
none | 204, or 200 { budgetWarning: { tokens, limit, message } } when the story's set is now over Tracker.MaxTrackerTokens (the bind has landed; a warning, never a refusal); 404 tracker_not_found (not the caller's tracker); 409 { error: "tracker_key_collision", message, key, source } (a tracker the author hid: key null, source: "story", a message naming neither); 404 the family's not-found body when the chat was purged under the bind; 422 { error: "tracker_limit_reached", cap }; 403 adult_account_required for a 13–17 or unread account — the host's account-state gate, which answers before the route runs (live 2026-10-29: PUT, GET and DELETE on the bindings all answered it for a minor account, nothing written) — and, as the route's own second line, 403 sfw_not_allowed for any other protected reader (a tracker's name and hint reach the eval prompt, and there is no all-ages screen for a tracker yet — refused, never screened) |
PUT /api/conversations/{id}/trackers/bindings/order |
{ trackerIds: Guid[] } |
204; 400 no_tracker_ids / duplicate_tracker_ids; 409 bindings_changed when the list isn't exactly the chat's bindings |
DELETE /api/conversations/{id}/trackers/bindings/{trackerId} |
— | 204; 404 tracker_binding_not_found |
GET /api/conversations/{id}/tracker-settings |
— | 200 { evalCadence: off\|per_message }, resolved as the eval resolves it (TrackerEvalCadences.Resolve(conversation, default)) |
PATCH /api/conversations/{id}/tracker-settings |
{ evalCadence? } |
200 the resolved cadence; 400 invalid_cadence for anything but the exact off / per_message (TrackerEvalCadences.TryParseWrite) |
Writing client. WhoDrawer → who/TrackersSection.tsx on who/useConversationTrackers.ts, a Trackers DrawerSection directly above World Knowledge (whose first card is the Journal): the inherited trackers read-only with a source badge, the reader's own in a SortableCardList with a 36 px remove action, an "Add tracker" tile (a full-width PlaceholderCard, empty or not, gone at the cap; it opens an EntityPickerModal over the reader's own trackers — ones already on the chat left out, one whose key the story tracks — takenTrackerIds — shown disabled with why, the key quoted only when the story's tracker is one the reader sees), the cap line, and an Updates Select (After every reply / Off) with the cost hint. A change bumps NewChatPage's trackersVersion, which ChatPanel keys its definitions read on, so the next reply's bar shows the set.
chat. (2026-11-07, c3652c2af). Story settings → About → Trackers this story keeps (chatConsole/src/chat/settings/tabs/StoryTrackersSection.tsx, rendered where the story serves trackerEdit, which every signed-in reader of their own story gets). One DrawerSection on the bindings read: the story's own trackers first, then inherited, each with its source ("added to this story", "from the character", "from the package", "the story's cast list", "built in"), and a shadowed own row saying the story's tracker is used instead. Remove is an icon on every row (RowRemoveButton): it unbinds the story's own, and on the rest it stays dimmed with why (a built-in points to the writing panel's feature switches). "+ Add" in the header and the shared AddInPlaceCard at the top of the list open one form in place: a RichSelect over …/trackers/choices with the trackers already on the story left out and a takenTrackerIds one disabled with why, then Cancel and Add. A refused bind is said inside the form; a 200 budgetWarning shows as a warning under the header, never blocking. Not on chat.: reorder, the Updates cadence, the cap line and the token figure.
T3 — Discoverability and sharing (E2 → E5)
Intent. Promote Tracker to Lorebook parity so trackers can be found, adopted, published and co-edited. The sequenced plan and the genericize-vs-bespoke table above stand; this section only records the go-decision and the acceptance bar. Order within T3: E2 → E5 → E3 → E4 (public read and sharing first, because T1/T2 immediately want "bind a tracker I don't own" and "link a lorebook I can use").
Acceptance criteria — T3 (one line per E-slice; each slice carries its own detailed list when it starts):
- E2: a public tracker has a
/browse/tracker/{uuid}page reachable from Browse, with an OpenGraph card, and can be adopted ("Use in character") from there. - E5: the owner can share a tracker (view / use / edit) through the standard permissions dialog; a
can_usegrantee can bind it to their character or conversation; acan_editgrantee sees it in their Forge with the changelog attributing edits. - E3: publishing a tracker goes through the publish request + moderation queue like a lorebook;
is_public/published_atbecome live; unpublishing hides it from Browse within one request. - E4: favorites, comments and tags work on the public page and feed Browse filters.
- Invariant across T3: an unshared, unpublished tracker remains invisible to everyone but its owner at every one of these surfaces (verified logged-out and as a second user).
Implementation Map
This section maps every file that needs to be created or modified to implement trackers as a standalone entity. Organized by layer, in implementation order.
Database Layer
New file: database/v1/68_tables_trackers.sql
Main table: trackers — standard entity pattern matching characters/lorebooks:
CREATE TABLE IF NOT EXISTS trackers (
id SERIAL PRIMARY KEY,
created_by_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
uuid UUID NOT NULL DEFAULT gen_random_uuid(),
name VARCHAR(60) NOT NULL DEFAULT '',
key VARCHAR(50) NOT NULL DEFAULT '', -- machine-readable identifier
description VARCHAR(500) NOT NULL DEFAULT '',
initial_value TEXT,
value_type INTEGER NOT NULL DEFAULT 0, -- 0=freeform, 1=numeric, 2=enum, 3=list
enum_values_json TEXT, -- JSON array for enum type
numeric_min NUMERIC,
numeric_max NUMERIC,
display_format VARCHAR(200),
extraction_hint TEXT,
injection_mode INTEGER NOT NULL DEFAULT 0, -- 0=full, 1=compact
scope INTEGER NOT NULL DEFAULT 0, -- 0=character, 1=package, 2=conversation (same set lorebooks use)
linked_lorebook_id INTEGER REFERENCES lorebooks(id) ON DELETE SET NULL,
linked_lorebook_max_entries INTEGER NOT NULL DEFAULT 3,
linked_character_group_id INTEGER REFERENCES character_groups(id) ON DELETE SET NULL,
is_visible BOOLEAN NOT NULL DEFAULT TRUE,
tags_0 BIGINT NOT NULL DEFAULT 0,
tags_1 BIGINT NOT NULL DEFAULT 0,
tags_2 BIGINT NOT NULL DEFAULT 0,
tags_3 BIGINT NOT NULL DEFAULT 0,
tags_4 BIGINT NOT NULL DEFAULT 0,
tags_5 BIGINT NOT NULL DEFAULT 0,
tags_6 BIGINT NOT NULL DEFAULT 0,
is_public BOOLEAN NOT NULL DEFAULT FALSE,
published_at TIMESTAMP WITH TIME ZONE,
scheduled_publish_at TIMESTAMP WITH TIME ZONE,
is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX idx_trackers_uuid ON trackers(uuid);
CREATE INDEX idx_trackers_created_by_user_id ON trackers(created_by_user_id);
CREATE INDEX idx_trackers_is_public ON trackers(is_public);
CREATE INDEX idx_trackers_is_deleted ON trackers(is_deleted);
CREATE INDEX idx_trackers_tags_0 ON trackers(tags_0);
CREATE INDEX idx_trackers_tags_1 ON trackers(tags_1);
CREATE UNIQUE INDEX idx_trackers_owner_key ON trackers(created_by_user_id, key)
WHERE is_deleted = FALSE; -- key unique per owner
No separate content table needed -- extraction_hint and initial_value are small enough for inline storage.
Binding tables:
-- Character-tracker bindings (character declares which trackers it uses)
CREATE TABLE IF NOT EXISTS character_tracker_bindings (
id SERIAL PRIMARY KEY,
character_id INTEGER NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
tracker_id INTEGER NOT NULL REFERENCES trackers(id) ON DELETE CASCADE,
override_initial_value TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
is_required BOOLEAN NOT NULL DEFAULT FALSE,
UNIQUE(character_id, tracker_id)
);
-- Conversation-tracker bindings (user adds tracker to conversation)
-- Same pattern as conversation_lorebook_bindings. No persona binding.
CREATE TABLE IF NOT EXISTS conversation_tracker_bindings (
id SERIAL PRIMARY KEY,
conversation_id INTEGER NOT NULL REFERENCES web_conversations(id) ON DELETE CASCADE,
tracker_id INTEGER NOT NULL REFERENCES trackers(id) ON DELETE CASCADE,
priority INTEGER NOT NULL DEFAULT 0,
UNIQUE(conversation_id, tracker_id)
);
-- Character groups (lightweight entity — named collection of characters)
-- See "Character Groups" section for full design.
CREATE TABLE IF NOT EXISTS character_groups (
id SERIAL PRIMARY KEY,
created_by_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
uuid UUID NOT NULL DEFAULT gen_random_uuid(),
name VARCHAR(60) NOT NULL DEFAULT '',
description VARCHAR(500) NOT NULL DEFAULT '',
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX idx_character_groups_uuid ON character_groups(uuid);
CREATE INDEX idx_character_groups_created_by_user_id ON character_groups(created_by_user_id);
-- Character group members (characters within a group)
CREATE TABLE IF NOT EXISTS character_group_members (
id SERIAL PRIMARY KEY,
character_group_id INTEGER NOT NULL REFERENCES character_groups(id) ON DELETE CASCADE,
character_id INTEGER NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
always_on_summary TEXT,
override_system_prompt TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
UNIQUE(character_group_id, character_id)
);
-- Bookmark table (follows user_lorebook_bookmarks pattern)
CREATE TABLE IF NOT EXISTS user_tracker_bookmarks (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
tracker_id INTEGER NOT NULL REFERENCES trackers(id) ON DELETE CASCADE,
is_favorite BOOLEAN NOT NULL DEFAULT FALSE,
is_in_list BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, tracker_id)
);
Modify: database/v1/21_tables_packages.sql
Uncomment package_tracker_bindings and extend with override fields:
CREATE TABLE IF NOT EXISTS package_tracker_bindings (
id SERIAL PRIMARY KEY,
package_id INTEGER NOT NULL REFERENCES packages(id) ON DELETE CASCADE,
tracker_id INTEGER NOT NULL REFERENCES trackers(id) ON DELETE CASCADE,
override_initial_value TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
is_required BOOLEAN NOT NULL DEFAULT FALSE,
UNIQUE(package_id, tracker_id)
);
New file: database/v1/views/45_tracker_view.sql
User-facing view following lorebook_view pattern:
- All tracker columns
- Creator info via users JOIN (
creator_slug,creator_username,creator_global_name) - Stats from
mv_tracker_stats(favorite_count,bound_character_count,bound_package_count,conversation_usage_count) - Share count subquery from
entity_permissions WHERE entity_type = entity_type('tracker')(use the constant helper rather than the literal — slot is 15, not 11/14) - Publish request status subquery
WHERE is_deleted = FALSE
New file: database/v1/views/46_admin_trackers_view.sql
Admin view following admin_lorebooks_view pattern:
- All tracker columns (NO
is_deletedfilter) - Creator info + rights + ban status
- Report counts (
total_reports,pending_reports) - Public URL via
fn_get_entity_public_url(entity_type('tracker'), uuid)(slot is 15; prefer the constant helper)
Add to: database/v1/views/10_entity_stats_materialized.sql
New materialized view mv_tracker_stats:
tracker_id,favorite_count(fromuser_tracker_bookmarks),bound_character_count(fromcharacter_tracker_bindings),bound_package_count(frompackage_tracker_bindings),conversation_usage_count(fromconversation_tracker_bindings)
New file: database/v1/functions/78_tracker_functions.sql
fn_upsert_tracker()— followsfn_upsert_lorebook()pattern. NULL tracker_id = INSERT, non-NULL = UPDATE with COALESCE. Returns(tracker_id INTEGER, is_new BOOLEAN).fn_delete_tracker()— soft delete. Verify ownership, setis_public=FALSE,is_deleted=TRUE.
Lorebook Entry Extension
The always_on_summary field is a first-class lorebook feature -- any lorebook entry can have one, regardless of whether the lorebook is tracker-linked. This keeps the lorebook system unified rather than introducing a separate "character lorebook" type.
-- Extension to existing lorebook_entries table
ALTER TABLE lorebook_entries
ADD COLUMN always_on_summary TEXT; -- short summary, always injected regardless of search
When a lorebook is linked to a list-type tracker (e.g., a roster), entries with an always_on_summary have that summary injected on every message, while the full content is only injected when the entry's keyword appears in the tracker's current value. This enables the two-tier injection model described in Character Roster.
The field is optional and has no effect when the lorebook is not linked to a tracker via linked_lorebook_id. A lorebook can function as both a regular keyword-searched lorebook and a tracker-linked lorebook simultaneously.
C# Backend Layer
Modify: server/EchoOfDreams.Core/Entities/EntityRegistry.cs
- Add
Tracker = 15toEntityTypeenum - Add
EntityDefinition:new(EntityType.Tracker, "tracker", "trackers", "trackers", HasUuid: true, DeletedColumn: "is_deleted") - Add to
ByNameandByTypedictionaries
New file: server/EchoOfDreams.Core/Storage/Models/Tracker.cs
Model class inheriting DbModelBase, ITimestamped with all tracker fields. Override DisplayName => Name.
New file: server/EchoOfDreams.Database/Interfaces/ITrackerRepository.cs
TrackerRow : EntityRowWithCreatorInfo— snake_case properties matchingtracker_viewITrackerRepositoryinterface:GetById,GetOwnerId,Count,GetPage,Create,Update,UpdateTags,Delete,GetUserProfileInfo
New file: server/EchoOfDreams.Database/Repositories/TrackerRepository.cs
- Extends
RepositoryBase<TrackerRow>,Source => "tracker_view" - Uses
fn_upsert_tracker()andfn_delete_tracker()
New file: server/EchoOfDreams.Database/Interfaces/IAdminTrackerRepository.cs
AdminTrackerRow : IAdminEntity—EntityType => EntityType.TrackerAdminTrackerQueryParamsrecordIAdminTrackerRepositoryinterface
New file: server/EchoOfDreams.Database/Repositories/AdminTrackerRepository.cs
Queries from admin_tracker_view, follows AdminCharacterRepository pattern.
Modify: server/EchoOfDreams.Database/Interfaces/IConversationBrowseRepository.cs
Add tracker browse/bind/unbind methods mirroring the lorebook pattern:
BrowseTrackersAsync(conversationId, userId, search, filter, sortBy, sortDirection, pageSize, offset, ct)GetTrackerAccessInfoAsync(trackerId, ct)BindTrackerAsync(conversationId, trackerId, priority, ct)UnbindTrackerAsync(conversationId, trackerId, ct)
New types: ConversationTrackerRow, ConversationTrackerBrowseResult, TrackerBindingInfo, TrackerAccessInfo
Binding sources for tracker browse: character_tracker_bindings (bound_to='character'), package_tracker_bindings via conversation's package (bound_to='package'), conversation_tracker_bindings (bound_to='conversation'). No persona binding.
Modify: server/EchoOfDreams.Database/Repositories/ConversationBrowseRepository.cs
Implement the tracker browse/bind/unbind methods.
Modify: server/EchoOfDreams.ServerAPI/Api/Models/CreatorModels.cs
Add TrackerRequest and OwnedTracker records following the existing entity DTO pattern. Both include LinkedCharacterGroupId (Guid?) alongside LinkedLorebookId.
Modify: server/EchoOfDreams.ServerAPI/Api/Models/WebChatModels.cs
- Add
ChatTrackerDtofor conversation context (id, name, key, valueType, boundTo, canUnbind) - Add
Trackersfield toPackageLockDto - Add
ShowTrackersboolean toWebConversationDtoandWebConversationDetailDto(master toggle state) - Add
ShowTrackerstoUpdateWebConversationRequest
New file: server/EchoOfDreams.ServerAPI/Api/Endpoints/CreatorTrackerEndpoints.cs
Full CRUD following CreatorCharacterEndpoints.cs pattern:
GET /api/creator/trackers— list with pagination, search, sortGET /api/creator/trackers/{trackerId:guid}— get by UUIDPOST /api/creator/trackers— createPUT /api/creator/trackers/{trackerId:guid}— updateDELETE /api/creator/trackers/{trackerId:guid}— soft delete
Modify: server/EchoOfDreams.ServerAPI/Api/Endpoints/ConversationsEndpoints.cs
Add tracker endpoints mirroring the lorebook binding pattern:
GET /api/conversations/{id:guid}/trackers/browse— browse available trackersPOST /api/conversations/{id:guid}/trackers/{trackerId:guid}— bind trackerDELETE /api/conversations/{id:guid}/trackers/{trackerId:guid}— unbind tracker
New file: server/EchoOfDreams.AdminAPI/Api/Endpoints/AdminTrackersEndpoints.cs
Admin CRUD following AdminCharacterEndpoints pattern.
New file: server/EchoOfDreams.Database/Interfaces/ICharacterGroupRepository.cs
CharacterGroupRow— id, uuid, name, description, created_by_user_id, member_count, timestampsCharacterGroupMemberRow— character_group_id, character_id, character_name, character_avatar_url, always_on_summary, override_system_prompt, sort_orderICharacterGroupRepositoryinterface:GetByOwner,GetById,GetByIdWithMembers,Create,Update,Delete,AddMember,UpdateMember,RemoveMember,ReorderMembers
New file: server/EchoOfDreams.Database/Repositories/CharacterGroupRepository.cs
Implements ICharacterGroupRepository with Dapper. No view needed -- lightweight entity queries the tables directly.
New file: server/EchoOfDreams.ServerAPI/Api/Endpoints/CreatorCharacterGroupEndpoints.cs
Character group CRUD + member management:
GET /api/creator/character-groups— list groups owned by userGET /api/creator/character-groups/{groupId:guid}— get group with membersPOST /api/creator/character-groups— create groupPUT /api/creator/character-groups/{groupId:guid}— update group name/descriptionDELETE /api/creator/character-groups/{groupId:guid}— delete groupPOST /api/creator/character-groups/{groupId:guid}/members— add character to groupPUT /api/creator/character-groups/{groupId:guid}/members/{characterId:guid}— update membership (summary, override, sort_order)DELETE /api/creator/character-groups/{groupId:guid}/members/{characterId:guid}— remove characterPUT /api/creator/character-groups/{groupId:guid}/members/reorder— batch update sort_order
Modify: DI registration
server/EchoOfDreams.ServerAPI/Program.cs: RegisterITrackerRepository/TrackerRepository,ICharacterGroupRepository/CharacterGroupRepository, map endpointsserver/EchoOfDreams.AdminAPI/Program.cs: RegisterIAdminTrackerRepository/AdminTrackerRepository, map endpoints
Admin & Permissions
Trackers follow the same entity patterns as characters, lorebooks, and modes:
Ownership & sharing: Trackers are standalone entities owned by a user (created_by_user_id). The existing EntityPermission system handles sharing (entity_type = entity_type('tracker'), currently slot 15 — see EntityRegistry note above) — tracker creators can grant view/edit access to other users. is_public makes a tracker discoverable in the Hub.
Admin access: Admin area permission falls under content (same area as characters and lorebooks) -- no new admin area needed.
Admin capabilities:
- View/search all trackers across users
- Edit tracker definitions (for moderation)
- Disable/delete trackers that violate content policy
- View tracker usage stats (how many characters/packages bind a tracker)
Tier / feature gating: The original doc predates the May 2026 subscription refactor — the legacy subscription_tier_limits table was dropped and per-feature access is now bought via the Feature Commitments system (Echoes spent per 30-day cycle, see docs-internal/architecture/billing/SUBSCRIPTION_REFACTOR.md). Any "trackers per character / per package / advanced extraction model" gate should therefore be expressed as a feature key in echo_feature_catalog (with fn_get_user_feature_metadata driving the runtime check), not as a column on the dropped subscription_tier_limits table or a hard tier comparison. Free tier still gets the basic tracker experience; richer extraction (e.g. expensive evaluation model, more concurrent trackers, character-scoped persistence via Journal) is a natural Feature Commitment row to add when wiring this up.
Frontend Layer (clientConsole)
Modify: clientConsole/src/types/entities.ts
Add ChatTracker interface (for who drawer) and OwnedTracker interface (for creator/forge).
ChatTracker follows ChatLorebook pattern: id, name, key, description, valueType, initialValue, isVisible, boundTo ('character'|'package'|'conversation'|null), canUnbind, isOwned, extends IsCreatedByUser, HasBookmarkStatus, HasTimestamps.
New file: clientConsole/src/api/trackers.ts
API client functions following clientConsole/src/api/lorebooks.ts pattern:
browseTrackersForConversation(conversationId, params)bindTrackerToConversation(conversationId, trackerId)unbindTrackerFromConversation(conversationId, trackerId)- Creator CRUD:
getTrackers,getTracker,createTracker,updateTracker,deleteTracker
Modify: clientConsole/src/pages/chat-v2/components/WhoDrawer.tsx
Add tracker section after Greeting (line 420), before Persona (line 422):
DrawerSectionwith title "Trackers" and count badge- List of bound trackers as
Cardcomponents (name, key, valueType badge, boundTo indicator) - "Manage trackers" button opens
EntityPickerModalwith bind/unbind toggle - Package lock check:
conversation?.packageLocks?.trackers - State additions:
trackers,trackerPickerOpen, bind/unbind handlers
Modify: clientConsole/src/pages/chat-v2/components/HowDrawer.tsx
Add master tracker visibility toggle:
- Toggle switch in the How drawer alongside streaming/model settings
- Persisted on the conversation via
serverClient.put(new field:showTrackersboolean) - Controls whether
TrackerBarcomponents render below messages
New file: clientConsole/src/components/chat/TrackerBar.tsx
Collapsed tracker bar component rendered below assistant message bubbles:
- Displays all visible tracker key:value pairs in compact pipe-separated format
- Only renders when conversation
showTrackersis true AND message hastrackerJson - Styled as subtle, low-contrast bar (same visual weight as timestamps)
- Uses tracker
injectionModeto determine compact vs full label formatting
New file: clientConsole/src/components/chat/TrackerDetails.tsx
Expanded tracker detail panel for a single message:
- Renders each tracker with type-appropriate visualization:
- Numeric: mini progress bar with value/max
- List: tag/chip per item
- Enum: selected value highlighted
- Freeform: plain text
- Highlights changed values with delta indicator (was → now)
- Color-coded source: green = AI-evaluated, blue = user-edited, red = evaluation failed
- Edit button per tracker value — opens inline editing, corrected value carries forward
- "Re-evaluate" button — re-runs evaluation against this message with current tracker definitions/hints, shows diff vs stored result
- "Why?" link per changed value — shows evaluation context (user message, assistant response, hint, raw LLM response)
- "Evaluation log" link — shows full raw evaluation input/output for debugging
- Toggled via context menu on individual message bubbles
Modify: Message bubble component (context menu)
Add "Show tracker details" / "Hide tracker details" to the existing message context menu. Works independently of master toggle — user can inspect a single message without enabling global tracker view.
New file: clientConsole/src/components/chat/TrackerTimeline.tsx
Conversation-level tracker history view:
- Table/timeline showing all messages where tracker values changed
- Columns: message number, timestamp, tracker key, old → new value, source (AI/user-edited/failed)
- Click row to jump to message in conversation
- "Re-evaluate range" action — select multiple messages, batch re-evaluate with current hints, show diff
Modify: clientConsole/src/pages/creator/TrackerFormPage.tsx (additional features)
Testing tools on the Forge tracker editor:
- "Preview evaluation prompt" button — shows the fully assembled evaluation prompt
- "Test hint" panel — A/B comparison: run two ExtractionHint variants against a selected message, show side-by-side results
Backend: Evaluation endpoints for testing tools
Modify server/EchoOfDreams.ServerAPI/Api/Endpoints/ConversationsEndpoints.cs:
POST /api/conversations/{id:guid}/trackers/re-evaluate/{messageId:guid}— re-run evaluation for a single message with current tracker definitions. Returns both old and new extraction results.POST /api/conversations/{id:guid}/trackers/re-evaluate-range— batch re-evaluate a range of messages. Returns diffs.GET /api/conversations/{id:guid}/messages/{messageId:guid}/tracker-evaluation-log— return the stored raw evaluation input/output for a message.
Modify server/EchoOfDreams.ServerAPI/Api/Endpoints/CreatorTrackerEndpoints.cs:
POST /api/creator/trackers/{trackerId:guid}/preview-prompt— given a conversation + message reference, return the fully assembled evaluation prompt without executing it.POST /api/creator/trackers/{trackerId:guid}/test-hint— given a conversation + message reference + two hint variants, execute both and return side-by-side results.
Database: Store evaluation metadata
The tracker_json field on messages stores the parsed tracker values. For testing/debugging, we also need the raw evaluation context. Add to web_messages (or a separate table):
tracker_evaluation_log TEXT— JSON containing: the evaluation prompt sent, the raw LLM response, parse/validation results, which values changed vs carried forward, timestamp, model used. NULL for messages that weren't evaluated (user messages, messages before trackers were active).
New file: clientConsole/src/api/characterGroups.ts
API client for character group CRUD + member management.
New file: clientConsole/src/pages/creator/CharacterGroupFormPage.tsx
Lightweight creator form for character groups:
- Fields: name, description
- Members list: add characters via EntityPickerModal, edit always_on_summary and override_system_prompt inline, drag-to-reorder
- Route:
/creator/character-groups/new,/creator/character-groups/:id
New file: clientConsole/src/pages/creator/TrackerFormPage.tsx
Creator form following existing Forge pattern:
- Fields: name, key, description, value type selector, initial value, extraction hint
- Conditional fields based on valueType (enum values editor, numeric min/max)
- Advanced section: injection mode, scope, linked lorebook picker, linked character group picker (visible when valueType = list), visibility, is_visible toggle
- Route:
/creator/trackers/new,/creator/trackers/:id
Frontend Layer (adminConsole)
New file: adminConsole/src/components/content/TrackersTab.tsx
Admin table following CharactersTab.tsx pattern:
- Columns: name, key, valueType, creator info, stats, report counts, status
- Moderation actions, search/filter support
Migration for Existing Data
The existing ActiveTrackersJson (string array) and tracker_json (key-value) on conversations/messages remain compatible. The migration path:
- New tracker entity table is created alongside existing columns
- Character bindings are optional -- conversations without bindings continue working with freeform tracker names
- Gradually, character creators define proper trackers and bind them
- Freeform tracker names on existing conversations are preserved
Architecture Integration Points
Beyond the entity CRUD scaffolding, trackers need to hook into several existing systems. These are the key integration points where tracker logic connects to the running architecture.
Pipeline: Story Injection (Part 1 — Read-Only Context)
Tracker state enters the story pipeline via two injection targets (see Two-Part Injection Design):
System-level content (linked lorebook entries, character group member prompts for present items):
| What | Where | Action |
|---|---|---|
| Provider interface | Core/Pipeline/Interfaces/IPromptContentProvider.cs |
Implement TrackerContentProvider with Key = "tracker" |
| Context key | Core/Pipeline/ContextKeys.cs |
Add public const string Tracker = "tracker" |
| Provider registration | Core/DependencyInjection/CoreServiceCollectionExtensions.cs |
Register TrackerContentProvider via TryAddEnumerable alongside existing providers |
| Dynamic provider | Core/Pipeline/Providers/PromptContextManager.cs |
Add "tracker" to DynamicProviderKeys (content changes per-message), add status label "Evaluating tracker state" |
The TrackerContentProvider.GetContentAsync() resolves linked content for present items: lorebook entries from linked_lorebook_id, character system prompts (or overrides) from linked_character_group_id. This goes into the system prompt area via standard provider output.
User-message-level state block (compact tracker values attached to last user message):
| What | Where | Action |
|---|---|---|
| Message building | Core/Pipeline/Stages/ — the stage that assembles the message list for the LLM |
Append tracker state block to the last user message (or insert as a separate user-role message immediately before it) |
| Content format | TrackerContentProvider or dedicated helper |
Format current values per tracker InjectionMode — no extraction hints, no type info, just state |
This is injected as user role specifically so the story LLM doesn't echo the tracker format in its narrative response.
Pipeline: Post-LLM Evaluation (Part 2 — Separate Call)
After the story LLM streams the response, tracker evaluation runs as a post-LLM stage with its own LLM call.
| What | Where | Action |
|---|---|---|
| Post-stage interface | Core/Pipeline/ChatPipelineFactory.cs |
Add "tracker_evaluation" to post-stages at Order=220 — third sibling after summarization (200) and journal (210). See Risk #5. |
| Stage implementation | New: Core/Pipeline/Stages/TrackerEvalStageBase.cs |
Implement IPostLlmStage mirroring JournalEvalStageBase shape. Builds evaluation prompt from 4 inputs (previous state, user message, assistant response, tracker definitions+hints), calls TrackerEvalService (which mirrors JournalEvalService — sets LlmRequest.RequireJsonObject = true, uses the same forgiving JSON parser), validates types, stores in message.tracker_json. Must be fire-and-forget — heavy LLM call inside detached Task.Run(...), ProcessAsync returns in milliseconds. Breaking this convention adds wall-clock time to every assistant turn. |
| Per-call stats | tracker_eval_stats table (lives inside 68_tables_trackers.sql, not a separate 27b_* file — see Phase 1 schema delta) + ITrackerEvalStatsRepository |
Mirror journal_eval_stats shape exactly. Columns: provider, model, cadence, prompt/completion/total/cache tokens, api_latency_ms, trackers_updated, trackers_skipped, parse_status (ok/fallback/failed), error_type, error_message. Inserted in try/finally so failed calls still produce a row. |
| Stats aggregation | database/v1/functions/70_stats_functions.sql + DefaultStatsMetrics.Build |
Add fn_stats_tracker_evals + StatsMetric("tracker_evals", ...) mirroring the journal entry. Makes per-conversation/per-user tracker eval cost and parse-failure rate visible in the same analytics surfaces as messaging and journal. |
| Feature toggle | Core/Settings/SettingsKeys.cs + HowDrawer Active Features panel |
Add Features.EnableTrackers (default true) following the Features.EnableJournal pattern. When off: provider returns empty AND the eval stage short-circuits before the LLM call (no spend on a turned-off feature). Per-conversation override, defaults from a user-level preference, resolved through ?? true. NOT mode-gated (revised 2026-05-31): trackers run on any mode; a mode omitting the "tracker" sub-prompt only shows a soft warning, not a mode-locked lock. |
| Regenerate-from-conversation | New: WebTrackerRegenerateService + POST /api/conversations/{id}/trackers/regenerate |
Mirror the Phase 1.6 Journal regen pattern — chunked walk over raw message-pairs, SSE progress events, ITrackerRegenLock for mutual exclusion with the per-message eval stage. Same destructive-opt-in shape ("Also wipe my manual edits"). |
| Pipeline context | Core/Pipeline/Interfaces/IPipelineContext.cs |
Already has InputTrackerJson / OutputTrackerJson — evaluation stage writes to OutputTrackerJson |
| Message persistence | Core/Pipeline/Stages/MessageStorageStageBase.cs |
Already stores context.InputTrackerJson and context.OutputTrackerJson — no changes needed |
The evaluation stage fires after the response is stored (so the user already sees it). On failure, tracker values carry forward unchanged — the story is unaffected. The evaluation prompt includes all four required inputs: previous tracker state, user message, assistant response, and tracker definitions with extraction hints and type constraints.
Pipeline: Lorebook Search Integration
Tracker values feed into the lorebook search query to keep relevant entries in scope.
| What | Where | Action |
|---|---|---|
| Search query building | Core/Pipeline/Providers/LorebookContentProvider.cs → BuildSearchQueryAsync() |
Append active tracker values to the search query alongside recent messages |
| Active lorebook set | Same file, lorebook resolution logic | For present character group members, add their character_lorebook_bindings to the active lorebook set |
| Linked lorebook search | Same file or TrackerContentProvider |
For trackers with linked_lorebook_id, search that specific lorebook with the tracker value as query |
Currently, BuildSearchQueryAsync() scans the last N messages (MessageScanDepth) and combines text for search. Tracker values are appended to this query so lorebook entries matching tracker state (location, roster, etc.) stay in scope even when not mentioned in recent messages.
Conversation Creation Flow
When a new conversation is created, tracker bindings from the character and package must be auto-activated.
| What | Where | Action |
|---|---|---|
| Conversation creation | Database/Interfaces/IWebConversationRepository.cs → CreateConversationAsync() |
After creating conversation, resolve tracker bindings from character + package and insert into conversation_tracker_bindings (or populate conversation_trackers.trackers_json) |
| Package application | Package application flow in ConversationsEndpoints.cs |
When applying a package, bind the package's trackers. Respect trackers_locked flag. |
| Initial values | Same flow | Store initial tracker values (with override precedence: greeting > package > character > tracker default) as the first message's tracker_json |
Settings: Tracker LLM Configuration
Tracker evaluation uses its own LLM settings family with a fallback chain — mirroring JournalEvalLlm.*. (An earlier revision floated hosting eval on an AI Task row, which would have made this family unnecessary; that approach was reversed — see Part 2: Tracker Evaluation and the dedicated-service warning in the post-LLM evaluation section. The settings family is required.) Canonical key names are the TrackerEvalLlm.* set in the Phase 1 settings table, including TrackerEvalLlm.PresetId and the "Use for Trackers" preset action; the TrackerLlm.* names below are the older spelling for the same thing.
| What | Where | Action |
|---|---|---|
| Settings keys | Core/Settings/SettingsKeys.cs |
Add TrackerEvalLlm.{Provider,Model,Endpoint,ApiKey,PresetId} following the JournalEvalLlm pattern |
| Settings defaults | Core/Settings/SettingsDefaults.cs |
Add default entries — empty (falls back through chain) |
| Fallback chain | LlmPresetEnricher |
TrackerEvalLlm → JournalEvalLlm → SummarizationLlm → Llm → default built-in |
| Preset-delete sweep | functions/66_fn_clear_preset_references.sql |
Add a TrackerEvalLlm.PresetId branch alongside the existing JournalEvalLlm.PresetId one |
Context Budget
Tracker content consumes tokens from the context budget.
| What | Where | Action |
|---|---|---|
| Budget calculation | Database/Interfaces/IConversationBrowseRepository.cs → GetContextBudgetAsync() |
Include tracker token usage in context budget data |
| Budget display | Frontend HowDrawer context budget visualization | Add tracker segment to the budget breakdown |
Tracker token cost = tracker state block + linked lorebook entries for present items + always-on summaries. The TrackerContentProvider should report its token usage for budget calculation.
Entity System Hooks
These are automatic once EntityType.Tracker = 15 is added to the registry (see the entity-slot warning — 11 and 14 are both taken).
| What | Where | Action |
|---|---|---|
| Entity registry | Core/Entities/EntityRegistry.cs |
Add enum value + definition + dictionaries (already documented above) |
| Bookmarks | Core/Storage/Models/UserContentBookmark.cs |
Automatic — uses EntityType enum, no code changes needed |
| Notifications | Core/Storage/Models/Notification.cs |
Automatic — uses EntityType for entity references |
| Publish requests | Database/Interfaces/IPublishRequestRepository.cs |
Automatic — CheckEntityOwnershipAsync() uses entity type int |
| Entity permissions | database/v1/13_tables_permissions.sql |
entity_type = entity_type('tracker') (slot 15) — automatic via existing permission system |
| Public URL resolver | fn_get_entity_public_url() (in functions/60_entity_public_url.sql) |
Add a branch for entity_type('tracker') (slot 15) to generate tracker browse URL |
| Entity UUID resolver | Database/Interfaces/IEntityUuidRepository.cs |
Add "tracker" to UUID resolution — maps UUID ↔ integer ID |
Changelog Triggers
Track create/update/delete operations on tracker entities.
| What | Where | Action |
|---|---|---|
| Changelog trigger | database/v1/functions/43_entity_changelog_triggers.sql |
Add trg_tracker_changelog() function following trg_project_changelog() pattern — logs changed fields as JSON |
Conversation Column: show_trackers
The master visibility toggle needs storage on the conversation.
| What | Where | Action |
|---|---|---|
| Database | database/v1/07_tables_conversations.sql (or migration) |
Add show_trackers BOOLEAN NOT NULL DEFAULT FALSE to web_conversations |
| View | database/v1/views/06_conversation_view.sql |
Add show_trackers to the conversation view |
| C# model | Core/Storage/Models/WebConversation.cs |
Add ShowTrackers property |
| C# view | Database/Interfaces/ConversationView.cs |
Add ShowTrackers property |
| API DTOs | ServerAPI/Api/Models/WebChatModels.cs |
Already documented — add to conversation DTOs and update request |
UI Considerations
Creator Side (Forge)
- Tracker definition editor (name, type, initial value, extraction hint)
- Bind trackers to characters with ordering
- Preview how tracker injection looks in the prompt
Chat Side
Who Drawer:
- Trackers section positioned after Greeting, before Persona in the who drawer. Sits as a sibling to the World Knowledge section that Journal Phase 1 shipped into (above the lorebook list) — the two evaluation-driven features share visual territory in the drawer.
- Users can browse and add/remove trackers from conversations (same bind/unbind pattern as lorebooks)
- Binding sources: character (from
character_tracker_bindings, read-only), package (frompackage_tracker_bindings, read-only whentrackers_locked = TRUE), conversation (conversation_tracker_bindings, user-managed — the per-conversation override path on top of character/package bindings)
How Drawer:
- Master tracker visibility toggle next to streaming/model settings (see Tracker Visibility)
- Conversation-level on/off, persisted on the conversation
Features.EnableTrackerstoggle in the Active Features panel, sibling toFeatures.EnableJournaland the Summary / Memories / Lorebook / Picture-entry rows. Off = no injection AND no eval LLM call (no spend on a turned-off feature). Unlike the Journal toggle, it is NOT mode-gated (revised 2026-05-31) — trackers work on any mode; omitting the sub-prompt only shows a soft warning.
Chat Bubbles:
- Collapsed tracker bar below assistant messages (visible when master toggle is on) -- compact key:value pairs, pipe-separated
- Context menu on message bubbles: "Show/Hide tracker details" to expand full tracker state for a specific message
- Expanded view shows each tracker with type-appropriate rendering (progress bar for numeric, chips for list, highlight for changed values)
- Inline editing of tracker values on any message via edit button in expanded view
- Tracker history/timeline accessible per conversation
Browse / Hub
- Characters show their trackers in the detail view
- Filter/search by tracker presence ("characters with HP tracking")
Profile Dashboards (later)
Profile pages (fn_get_profile_page + ProfilePageContentEnricher, shipped after this doc was written) accept a typed section catalog (about, characters, modes, lorebooks, packages, projects, stats_overview, platforms). A future trackers section type would let creators surface their public trackers on their profile alongside characters and lorebooks. This is a downstream addition — out of scope for the initial tracker rollout, but worth keeping the section-catalog naming in mind so a trackers key stays available.
Known Risks & Mitigations
1. Numeric Tracker Accuracy
Risk: When the narrative says "you take a slash across the arm," the evaluation LLM has to invent a number. HP went from 72 to... 58? 65? 60? There's no ground truth. This will be the primary source of user complaints — values drifting from what the user expects.
Mitigation:
- Numeric trackers work best when the narrative is mechanically explicit (RPG-style: "you take 14 damage") rather than purely literary. The doc and creator guidance should set this expectation.
ExtractionHintis the main tool: creators can write hints like "Minor wound = -5 to -10. Major wound = -15 to -25. Healing potion restores +20. When ambiguous, round conservatively (less damage, less healing)."- The inline edit button on the tracker bar lets users correct drift quickly when it happens — make this workflow frictionless.
- Consider a future "confirmation mode" where the evaluation proposes changes and the user approves before they're stored.
2. List Tracker Implicit Removals
Risk: If Grimjaw stops talking for 3 messages, did he leave the scene? Or is he standing there quietly? The evaluation LLM will struggle with implicit departures — explicit exits ("Grimjaw waves goodbye") are fine, but the ambiguous middle ground causes roster drift.
Mitigation:
ExtractionHintguidance for list trackers should instruct: "Only remove characters when there's clear evidence they left (explicit departure, scene change to a new location without them). Characters who are simply quiet remain present."- The evaluation prompt includes the user message, which helps — if the user says "we leave Grimjaw behind," that's unambiguous even if the narrative is vague about it.
- The tracker bar makes drift visible, and inline editing lets users fix it immediately.
3. User-Message Injection Requires New Pipeline Mechanism
Risk: Every existing content provider uses GetContentAsync() → content goes into the system prompt area. Injecting tracker state into the last user message is architecturally different — the pipeline doesn't have a hook for "append to the last user message." This isn't a drop-in provider.
Mitigation:
- This needs a new injection point in the message-building stage, not a standard
IPromptContentProvider. TheTrackerContentProviderhandles system-level content (linked lorebook entries, character group prompts) via the standard mechanism. The user-message state block needs a separate path — either:- A new interface (e.g.,
IUserMessageDecorator) that the message-building stage calls to append content to the last user message - Or a special-case in the message-building stage that checks for tracker context on
IPipelineContextand appends it
- A new interface (e.g.,
- The second option is simpler and avoids over-engineering for what is currently a single use case. If other features later need user-message injection, extract the interface then.
4. Character Group Lorebook Token Budget Explosion
Risk: 5 present characters × 2 lorebooks each × 3 entries per lorebook × 200 tokens = 6,000 tokens just from presence-gated lorebooks. On top of system prompt, summaries, persona, regular lorebooks, and always-on summaries, this can blow the context window.
Mitigation:
- Add a total token cap for character group lorebook activation — e.g.,
MaxCharacterGroupLorebookTokenssetting (default: 2,000). When the total exceeds the cap, lower-priority characters' lorebooks are dropped first (priority = sort_order on the group membership). - Presence-gated lorebooks share the existing
Knowledge.MaxEntriesbudget with regular lorebook results. They don't get their own unlimited allocation — they compete for the same entry slots. - The context budget visualization in the How drawer should show character group lorebook usage as a visible segment so creators can see the cost.
- Forge should warn creators when a character group's total potential lorebook cost exceeds the budget: "5 characters with 12 total lorebook entries (~3,200 tokens). Consider reducing entries or using compact character overrides instead of full lorebooks."
5. Combined Tracker + Journal Evaluation Call
Decided against (2026-05-24). Journal Phase 1 shipped with two separate calls even on the on_summarization cadence — the journal eval runs as a second LLM call after summarization completes, never as an extended schema on the summarization call ("two calls keep prompts focused; entangling them means one bad parse drops both"). Tracker eval lands as a third independent sibling stage, not a combined call.
The three post-LLM eval siblings:
| Stage | Order | Source |
|---|---|---|
SummarizationStageBase |
200 | shipped |
JournalEvalStageBase |
210 | shipped (Phase 1) |
TrackerEvalStageBase |
220 | proposed (this doc) |
All three follow the fire-and-forget convention (heavy LLM call inside a detached Task.Run(...), ProcessAsync returns in milliseconds) so they race to completion in parallel by default — no scheduler, no orchestration, no shared state. The pattern stays parallelism-friendly only as long as no implementer awaits the LLM call inline.
Open Questions
Tracker sharingResolved: Trackers are standalone entities (like lorebooks) that multiple characters and packages reference via binding tables. The package system already has atrackers_lockedflag and a stubbedpackage_tracker_bindingstable, confirming this pattern. A "Game Time" tracker can be reused across characters and packages. Standalone trackers can be shared via the existingEntityPermissionsystem and discovered in the Hub whenis_public = TRUE.Cross-conversation trackersResolved (revised 2026-05-24): Trackers have ascopeproperty —conversation,character, orpackage— the same set lorebooks use. The scope says where the definition lives. Tracker values are per-conversation only; Journal Phase 1 shipped without a persistence rail, so the earlier "persist via Journal commit" plan is removed. Cross-conversation value continuity is a Phase 2+ topic dependent on Journal materialization. See Scope.Evaluation prompt tuning: The evaluation LLM needs to reliably output valid JSON with only changed values. For list-type trackers (roster), it needs to handle additions AND removals accurately. May need few-shot examples in the evaluation prompt for complex tracker types. How much prompt engineering is needed per tracker type?
Token budget: Tracker context in the prompt costs tokens. Need a way to manage how verbose the tracker injection is, especially with many active trackers. Linked-lorebook results add to this -- a roster with 5 characters could inject 5 lorebook entries.
Greeting integrationResolved: Yes. A greeting carries start values (character_greetings.tracker_json), and a package can set its own per greeting (package_greeting_bindings.tracker_json) — each a JSON object mapping tracker keys to starting values. A "Start at the tavern" greeting setslocation: "The Rusty Tankard". Precedence for every key, as built (TRACKER_GREETING_START_DELIVERY.md D6): the package's greeting binding > the character's greeting > the winning binding's own start > the tracker'sinitial_value. (Was: atracker_overrides_jsonfield, with package binding beating character binding — superseded.) See Package Integration.Linked lorebook injection positionResolved: Option (a) alongside tracker values in the"trackers"provider output. Keeps tracker state and its associated lorebook context together as a coherent block. The AI sees "Current state: Location = Shadowkeep" immediately followed by the Shadowkeep lorebook entry, rather than having to correlate state in one part of the prompt with lorebook data elsewhere. The"lorebook"provider continues to handle general (non-tracker-linked) lorebook injection independently.Roster identity matchingResolved: Linked-lorebook search uses keyword matching against tracker value items as the query. This is the most reliable approach for name-based lookups -- the roster value"Elara"matches against the lorebook entry's keywords directly. Standard vector/FTS search is unnecessary overhead for what is essentially a keyed lookup. If the roster contains"the ranger"and Elara's keywords include"the ranger", the match works. The evaluation LLM'sExtractionHintshould guide it to use primary keywords (character names) rather than descriptors to keep matching reliable.Roster deduplicationResolved: Yes, deduplicate. If "Elara" is in the roster AND mentioned in a recent message, the lorebook entry appears once. The tracker-linked result takes precedence (it's deterministic and guaranteed), and the general lorebook search result is suppressed. This is consistent with the design where linked-lorebook results are injected alongside the tracker (option a from Q6), separate from the general lorebook provider -- deduplication happens at the prompt assembly level by entry ID.Conditional entry evaluation cost: In Phase 2, every candidate lorebook entry needs its conditions checked against tracker state. With many entries and many conditions, this adds a filtering step to every search. Should condition checking happen in the database (WHERE clause on tracker state) or in application code (post-filter)? Database is faster but requires tracker state to be query-accessible.
Condition authoring UX: Conditions reference tracker keys that might come from a different creator (the character creator defines trackers, the lorebook creator defines conditions). How do we surface available tracker keys when editing lorebook entry conditions? Should conditions be validated against known trackers at save time, or loosely coupled (reference any key string, fail silently if tracker doesn't exist)?
Tracker key stability: Conditional entries reference tracker keys by string. If a creator renames a tracker key, conditions on lorebook entries break silently. Options: immutable keys after first use in a condition, cascade rename to conditions, or warn at rename time with a list of affected entries.
Always-on summary token budgetResolved: GlobalMaxAlwaysOnSummaryTokenscap (default 800) with priority-based dropping viasort_order. Forge shows live token count with warnings. See Presence-Aware Character Injection.Character lorebook nesting: Character lorebooks can have their own attached lorebooks (e.g., an NPC lorebook links to a faction lorebook). How deep should this nesting go? One level seems practical; deeper nesting risks unpredictable token costs and circular references. Should the system enforce a depth limit?
Presence-Aware pattern generalizationResolved: This is a first-class lorebook feature, not a distinct lorebook type. Any lorebook entry can have analways_on_summaryfield, and any lorebook can be linked to a list-type tracker. This avoids creating a separate "character lorebook" concept and keeps the lorebook system unified. Thealways_on_summaryfield is optional and has no effect on entries in lorebooks that aren't tracker-linked -- it only activates when the lorebook is bound to a tracker vialinked_lorebook_id. This means the same lorebook can function as a regular keyword-searched lorebook AND as a tracker-linked lorebook simultaneously.Revisit — a reader-only "show tracker bars" preference. (The owner answered the debugging half on eod-519 with the folded "and N hidden trackers" on chat.'s scene, now built: see Revealing hidden trackers. A preference to fold the visible scene away is still open.) Layer 1 above designed a visibility toggle; what shipped is the Trackers feature switch, which also stops the model from getting any tracker. A reader who wants the bars out of the way but the story to keep tracking has no control for that today. A separate, display-only preference would close it. A product change: it waits for the owner (Relay), and is not built (director (b7), 2026-11-25, on a user report the owner forwarded).
Revisit — a staff reveal of hidden trackers. eod-519's reveal is the story owner's, in their own story. When staff look into a report, they use the moderator transcript (AdminAPI), which shows what readers see (
ShownTrackers.SnapshotJson). A staff-only "and N hidden trackers" there would need its own read, gated by the support or moderation area. Not built (HIDDENREVEAL lane, 2026-11-25).Revisit — a visual-novel turn's stored
trackers. A VN turn'sscene_jsonrecords the tracker values its blocking guard read (SceneTurnRecord.Trackers: the keys the scene graph gates a move on, for replay). The run's turn read servesscene_jsonas stored. So if a graph gates on a tracker an author hid, that value is in the payload. The VN console parses the field and draws nothing from it, so no hidden value is shown on screen. Cutting it from the served copy is the VN owner's call (HIDDENREVEAL lane, 2026-11-25).