Mode-Specific Lorebook Injection

Status: Planned

Overview

Currently, the "lorebook" provider key searches all lorebooks merged from the conversation's three sources (character, persona, conversation bindings). The mode has no say in which lorebooks are searched -- it either includes lorebook content or doesn't.

This feature allows a sub-prompt with provider key "lorebook" to optionally specify one specific lorebook to inject, giving mode creators precise control over which world-building data appears and where in the prompt it goes.


Problem

Current behavior

A mode includes a sub-prompt with provider_key = "lorebook". When the pipeline processes this:

  1. Collect all lorebooks bound to the conversation (character + persona + conversation bindings)
  2. Search all entries across all lorebooks
  3. Inject matching entries at the sub-prompt's position

The mode creator has no control over which lorebooks are searched. If a character has 3 lorebooks bound (world lore, NPC directory, item catalog), the mode gets all of them merged together or none of them.

Why this is limiting

  1. Positioning: A mode might want world lore early in the prompt (high priority context) but item descriptions later (reference material). With one provider key, all lorebook content lands in the same spot.

  2. Framing: Different lorebooks benefit from different instructions. World lore might need "treat these as absolute facts" while NPC entries might need "use these as reference but adapt to the scene." A single sub-prompt template applies one framing to all.

  3. Budget control: A mode might want to allocate 5 entries max to world lore and 3 to NPCs. Currently, the combined budget is shared -- a chatty world lorebook could crowd out NPC entries. Individual entries should target ~500 tokens for optimal search relevance and token efficiency (see Design Principles: Token Budget).

  4. Mode-bundled lore: A mode creator might want to ship a lorebook with their mode -- e.g., a "Mystery Investigation" mode that includes its own lorebook of investigation-related prompts and techniques. Without specific lorebook targeting, the mode can't reference its own bundled lorebook.


Proposed Design

Sub-Prompt Level: Lorebook Reference

Add an optional lorebook_id field to the sub-prompt ↔ mode link (or to the sub-prompt itself):

PromptModeSubPromptLink
├── ... existing fields ...
└── LorebookId    (optional) FK to lorebooks table

Behavior:

provider_key lorebook_id Result
"lorebook" NULL Current behavior: search all merged lorebooks
"lorebook" 42 Search ONLY lorebook #42
not "lorebook" any lorebook_id ignored

Multiple Lorebook Sub-Prompts

A mode can include multiple sub-prompts with provider_key = "lorebook", each targeting a different lorebook:

Mode: "Epic Adventure"
  Sub-prompt 1: provider="character", order=0
    → Character personality
  Sub-prompt 2: provider="lorebook", lorebook_id=10, order=100
    → Template: "World lore (treat as absolute facts):\n{content}"
    → MaxEntries override: 5
  Sub-prompt 3: provider="lorebook", lorebook_id=11, order=200
    → Template: "Known NPCs (adapt to current scene):\n{content}"
    → MaxEntries override: 3
  Sub-prompt 4: provider="lorebook", lorebook_id=NULL, order=300
    → Template: "Additional context:\n{content}"
    → Catches everything else from character/persona/conversation bindings
  Sub-prompt 5: provider="persona", order=400
    → User persona

Search Scope Resolution

When lorebook_id is set, the provider:

  1. Searches only entries from that specific lorebook
  2. Uses its own MaxEntries / threshold settings (could override from sub-prompt or lorebook defaults)
  3. Does NOT deduplicate against other lorebook sub-prompts (each operates independently)

When lorebook_id is NULL (default):

  1. Current behavior: merge all lorebooks from character + persona + conversation
  2. Exclude any lorebooks already targeted by a specific sub-prompt in the same mode (avoids double-injection)
  3. This makes the NULL lorebook sub-prompt a "catch-all" for remaining lorebooks

Mode-Bundled Lorebooks

A mode can own a lorebook that gets automatically included when the mode is active:

PromptMode
├── ... existing fields ...
└── BundledLorebookId    (optional) FK to lorebooks table

When a conversation uses this mode:

Use cases:


Pipeline Changes

LorebookContentProvider

Currently a single provider registered under key "lorebook". Needs to support:

  1. Context-aware filtering: Accept a lorebookId parameter from the sub-prompt context
  2. Exclusion set: When running in catch-all mode, accept a set of lorebook IDs to exclude

Option A: Parameterized provider

The existing provider gains awareness of the sub-prompt's lorebook_id:

// In pipeline context, sub-prompt metadata is available
var targetLorebookId = currentSubPrompt.LorebookId;
var excludeLorebookIds = GetAlreadyTargetedLorebookIds(mode);

if (targetLorebookId.HasValue)
    searchContext.FilterToLorebook(targetLorebookId.Value);
else
    searchContext.ExcludeLorebooks(excludeLorebookIds);

Option B: Provider instance per sub-prompt

Create a new provider instance for each lorebook-targeting sub-prompt. Simpler logic per instance but breaks the singleton pattern.

Option A is preferred -- keeps the stateless service pattern from CLAUDE.md. The lorebook ID is context passed per-call, not stored in the provider.

Search Context Changes

LorebookSearchContext (or equivalent) needs:

public int? TargetLorebookId { get; set; }       // Search only this lorebook
public HashSet<int>? ExcludeLorebookIds { get; set; }  // Skip these (already handled)

Database queries filter accordingly:


Database Changes

-- Add lorebook reference to sub-prompt link
ALTER TABLE prompt_mode_sub_prompt_links
    ADD COLUMN lorebook_id INTEGER REFERENCES lorebooks(id);

-- Add bundled lorebook to modes
ALTER TABLE prompt_modes
    ADD COLUMN bundled_lorebook_id INTEGER REFERENCES lorebooks(id);

Minimal schema change. No new tables needed.


UI Considerations

Mode Editor (Forge)

Chat Side


Examples

Example 1: RPG Mode with separated lore

Mode: "Tabletop RPG"
  [order 0]   provider=character     → Character sheet and personality
  [order 50]  provider=scenario      → Current scenario/quest
  [order 100] provider=lorebook, lorebook_id=WORLD_LORE
    Template: "## World Rules\nThese are established facts about the world.
              The player cannot contradict these.\n{content}"
  [order 200] provider=lorebook, lorebook_id=BESTIARY
    Template: "## Bestiary Reference\nUse these stats and behaviors when
              these creatures appear.\n{content}"
  [order 300] provider=lorebook (catch-all)
    Template: "## Additional Lore\n{content}"
  [order 400] provider=recalled_memory → Past session memories
  [order 500] provider=persona         → Player character sheet

Example 2: Mode with bundled lorebook

Mode: "Detective Noir"
  BundledLorebook: "noir_investigation_techniques"
    Entries: "Crime scene analysis", "Interrogation approaches",
             "Evidence chain building", "Red herring detection"

  [order 0]   provider=character
  [order 100] provider=lorebook, lorebook_id=noir_investigation_techniques
    Template: "## Investigation Framework\nApply these techniques when the
              player investigates.\n{content}"
  [order 200] provider=lorebook (catch-all)
    Template: "## Case Files\n{content}"
  [order 300] provider=recalled_memory

The bundled lorebook travels with the mode. Anyone who uses "Detective Noir" mode automatically gets the investigation techniques, regardless of which character they pair it with.



When both features are active, tracker-driven lorebook results and mode-targeted lorebook results need to coexist. The resolution:

Tracker results land in the "trackers" provider output

Tracker-driven lorebook entries (from linked lorebooks) are injected as part of the "trackers" provider key output, alongside tracker values. This keeps the tracker and its context together:

Active trackers:
- Location: Shadowkeep, Level 2
  [Lorebook: Shadowkeep is a five-floor dungeon built by ancient dwarves.
   Level 2 contains the collapsed bridge and goblin warrens...]
- Roster: Elara, Grimjaw
  [Lorebook: Elara is a ranger from the Northern Reaches...]
  [Lorebook: Grimjaw is a veteran dwarven fighter...]

Mode-targeted results land in their sub-prompt position

Mode-specific lorebook sub-prompts inject at their configured position with their configured framing, independent of tracker results.

Deduplication

If a lorebook entry is matched by both a tracker (linked lorebook) and a mode sub-prompt (targeted lorebook), deduplicate. The mode sub-prompt wins placement (it has explicit framing), and the tracker provider skips the duplicate.

When neither feature is configured

Falls back to current behavior: single "lorebook" provider searches all merged lorebooks based on recent messages only.


Open Questions

  1. Per-sub-prompt MaxEntries: Should each lorebook sub-prompt have its own entry budget, or share the global Knowledge.MaxEntries setting? Per-sub-prompt is more flexible but adds complexity to the mode editor.

  2. Per-sub-prompt thresholds: Same question for search thresholds (vector, FTS, keyword). Probably overkill -- use the global settings and let the lorebook-level defaults handle it.

  3. Bundled lorebook ownership: When a mode is public and has a bundled lorebook, is the lorebook implicitly public too? Or does it need its own visibility setting?

  4. Catch-all exclusion: If the mode has specific lorebook sub-prompts but no catch-all, should remaining lorebooks be silently dropped or injected at a default position? Silently dropping is consistent with the current "mode controls everything" philosophy.

  5. Multiple modes sharing a lorebook sub-prompt: If a sub-prompt is shared across modes (via the N:M link), the lorebook_id lives on the link, not the sub-prompt. This means the same sub-prompt can target different lorebooks in different modes. Is this desired or confusing?

  6. Tracker overlap: If a mode has a sub-prompt targeting the NPC lorebook AND a roster tracker also links to the NPC lorebook, who "owns" the search? The deduplication strategy above resolves it, but creators need to understand the interaction.

  7. Interaction with conditional entries: Conditional entries add tracker-based activation conditions to lorebook entries. When a mode sub-prompt targets a specific lorebook, should it respect entry conditions (only inject entries whose tracker conditions are met) or bypass them (inject all matching entries regardless of state)? Respecting conditions is more consistent, but a mode creator might expect their targeted entries to always appear.