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:

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:

  1. 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.

  2. Inject tracker state as a user message, 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 treat user turns 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:

  1. 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.

  2. 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:

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):


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

  1. Simplest value type: Freeform text, no validation, no linked lorebook. Pure state tracking.
  2. Existing infrastructure is ready:
    • tracker_json on messages already stores tracker values per message
    • tracker_start_json / tracker_end_json on summaries already capture state across summary boundaries
    • ActiveTrackersJson on conversations already stores active tracker names
  3. Immediate value for memories and summaries: The memory and summarization systems already have a IncludeTimeHeader setting with a "gametime" option that's stubbed but unimplemented:
    • SummaryContentProviderBase.cs:59 → // "gametime" => future implementation
    • WebMemoryContentProvider formats 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):

2. Prompt injection (new, minimal):

3. Tracker evaluation (new, separate call):

4. Summary time headers (fill existing stub):

5. Memory time headers (fill existing stub):

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


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:

  1. When a user starts a conversation from a package, the package's bound trackers are automatically activated.
  2. If trackers_locked = TRUE, the user cannot add/remove trackers -- the package author controls the tracker set entirely.
  3. If trackers_locked = FALSE, the user can add/remove non-required trackers beyond what the package provides.
  4. OverrideInitialValue on the package binding takes precedence over the character binding's override, which takes precedence over the tracker's own InitialValue. 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:

What's NOT injected:

The provider key is "trackers" (added to ContextKeys.cs). The TrackerContentProvider handles two injection targets:

  1. System-level: linked lorebook entries and character group content for present items (via standard provider output)
  2. 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):

  1. Last tracker state — the current values from the previous message's tracker_json (or initial values if first message)
  2. Last user message — what the user said/did (provides intent context for state changes)
  3. Last assistant message — the story response (the primary source of state changes)
  4. 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:

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:

  1. Creator updates an ExtractionHint in the Forge
  2. Goes back to the conversation, finds a message where extraction was wrong
  3. Clicks "Re-evaluate" on that message
  4. Sees the new extraction result alongside the stored one
  5. 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:

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:

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:

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:

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.


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:

  1. The tracker value is used as a search query against that specific lorebook
  2. Matching entries are injected (alongside or separate from the general lorebook search)
  3. 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):

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:

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:

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:

  1. 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.

  2. 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:

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.

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:

  1. The tracker provider reads the current tracker value (list of present character names)
  2. For each present character member, resolve their character_lorebook_bindings
  3. Add those lorebook IDs to the active lorebook set for this message's search
  4. Absent characters' lorebooks are excluded from the search set
  5. The lorebook provider searches across the combined set: conversation-bound lorebooks + present characters' lorebooks

Edge cases:

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:

  1. Always-on summaries from both character group members and lorebook entries (shared token budget)
  2. Present characters: inject system prompt (or override) for group members, inject lorebook entry content for lorebook matches
  3. Present group members' attached lorebooks become active for search
  4. 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:

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:

  1. 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. The key field on the tracker entity should be immutable after creation (or rename should cascade to conditions).

  2. 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 tracker ValueType directly determines which condition operators are valid.

  3. 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.

  4. Package integration: Packages that bundle trackers + lorebooks can pre-wire conditions. A "Fantasy RPG" package ships with a story_arc enum 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:

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:

  1. Its character's bindings (via character_tracker_bindings)
  2. Its package's bindings, if started from a package (via package_tracker_bindings)
  3. 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 Freeform only. UPDATED — typed values shipped 2026-05-31 (post-Phase-1). Phase 1 launched freeform-only; the type system (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 Branching does not copy tracker values. The new branch starts with each tracker initialized from its binding's override_initial_value (or the tracker's InitialValue). Superseded (verified 2026-09-03): 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:

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.

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:

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 New 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 Extract 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):

  1. Numeric / enum / list value types + the validation + visualization that comes with them (HP bars, chips, enum highlights)
  2. package and conversation scopes + package_tracker_bindings, conversation_tracker_bindings, the trackers_locked UX, conversation-level add/remove from the WhoDrawer
  3. Regenerate-from-conversation (Phase 1.6 in journal-speak — chunked walk, SSE progress, regen lock)
  4. Linked lorebooks (linked_lorebook_id) and the tracker-aware lorebook search arm
  5. always_on_summary on lorebook_entries + character groups + presence-aware injection
  6. Per-message expanded tracker view + timeline + "Why?" + evaluation log UI
  7. 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.

E2 — Discoverability (M). Prereq for E3. Makes the entity public-readable.

E3 — Publish & moderation (M). Depends on E2. Lets a tracker go public.

E4 — Social (M). Each item independent; depends on E2 for public context.

E5 — Collaboration (M). Unlocks shared editing.

E6 — Binding expansion (L). Activates the forward-designed table. Overlaps Phase 2 item #2 ("package and conversation scopes").

Not planned (record the decision):

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):

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):

Behavior:

Invariants that must stay true:

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:

P1 — Trackers on a package

Acceptance Criteria (P1)

User use cases — satisfiable + accessible (verify by driving the UI, not the code):

Behavior:

Invariants that must stay true:

Edges:

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):

Acceptance criteria — T2

User use cases:

Behavior:

Invariants:

Edges:

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):

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:

New file: database/v1/views/46_admin_trackers_view.sql

Admin view following admin_lorebooks_view pattern:

Add to: database/v1/views/10_entity_stats_materialized.sql

New materialized view mv_tracker_stats:

New file: database/v1/functions/78_tracker_functions.sql

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

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

New file: server/EchoOfDreams.Database/Repositories/TrackerRepository.cs

New file: server/EchoOfDreams.Database/Interfaces/IAdminTrackerRepository.cs

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:

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

New file: server/EchoOfDreams.ServerAPI/Api/Endpoints/CreatorTrackerEndpoints.cs

Full CRUD following CreatorCharacterEndpoints.cs pattern:

Modify: server/EchoOfDreams.ServerAPI/Api/Endpoints/ConversationsEndpoints.cs

Add tracker endpoints mirroring the lorebook binding pattern:

New file: server/EchoOfDreams.AdminAPI/Api/Endpoints/AdminTrackersEndpoints.cs

Admin CRUD following AdminCharacterEndpoints pattern.

New file: server/EchoOfDreams.Database/Interfaces/ICharacterGroupRepository.cs

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:

Modify: DI registration

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:

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:

Modify: clientConsole/src/pages/chat-v2/components/WhoDrawer.tsx

Add tracker section after Greeting (line 420), before Persona (line 422):

Modify: clientConsole/src/pages/chat-v2/components/HowDrawer.tsx

Add master tracker visibility toggle:

New file: clientConsole/src/components/chat/TrackerBar.tsx

Collapsed tracker bar component rendered below assistant message bubbles:

New file: clientConsole/src/components/chat/TrackerDetails.tsx

Expanded tracker detail panel for a single message:

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:

Modify: clientConsole/src/pages/creator/TrackerFormPage.tsx (additional features)

Testing tools on the Forge tracker editor:

Backend: Evaluation endpoints for testing tools

Modify server/EchoOfDreams.ServerAPI/Api/Endpoints/ConversationsEndpoints.cs:

Modify server/EchoOfDreams.ServerAPI/Api/Endpoints/CreatorTrackerEndpoints.cs:

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):

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:

New file: clientConsole/src/pages/creator/TrackerFormPage.tsx

Creator form following existing Forge pattern:

Frontend Layer (adminConsole)

New file: adminConsole/src/components/content/TrackersTab.tsx

Admin table following CharactersTab.tsx pattern:

Migration for Existing Data

The existing ActiveTrackersJson (string array) and tracker_json (key-value) on conversations/messages remain compatible. The migration path:

  1. New tracker entity table is created alongside existing columns
  2. Character bindings are optional -- conversations without bindings continue working with freeform tracker names
  3. Gradually, character creators define proper trackers and bind them
  4. 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)

Chat Side

Who Drawer:

How Drawer:

Chat Bubbles:

Browse / Hub

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:

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:

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:

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:

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

  1. Tracker sharing Resolved: Trackers are standalone entities (like lorebooks) that multiple characters and packages reference via binding tables. The package system already has a trackers_locked flag and a stubbed package_tracker_bindings table, confirming this pattern. A "Game Time" tracker can be reused across characters and packages. Standalone trackers can be shared via the existing EntityPermission system and discovered in the Hub when is_public = TRUE.

  2. Cross-conversation trackers Resolved (revised 2026-05-24): Trackers have a scope property — conversation, character, or package — 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.

  3. 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?

  4. 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.

  5. Greeting integration Resolved: 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 sets location: "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's initial_value. (Was: a tracker_overrides_json field, with package binding beating character binding — superseded.) See Package Integration.

  6. Linked lorebook injection position Resolved: 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.

  7. Roster identity matching Resolved: 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's ExtractionHint should guide it to use primary keywords (character names) rather than descriptors to keep matching reliable.

  8. Roster deduplication Resolved: 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.

  9. 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.

  10. 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)?

  11. 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.

  12. Always-on summary token budget Resolved: Global MaxAlwaysOnSummaryTokens cap (default 800) with priority-based dropping via sort_order. Forge shows live token count with warnings. See Presence-Aware Character Injection.

  13. 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?

  14. Presence-Aware pattern generalization Resolved: This is a first-class lorebook feature, not a distinct lorebook type. Any lorebook entry can have an always_on_summary field, 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. The always_on_summary field 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 via linked_lorebook_id. This means the same lorebook can function as a regular keyword-searched lorebook AND as a tracker-linked lorebook simultaneously.

  15. 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).

  16. 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).

  17. Revisit — a visual-novel turn's stored trackers. A VN turn's scene_json records 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 serves scene_json as 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).