Lorebook LLM Editor
Status: Implemented (Phases 1-3) — see Lorebook Assistant for the user-facing documentation.
Prerequisite for: Living Lorebooks (Journal materialization)
Overview
The Lorebook LLM Editor (now called the Lorebook Assistant) is a chat-like interface where users collaborate with an LLM to create, edit, and refine lorebook entries. Instead of manually filling out forms entry-by-entry, the user converses with an assistant that has tool access to the lorebook -- it can read existing entries, search for related content, propose new entries, suggest edits, and batch-process raw notes into structured lorebook data.
The UX is inspired by Claude Code (a chat that proposes tool actions the user approves) and Ginger (standalone lorebook editor with find/replace, merge, and bulk operations), addressing the bulk-edit gap that SillyTavern's World Info editor lacks.
Use Cases
| Use Case | Description |
|---|---|
| Notes → Entries | User pastes rough notes, worldbuilding docs, or wiki text. The LLM parses them into structured lorebook entries with names, keywords, categories, and content. |
| Edit Existing | User has a lorebook but wants changes -- consolidate duplicate entries, improve keyword coverage, split oversized entries, update stale content. The LLM reads existing entries and proposes targeted edits. |
| From Scratch | User describes a world concept conversationally. The LLM iteratively builds entries, asking clarifying questions and proposing entries as the world takes shape. |
| Bulk Refactor | User wants to rename a faction across 20 entries, recategorize entries, or adjust priorities system-wide. The LLM proposes batch operations. |
Why This Matters
Manual lorebook editing doesn't scale. A detailed world has 50-200+ entries. Creating each one by hand (name, keywords, content, priority, category) is tedious. Maintaining consistency across entries is harder. The LLM editor turns lorebook creation from a form-filling exercise into a collaborative worldbuilding conversation.
This feature is also the prerequisite for living lorebooks -- the Journal's materialization step (converting auto-generated character/location profiles into lorebook entries) needs the same infrastructure: tool-based entry creation, proposal review, and session-scoped versioning.
Architecture
System Diagram
┌─────────────────────────────────────────────────────────────┐
│ Client (React) │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ Chat Panel │ │ Proposal │ │ Session Diff │ │
│ │ (messages, │ │ Review Panel │ │ Panel │ │
│ │ streaming) │ │ (approve/ │ │ (before/after │ │
│ │ │ │ reject/redo) │ │ per session) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────────┘ │
│ │ │ │ │
│ └────────┬────────┴──────────────────┘ │
│ │ SSE + REST │
└──────────────────┼──────────────────────────────────────────┘
│
┌──────────────────┼──────────────────────────────────────────┐
│ │ ServerAPI │
│ ┌───────────────▼──────────────────┐ │
│ │ LorebookAssistantEndpoints │ │
│ │ POST /sessions │ │
│ │ POST /sessions/{id}/chat (SSE)│ │
│ │ POST /sessions/{id}/approve │ │
│ │ POST /sessions/{id}/reject │ │
│ │ GET /sessions/{id}/diff │ │
│ └───────────────┬──────────────────┘ │
│ │ │
│ ┌───────────────▼──────────────────┐ │
│ │ LorebookAssistantService │ │
│ │ (orchestrates LLM + tools) │ │
│ │ │ │
│ │ ┌─────────────────────────┐ │ │
│ │ │ Semantic Kernel │ │ │
│ │ │ - Kernel + Plugins │ │ │
│ │ │ - Tool execution loop │ │ │
│ │ │ - Chat history mgmt │ │ │
│ │ └────────────┬────────────┘ │ │
│ │ │ │ │
│ │ ┌────────────▼────────────┐ │ │
│ │ │ LorebookToolPlugin │ │ │
│ │ │ (C# methods as tools) │ │ │
│ │ │ - SearchEntries │ │ │
│ │ │ - GetEntry │ │ │
│ │ │ - ListEntries │ │ │
│ │ │ - ProposeCreate │ │ │
│ │ │ - ProposeEdit │ │ │
│ │ │ - ProposeDisable │ │ │
│ │ │ - EstimateTokens │ │ │
│ │ │ - GetLorebookInfo │ │ │
│ │ │ - ListCategories │ │ │
│ │ └────────────┬────────────┘ │ │
│ │ │ │ │
│ └────────────────┼─────────────────┘ │
│ │ │
│ ┌────────────────▼─────────────────────────┐ │
│ │ PostgreSQL │ │
│ │ - lorebook_assistant_sessions │ │
│ │ - lorebook_assistant_messages │ │
│ │ - lorebook_entry_proposals │ │
│ │ - lorebook_session_snapshots │ │
│ │ - lorebook_session_snapshot_entries │ │
│ │ - Existing lorebook tables (partitioned) │ │
│ └────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Technology Choices
| Concern | Choice | Rationale |
|---|---|---|
| LLM orchestration | Semantic Kernel | Mature tool-calling loop, automatic function-to-tool schema generation, chat history management, multi-provider support. The existing ILlmClient abstraction handles chat; SK handles the tool loop for this feature specifically. |
| Tool definitions | C# methods with [KernelFunction] attributes |
Type-safe, discoverable, testable. SK auto-generates JSON schemas from method signatures. |
| LLM connectivity | IChatCompletionService via SK, backed by existing provider config |
SK supports OpenAI, Anthropic, Google connectors. Wire up using the user's existing LLM preset (provider, API key, model). Requires connector packages: Microsoft.SemanticKernel.Connectors.OpenAI, Microsoft.SemanticKernel.Connectors.Google, and the community Microsoft.SemanticKernel.Connectors.Anthropic package. |
| Database | Dapper + stored procedures (existing pattern) | Consistent with codebase. No EF Core introduction. Npgsql for connection pooling as already used. |
| Streaming | SSE (Server-Sent Events) | Same pattern as existing chat endpoint (/conversations/{id}/chat). |
Why Semantic Kernel (Not Raw SDK Calls)
The existing ILlmClient abstraction handles single-turn completions and streaming. The lorebook editor needs a multi-turn tool-calling loop: the LLM calls a tool, gets the result, decides to call another tool or respond to the user, and this cycle repeats. Building this loop manually for each provider (Anthropic, OpenAI, Gemini each have different tool-calling APIs) is significant work.
Semantic Kernel provides:
- Automatic tool-calling loop with configurable behavior (auto-invoke, manual invoke)
[KernelFunction]attribute to expose C# methods as tools with auto-generated schemas- Chat history management with tool call/result tracking
- Connectors for all providers the codebase already supports
FunctionChoiceBehaviorto control when/how the LLM uses tools
SK is used only for the assistant feature -- it does not replace the existing ILlmClient for chat conversations.
Microsoft.Extensions.AI Consideration
Microsoft.Extensions.AI provides a thinner abstraction (IChatClient) that can also handle tool calling. It's lighter than SK but requires more manual orchestration. SK builds on top of M.E.AI and adds the orchestration layer. Since the lorebook editor's core value IS the orchestration (multi-step tool loops with approval), SK's higher-level abstractions are justified here.
If future features need simpler LLM access without tool-calling (e.g., a one-shot "summarize this entry" button), M.E.AI's IChatClient could be used directly.
Data Model
New Tables
lorebook_assistant_sessions
An editing session scoped to one lorebook. Sessions persist across browser refreshes and can be resumed.
CREATE TABLE lorebook_assistant_sessions (
id SERIAL PRIMARY KEY,
lorebook_id INTEGER NOT NULL REFERENCES lorebooks(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id),
title VARCHAR(200),
status SMALLINT NOT NULL DEFAULT 0, -- 0=active, 1=completed, 2=abandoned
auto_approve BOOLEAN NOT NULL DEFAULT FALSE,
preset_id INTEGER REFERENCES llm_presets(id), -- LLM preset override
-- Stats
proposals_total INTEGER NOT NULL DEFAULT 0,
proposals_approved INTEGER NOT NULL DEFAULT 0,
proposals_rejected INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_las_user_lorebook ON lorebook_assistant_sessions(user_id, lorebook_id);
lorebook_assistant_messages
Chat history within a session. Stores both user/assistant messages and tool interactions.
CREATE TABLE lorebook_assistant_messages (
id SERIAL PRIMARY KEY,
session_id INTEGER NOT NULL REFERENCES lorebook_assistant_sessions(id) ON DELETE CASCADE,
role SMALLINT NOT NULL, -- 0=user, 1=assistant, 2=system, 3=tool_call, 4=tool_result
content TEXT NOT NULL,
-- Tool tracking (for role=tool_call and role=tool_result)
tool_name VARCHAR(100),
tool_call_id VARCHAR(200), -- Provider's tool call ID for correlation
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_lam_session ON lorebook_assistant_messages(session_id, created_at);
lorebook_entry_proposals
Pending changes proposed by the LLM. Each proposal is a single atomic operation on one entry.
CREATE TABLE lorebook_entry_proposals (
id SERIAL PRIMARY KEY,
session_id INTEGER NOT NULL REFERENCES lorebook_assistant_sessions(id) ON DELETE CASCADE,
message_id INTEGER REFERENCES lorebook_assistant_messages(id), -- Which assistant message proposed this
-- What operation
operation SMALLINT NOT NULL, -- 0=create, 1=update, 2=disable
-- Target (null for creates)
entry_id INTEGER REFERENCES lorebook_entries(id) ON DELETE SET NULL,
-- Proposed values (JSON to handle partial updates flexibly)
-- For updates: only changed fields are present (omitted = unchanged)
proposed_data JSONB NOT NULL, -- { name, keywords, content, priority, category, color, ... }
-- For updates: snapshot of the entry BEFORE the proposed change
original_data JSONB,
-- Optimistic locking: entry version at time of proposal
entry_version INTEGER, -- NULL for creates; checked on apply for updates/disables
-- Review state
status SMALLINT NOT NULL DEFAULT 0, -- 0=pending, 1=approved, 2=rejected, 3=auto_approved
reviewed_at TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_lep_session_status ON lorebook_entry_proposals(session_id, status);
CREATE INDEX idx_lep_entry_id ON lorebook_entry_proposals(entry_id);
lorebook_session_snapshots
Session metadata for snapshot tracking. The actual snapshot data lives in lorebook_session_snapshot_entries (one row per entry) rather than a single JSONB blob. This keeps snapshots queryable, avoids multi-megabyte JSONB for large lorebooks (200+ entries), and enables efficient per-entry diff computation in SQL.
CREATE TABLE lorebook_session_snapshots (
id SERIAL PRIMARY KEY,
session_id INTEGER NOT NULL REFERENCES lorebook_assistant_sessions(id) ON DELETE CASCADE,
lorebook_id INTEGER NOT NULL REFERENCES lorebooks(id) ON DELETE CASCADE,
entry_count INTEGER NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(session_id)
);
lorebook_session_snapshot_entries
Per-entry snapshot rows. Each row captures one entry's state at session start. Uses a snapshot_entry_id that references the original lorebook_entries.id (not a FK -- the original entry may be deleted during the session).
CREATE TABLE lorebook_session_snapshot_entries (
id SERIAL PRIMARY KEY,
snapshot_id INTEGER NOT NULL REFERENCES lorebook_session_snapshots(id) ON DELETE CASCADE,
-- Reference to the original entry (NOT a FK -- entry may be deleted)
original_entry_id INTEGER NOT NULL,
-- Snapshotted metadata (from lorebook_entries)
name VARCHAR(60) NOT NULL,
keywords_json TEXT NOT NULL DEFAULT '[]',
category VARCHAR(100) NOT NULL DEFAULT '',
color VARCHAR(7) NOT NULL DEFAULT '',
priority INTEGER NOT NULL DEFAULT 0,
is_enabled BOOLEAN NOT NULL DEFAULT TRUE,
trigger_probability INTEGER NOT NULL DEFAULT 100,
always_include BOOLEAN NOT NULL DEFAULT FALSE,
token_count_approx INTEGER NOT NULL DEFAULT 0,
-- Snapshotted content (from lorebook_entry_contents)
content TEXT NOT NULL DEFAULT ''
);
CREATE INDEX idx_lsse_snapshot ON lorebook_session_snapshot_entries(snapshot_id);
CREATE INDEX idx_lsse_original_entry ON lorebook_session_snapshot_entries(snapshot_id, original_entry_id);
Why relational instead of JSONB:
- Large lorebooks (200+ entries, ~500 tokens each) would produce multi-MB JSONB blobs. Relational rows are cheaper to store, index, and query.
fn_get_lorebook_session_diffcan JOIN snapshot entries against live entries directly in SQL, producing per-entry diffs without parsing JSONB in application code.- Individual entry snapshots are addressable: the diff view can link directly to the snapshot row for before/after comparison.
- Consistent with the project's "logic lives in PostgreSQL" pattern -- the database does the diff, not the application.
Keyword Filters on lorebook_entries (Added in Implementation)
The following columns were added to lorebook_entries to support include/exclude keyword filters and trigger regex:
ALTER TABLE lorebook_entries ADD COLUMN include_keywords_json TEXT NOT NULL DEFAULT '[]';
ALTER TABLE lorebook_entries ADD COLUMN exclude_keywords_json TEXT NOT NULL DEFAULT '[]';
ALTER TABLE lorebook_entries ADD COLUMN trigger_regex TEXT; -- nullable, POSIX regex pattern
The lorebook_entry_keywords normalized table was updated with a keyword_type column:
0= trigger keyword (OR logic)1= include keyword (AND logic)2= exclude keyword (NOT logic, global veto)
A helper function fn_safe_regex_match(text, pattern) was added for safe POSIX regex evaluation (returns FALSE on invalid patterns).
See Lorebooks — Keyword Types for user-facing documentation.
Optimistic Locking on lorebook_entries
Add a version counter to the existing lorebook_entries table:
ALTER TABLE lorebook_entries ADD COLUMN version INTEGER NOT NULL DEFAULT 1;
-- Increment on every update (handled in fn_upsert_lorebook_entry)
When a proposal is created for an existing entry, it captures the current version. On apply, if entry.version != proposal.entry_version, the proposal is rejected with a conflict error ("entry was modified outside this session"). The UI shows which fields changed so the user can re-propose.
Stored Procedures
-- Create session + snapshot atomically.
-- Inserts into lorebook_assistant_sessions, lorebook_session_snapshots,
-- and lorebook_session_snapshot_entries (one row per existing entry,
-- JOINing lorebook_entries + lorebook_entry_contents with lorebook_id
-- for partition pruning).
fn_create_lorebook_assistant_session(
p_lorebook_id, p_user_id, p_preset_id, p_auto_approve
) RETURNS (session_id, snapshot_id)
-- Apply an approved proposal (create/update/disable the actual entry)
-- Checks entry_version for optimistic lock; returns conflict error on mismatch
-- IMPORTANT: Lorebook entries use a split table pattern:
-- - lorebook_entries: metadata (name, priority, is_enabled, etc.)
-- - lorebook_entry_contents: content text + keywords (FK: lorebook_entry_content_id)
-- (partitioned by lorebook_id -- always include lorebook_id in queries)
-- The apply procedure must handle both tables:
-- - Creates: INSERT into lorebook_entry_contents (with lorebook_id), then INSERT into lorebook_entries
-- - Updates: UPDATE the relevant table(s) based on which fields changed
-- (content changes → lorebook_entry_contents; metadata changes → lorebook_entries)
-- - Disables: SET lorebook_entries.is_enabled = FALSE
-- NOTE: INSERT/UPDATE on lorebook_entries.keywords_json auto-triggers
-- fn_sync_lorebook_entry_keywords, which syncs the normalized
-- lorebook_entry_keywords table. No manual keyword sync needed.
fn_apply_lorebook_proposal(
p_proposal_id, p_user_id
) RETURNS (entry_id, operation_applied, conflict, conflict_message)
-- Batch approve proposals
fn_batch_apply_lorebook_proposals(
p_proposal_ids INT[], p_user_id
) RETURNS TABLE(proposal_id, entry_id, operation_applied, success, error_message)
-- Get session diff (compare snapshot entries to current state).
-- JOINs lorebook_session_snapshot_entries against live lorebook_entries +
-- lorebook_entry_contents (with lorebook_id for partition pruning).
-- Detects added/modified/deleted entries by comparing snapshot rows to live rows.
fn_get_lorebook_session_diff(
p_session_id
) RETURNS TABLE(entry_id, entry_name, change_type, original_data, current_data)
Views
-- Session list with stats
CREATE VIEW vw_lorebook_assistant_sessions AS
SELECT
s.*,
l.name AS lorebook_name,
(SELECT COUNT(*) FROM lorebook_entry_proposals WHERE session_id = s.id AND status = 0) AS pending_count,
(SELECT MAX(created_at) FROM lorebook_assistant_messages WHERE session_id = s.id) AS last_message_at
FROM lorebook_assistant_sessions s
JOIN lorebooks l ON l.id = s.lorebook_id;
Tool Design
Tools are C# methods in a LorebookToolPlugin class, decorated with Semantic Kernel's [KernelFunction] attribute. SK auto-generates the JSON tool schema from the method signature, description, and parameter attributes.
Tool Inventory
Read Tools
All read tools accept an optional lorebookId parameter. When omitted, they operate on the session's lorebook (_lorebookId). When provided, they can read from other lorebooks the user has access to -- enabling cross-referencing for inspiration, consistency checks, or comparing entries across worlds. Permission is validated on every call via IEntityPermissionRepository: the user must own the target lorebook or have at least can_view permission on it. Attempting to read a lorebook without access returns a ToolError with "permission_denied".
public class LorebookToolPlugin
{
/// <summary>
/// Get lorebook metadata (name, description, entry count, search settings).
/// Call this first to understand the lorebook you're editing.
/// Defaults to the session's lorebook. Pass a different lorebookId to inspect
/// another lorebook you have access to (for cross-referencing).
/// </summary>
[KernelFunction("get_lorebook_info")]
[Description("Get lorebook metadata including name, description, entry count, and search settings. Defaults to the current lorebook; pass a different lorebookId to inspect another you have access to.")]
public async Task<LorebookInfoResult> GetLorebookInfoAsync(
[Description("Lorebook ID to inspect (omit for current session's lorebook)")] int? lorebookId = null)
/// <summary>
/// Search entries by text query using direct lorebook-scoped search
/// (vector + FTS + keyword matching against the lorebook's partition).
/// Returns matching entries with scores and match source.
/// </summary>
[KernelFunction("search_entries")]
[Description("Search lorebook entries by text. Returns entries ranked by relevance with match source (FTS vs keyword). Defaults to the current lorebook; pass a different lorebookId to search another you have access to.")]
public async Task<SearchEntriesResult> SearchEntriesAsync(
[Description("Search query text")] string query,
[Description("Max entries to return (default 10)")] int limit = 10,
[Description("Lorebook ID to search (omit for current session's lorebook)")] int? lorebookId = null)
/// <summary>
/// Get a single entry by ID with full content, including keyword cross-references.
/// Can read entries from other lorebooks the user has access to.
/// </summary>
[KernelFunction("get_entry")]
[Description("Get a lorebook entry by ID with full content, keywords (trigger, include, exclude), trigger regex, metadata, and keyword cross-references. Pass lorebookId if reading from a different lorebook.")]
public async Task<EntryDetailResult> GetEntryAsync(
[Description("Entry ID")] int entryId,
[Description("Lorebook ID the entry belongs to (omit for current session's lorebook)")] int? lorebookId = null)
/// <summary>
/// Get multiple entries by IDs in a single call (up to 20).
/// Efficient for examining flagged entries from analysis results.
/// </summary>
[KernelFunction("get_entries_by_ids")]
[Description("Get full details of multiple entries by their IDs (up to 20). Efficient for batch examination.")]
public async Task<BatchEntryResult> GetEntriesByIdsAsync(
[Description("Entry IDs to fetch")] int[] entryIds)
/// <summary>
/// List all entries with brief info (no full content).
/// Use for getting an overview before targeted reads.
/// </summary>
[KernelFunction("list_entries")]
[Description("List lorebook entries with name, keywords, category, and token count. No full content. Supports filtering by category, always-include, and priority range.")]
public async Task<ListEntriesResult> ListEntriesAsync(
[Description("Filter by category (optional)")] string? category = null,
[Description("Filter by always-include flag (optional)")] bool? alwaysInclude = null,
[Description("Minimum priority filter (optional)")] int? minPriority = null,
[Description("Maximum priority filter (optional)")] int? maxPriority = null,
[Description("Offset for pagination (default 0)")] int offset = 0,
[Description("Limit for pagination (default 50, max 100)")] int limit = 50)
/// <summary>
/// Get all entries in a category with full content (up to 30).
/// </summary>
[KernelFunction("get_entries_by_category")]
[Description("Get all entries in a category with full content (up to 30). Use for bulk review of a category.")]
public async Task<CategoryEntriesResult> GetEntriesByCategoryAsync(
[Description("Category name")] string category)
/// <summary>
/// List all categories in use across entries with entry counts and token totals.
/// </summary>
[KernelFunction("list_categories")]
[Description("List all categories used by entries with entry count and total tokens per category.")]
public async Task<ListCategoriesResult> ListCategoriesAsync()
/// <summary>
/// Comprehensive quality analysis of the lorebook.
/// Flags oversized entries, stubs, unreachable entries, keyword-content mismatches,
/// missing embeddings, overused keywords, and high-influence entries.
/// </summary>
[KernelFunction("analyze_lorebook")]
[Description("Run comprehensive quality analysis. Reports issues like oversized entries, unreachable entries, keyword-content mismatches, missing embeddings, and overused keywords.")]
public async Task<AnalysisResult> AnalyzeLorebookAsync()
/// <summary>
/// List all proposals in the current session with their statuses.
/// Useful for understanding user feedback on rejected proposals.
/// </summary>
[KernelFunction("list_proposals")]
[Description("List all proposals in this session with statuses and rejection feedback. Use to learn from user feedback.")]
public async Task<ProposalListResult> ListProposalsAsync()
Write Tools (Proposal-Based)
Write tools don't modify the lorebook directly. They create proposals that are returned to the user for review. If auto-approve is on, proposals are applied immediately.
/// <summary>
/// Propose creating a new lorebook entry. This does NOT create the entry directly --
/// it creates a proposal that the user must approve before it takes effect.
/// </summary>
[KernelFunction("propose_create_entry")]
[Description("Propose a new lorebook entry. This only creates a proposal — the entry is NOT created until the user approves it.")]
public async Task<ProposalResult> ProposeCreateEntryAsync(
[Description("Entry name (max 60 chars)")] string name,
[Description("Entry content text")] string content,
[Description("Trigger keywords (OR logic)")] string[] keywords,
[Description("Category for organization (optional)")] string? category = null,
[Description("Priority, higher = injected first (default 50)")] int priority = 50,
[Description("Whether to always include regardless of search (default false)")] bool alwaysInclude = false,
[Description("Trigger probability 0-100 (default 100)")] int triggerProbability = 100,
[Description("Entry color as hex, e.g. '#ff0000' (optional)")] string? color = null,
[Description("Include keywords - AND logic, all must match (optional)")] string[]? includeKeywords = null,
[Description("Exclude keywords - NOT logic, vetoes entry if any match (optional)")] string[]? excludeKeywords = null,
[Description("POSIX regex pattern for triggering (optional)")] string? triggerRegex = null)
/// <summary>
/// Propose editing an existing entry. Only include fields you want to change --
/// omitted fields remain unchanged. This does NOT apply the edit directly;
/// it creates a proposal that the user must approve.
/// </summary>
[KernelFunction("propose_update_entry")]
[Description("Propose changes to an existing entry. Only specify fields to change; omitted fields stay unchanged. This only creates a proposal — the edit is NOT applied until the user approves it.")]
public async Task<ProposalResult> ProposeUpdateEntryAsync(
[Description("Entry ID to edit")] int entryId,
[Description("New name (optional)")] string? name = null,
[Description("New content (optional)")] string? content = null,
[Description("New trigger keywords (optional)")] string[]? keywords = null,
[Description("New category (optional)")] string? category = null,
[Description("New priority (optional)")] int? priority = null,
[Description("New always-include flag (optional)")] bool? alwaysInclude = null,
[Description("New trigger probability (optional)")] int? triggerProbability = null,
[Description("New color as hex (optional)")] string? color = null,
[Description("New include keywords (optional)")] string[]? includeKeywords = null,
[Description("New exclude keywords (optional)")] string[]? excludeKeywords = null,
[Description("New trigger regex (optional)")] string? triggerRegex = null)
/// <summary>
/// Propose disabling an entry (sets is_enabled=false). The entry is preserved
/// but excluded from search. This does NOT remove the entry directly;
/// it creates a proposal that the user must approve. Prefer this over
/// permanent deletion -- disabled entries can be re-enabled later.
/// </summary>
[KernelFunction("propose_disable_entry")]
[Description("Propose disabling a lorebook entry (excluded from search but preserved). This only creates a proposal — the entry is NOT disabled until the user approves it. Prefer over deletion.")]
public async Task<ProposalResult> ProposeDisableEntryAsync(
[Description("Entry ID to disable")] int entryId,
[Description("Reason for disabling")] string reason)
}
Tool Result Types
// Proposal result returned to the LLM after a write tool call
public record ProposalResult(
int ProposalId,
string Operation, // "create", "update", "disable"
string Status, // "pending", "auto_approved"
string Summary // Human-readable summary of what was proposed
);
// Entry detail result (updated with keyword types and cross-references)
public record EntryDetailResult(
int Id,
string Name,
string Content,
string[] Keywords,
string[]? IncludeKeywords,
string[]? ExcludeKeywords,
string? TriggerRegex,
string? Category,
string? Color,
int Priority,
bool AlwaysInclude,
int TriggerProbability,
int TokenCountApprox,
bool HasEmbedding,
KeywordCrossRef[]? KeywordCrossRefs // Other entries sharing keywords
);
// List result (with total for pagination)
public record ListEntriesResult(
int TotalCount,
int Page,
int PageSize,
ListEntryItem[] Entries
);
// Token estimate result
public record TokenEstimateResult(
int EstimatedTokens,
string Recommendation // "Good size", "Consider splitting (~500 token target)", etc.
);
// Search result (updated with match source)
public record SearchEntriesResult(
int TotalMatches,
SearchEntryItem[] Entries
);
public record SearchEntryItem(
int Id,
string Name,
string ContentPreview, // First 200 chars
string[] Keywords,
string? Category,
double Score,
string MatchSource // "FTS", "keyword", "vector", etc.
);
Tool Execution Context
Each tool plugin instance is scoped to a session and carries the session context:
public class LorebookToolPlugin
{
private readonly int _lorebookId;
private readonly int _sessionId;
private readonly int _userId;
private readonly bool _autoApprove;
private readonly ILorebookRepository _lorebookRepository;
private readonly ILorebookSearchRepository _searchRepository;
private readonly ILorebookProposalRepository _proposalRepository;
private readonly IEntityPermissionRepository _permissionRepository;
// Constructor receives session-scoped context
public LorebookToolPlugin(
int lorebookId,
int sessionId,
int userId,
bool autoApprove,
ILorebookRepository lorebookRepository,
ILorebookSearchRepository searchRepository,
ILorebookProposalRepository proposalRepository,
IEntityPermissionRepository permissionRepository)
{
_lorebookId = lorebookId;
_sessionId = sessionId;
_userId = userId;
_autoApprove = autoApprove;
// ...
}
/// <summary>
/// Resolve the effective lorebook ID. If the caller passed a lorebookId, validate
/// permission (owner or can_view) and return it. Otherwise return _lorebookId.
/// Throws ToolError("permission_denied") if the user lacks access.
/// </summary>
private async Task<int> ResolveLorebookIdAsync(int? lorebookId) { /* ... */ }
}
This is one case where a factory creating per-session instances is justified -- the plugin carries session-scoped state that genuinely varies per request (lorebookId, sessionId, autoApprove flag). See CLAUDE.md: "Sometimes you DO need factories that create instances."
Search Infrastructure: Direct Lorebook-Scoped Search
The existing ILorebookSearchRepository methods (SearchForConversationAsync, SearchForDiscordChannelAsync) resolve lorebook IDs from character/persona bindings and are designed for conversation context. The assistant needs a direct lorebook-scoped search that takes a lorebookId explicitly.
A new method is needed on ILorebookSearchRepository:
/// <summary>
/// Search entries within a single lorebook by ID. Runs the same hybrid search
/// (vector + FTS + simple keyword) but directly against the specified lorebook's
/// partition, bypassing conversation/character binding resolution.
/// </summary>
Task<IReadOnlyList<LorebookSearchResult>> SearchByLorebookIdAsync(
int lorebookId,
string query,
float[]? embedding,
SearchOptions? options = null,
CancellationToken ct = default);
This queries the lorebook_entry_contents_lb_{lorebookId} partition directly, leveraging the per-partition HNSW and GIN indexes. The lorebookId in the query ensures partition pruning. The search options (SearchOptions) are the same as existing search -- vector threshold, FTS threshold, keyword matching, topK.
Service Layer
LorebookAssistantService
Orchestrates the LLM tool-calling loop.
public class LorebookAssistantService
{
private readonly IKernelFactory _kernelFactory;
private readonly ILorebookAssistantSessionRepository _sessionRepository;
private readonly ILorebookAssistantMessageRepository _messageRepository;
private readonly ILorebookProposalRepository _proposalRepository;
private readonly ILorebookToolPluginFactory _pluginFactory;
private readonly ILoggerFactory _loggerFactory;
/// <summary>
/// Process a user message: store it, run the SK tool loop,
/// stream assistant responses, store all messages and proposals.
/// </summary>
public async IAsyncEnumerable<AssistantEvent> ProcessMessageAsync(
int sessionId,
string userMessage,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
// 1. Load session + history
// 2. Store user message
// 3. Build Kernel with plugin for this session
// 4. Run SK tool-calling loop (auto-invoke tools)
// 5. For each tool call:
// - Yield tool_call event (so client can show "Searching entries...")
// - Execute tool
// - Yield tool_result event (so client can show result)
// - If proposal created: yield proposal event
// 6. Stream final assistant text response
// 7. Store assistant message
}
}
IKernelFactory
Creates a Semantic Kernel Kernel wired to the user's LLM preset.
public interface IKernelFactory
{
/// <summary>
/// Build a Kernel using the specified preset (or session default).
/// Resolves provider, API key, model, and generation settings.
/// </summary>
Task<Kernel> CreateAsync(int userId, int? presetId, CancellationToken ct = default);
}
The factory reads the user's LLM preset via ILlmPresetRepository, resolves provider/key/model, and configures the appropriate SK connector:
public class KernelFactory : IKernelFactory
{
public async Task<Kernel> CreateAsync(int userId, int? presetId, CancellationToken ct)
{
var preset = await _presetRepository.GetByIdAsync(presetId ?? defaultPresetId);
var builder = Kernel.CreateBuilder();
switch (ParseProvider(preset.Provider))
{
case LlmProvider.OpenAI:
builder.AddOpenAIChatCompletion(preset.Model, preset.ApiKey);
break;
case LlmProvider.Anthropic:
builder.AddAnthropicChatCompletion(preset.Model, preset.ApiKey);
break;
case LlmProvider.Gemini:
builder.AddGoogleAIGeminiChatCompletion(preset.Model, preset.ApiKey);
break;
case LlmProvider.Custom:
case LlmProvider.OpenRouter:
builder.AddOpenAIChatCompletion(
preset.Model, preset.ApiKey,
endpoint: new Uri(preset.Endpoint));
break;
}
return builder.Build();
}
}
SSE Event Types
The streaming endpoint emits these event types:
// Events sent via SSE
type AssistantEvent =
| { type: "message_start" }
| { type: "text_delta"; content: string }
| { type: "message_end" }
| { type: "tool_call"; name: string; arguments: Record<string, unknown> }
| { type: "tool_result"; name: string; result: unknown }
| { type: "proposal"; proposal: Proposal }
| { type: "proposals_complete"; count: number }
| { type: "error"; message: string }
System Prompt
The assistant receives a system prompt that establishes its role and guides its behavior. The prompt is constructed per-session and includes lorebook-specific context.
You are a lorebook editor assistant. You help users create, edit, and organize
lorebook entries for their worldbuilding projects.
## Current Lorebook
- Name: {lorebook.Name}
- Description: {lorebook.Description}
- Entry Count: {entryCount}
- Search Settings: Vector={enableVector}, Keyword={enableKeyword}, TopK={topK}
## Your Tools
You have tools to read and modify lorebook entries. Write operations create
PROPOSALS that the user reviews before they take effect.
## Guidelines
### Entry Quality
- Keep entries under ~500 tokens. Split large topics into focused entries.
- Write content as if explaining to someone with no prior context.
- Choose 2-5 distinctive keywords per entry. Avoid generic words.
- Set meaningful priorities: 100=critical lore, 50=normal, 10=flavor.
### Workflow
- When the user shares notes or text, extract distinct topics into separate entries.
- When editing, read the existing entry first before proposing changes.
- For bulk operations, explain your plan before executing.
- Group related proposals together in one response.
### Interaction Style
- Be direct and efficient. This is a tool, not a creative writing partner.
- When proposing entries, briefly state what each entry covers and why.
- If content is ambiguous, ask before guessing.
{additionalInstructions}
The {additionalInstructions} block allows per-session customization (e.g., "Focus on D&D 5e lore conventions" or "Use Japanese naming conventions").
Approval Workflow
Standard Flow (auto_approve = false)
User: "Add entries for the three main factions in my world"
│
▼
LLM calls search_entries("factions") to check existing
│
▼
LLM calls propose_create_entry("The Iron Covenant", ...) → Proposal #1 (pending)
LLM calls propose_create_entry("Verdant Circle", ...) → Proposal #2 (pending)
LLM calls propose_create_entry("Shadow Syndicate", ...) → Proposal #3 (pending)
│
▼
LLM responds: "I've proposed 3 faction entries. Review them in the panel."
│
▼
Client shows 3 proposals with diff view:
[✓ Approve] [✗ Reject] [↻ Redo] per proposal
[✓ Approve All] [✗ Reject All] for batch
│
▼
User approves #1 and #3, rejects #2 with note: "Make Verdant Circle more druidic"
│
▼
#1 and #3 applied → actual lorebook entries created
#2 rejection + note sent back to LLM as context
│
▼
LLM proposes revised #2 → new Proposal #4 (pending)
Auto-Approve Flow
When auto_approve = true, proposals are applied immediately after creation. The tool returns status: "auto_approved" instead of "pending". The user still sees what was applied in the chat timeline and can undo via the session diff view.
Redo Flow
When a user rejects a proposal with a note, the rejection and note are added to the chat history as a system message:
[System] User rejected proposal #2 (create "Verdant Circle").
User feedback: "Make Verdant Circle more druidic, focused on nature magic and ancient forests."
The LLM sees this in its history and can propose a revised version.
Session Versioning & Diff
Snapshot on Session Start
When a session is created, fn_create_lorebook_assistant_session atomically snapshots all current entries into lorebook_session_snapshot_entries (one row per entry). The procedure JOINs lorebook_entries with lorebook_entry_contents (including lorebook_id for partition pruning) and inserts each entry's metadata + content as a snapshot row:
-- Inside fn_create_lorebook_assistant_session (simplified):
INSERT INTO lorebook_session_snapshot_entries (
snapshot_id, original_entry_id,
name, keywords_json, category, color, priority,
is_enabled, trigger_probability, always_include,
token_count_approx, content
)
SELECT
v_snapshot_id, le.id,
le.name, le.keywords_json, le.category, le.color, le.priority,
le.is_enabled, le.trigger_probability, le.always_include,
le.token_count_approx, lec.content
FROM lorebook_entries le
JOIN lorebook_entry_contents lec
ON le.lorebook_entry_content_id = lec.id
AND lec.lorebook_id = le.lorebook_id -- partition pruning
WHERE le.lorebook_id = p_lorebook_id
AND le.is_enabled = TRUE;
Diff Computation
The diff endpoint (GET /sessions/{id}/diff) compares the snapshot entries to the current lorebook state using a FULL OUTER JOIN in fn_get_lorebook_session_diff:
-- fn_get_lorebook_session_diff (simplified logic):
-- FULL OUTER JOIN snapshot entries against live entries by original_entry_id.
-- Detects: added (live exists, snapshot doesn't), modified (both exist, fields differ),
-- deleted (snapshot exists, live doesn't or is_enabled=false).
SELECT
COALESCE(le.id, sse.original_entry_id) AS entry_id,
COALESCE(le.name, sse.name) AS entry_name,
CASE
WHEN sse.id IS NULL THEN 'added'
WHEN le.id IS NULL OR le.is_enabled = FALSE THEN 'deleted'
WHEN le.name != sse.name OR lec.content != sse.content
OR le.keywords_json != sse.keywords_json
OR le.priority != sse.priority
OR le.category != sse.category THEN 'modified'
END AS change_type,
-- original_data from snapshot row, current_data from live row (as JSONB)
FROM lorebook_session_snapshot_entries sse
FULL OUTER JOIN lorebook_entries le
ON le.id = sse.original_entry_id AND le.lorebook_id = snap.lorebook_id
LEFT JOIN lorebook_entry_contents lec
ON le.lorebook_entry_content_id = lec.id
AND lec.lorebook_id = le.lorebook_id -- partition pruning
WHERE snap.session_id = p_session_id;
Change types:
- Added: Entry exists in live lorebook but not in snapshot (created during session)
- Modified: Entry exists in both but fields differ (name, content, keywords, priority, category, etc.)
- Deleted: Entry in snapshot but missing from live lorebook or
is_enabled = FALSE
Diff UI
The session diff panel shows a summary of all changes made during the session:
Session: "Faction worldbuilding" — 3 changes
+ Added: "The Iron Covenant" (Factions)
Content: "A militaristic order of paladins and war-clerics..."
Keywords: iron covenant, paladins, military order
~ Modified: "World Overview" (General)
Content: Added mention of three factions...
- "The world of Aethermoor is divided by ancient rivalries."
+ "The world of Aethermoor is divided by three great factions: the Iron Covenant,
the Verdant Circle, and the Shadow Syndicate."
- Deleted: "Old Faction Notes" (Uncategorized)
Was: "TODO: flesh out the faction system"
The diff is computed per-field so users can see exactly what changed in each entry's content, keywords, priority, etc.
API Endpoints
All endpoints under /api/creator/lorebooks/{lorebookId}/assistant/.
Session Management
POST /sessions
Body: { autoApprove?: boolean, presetId?: int, title?: string }
Creates a new editing session + snapshot.
Returns: { sessionId, createdAt }
GET /sessions
List active and recent sessions for this lorebook.
Returns: [{ id, title, status, proposalStats, lastMessageAt, createdAt }]
GET /sessions/{sessionId}
Get session details + message history.
Returns: { session, messages[], pendingProposals[] }
PUT /sessions/{sessionId}
Update session settings (autoApprove, title).
DELETE /sessions/{sessionId}
Abandon session (status=abandoned). Does not undo applied proposals.
To undo, use the diff view and manual revert.
Chat
POST /sessions/{sessionId}/chat
Body: { message: string }
SSE stream. Sends user message, runs LLM tool loop, streams response.
Events: message_start, text_delta, tool_call, tool_result, proposal,
proposals_complete, message_end, error
Proposal Review
GET /sessions/{sessionId}/proposals
List proposals for this session, filterable by status.
Query: ?status=pending|approved|rejected
Returns: [{ id, operation, entryId, proposedData, originalData, status }]
POST /sessions/{sessionId}/proposals/{proposalId}/approve
Approve and apply a single proposal.
Returns: { entryId, operation }
POST /sessions/{sessionId}/proposals/{proposalId}/reject
Body: { feedback?: string }
Reject a proposal. Optional feedback is injected into chat history.
Returns: { }
POST /sessions/{sessionId}/proposals/batch
Body: { approve: int[], reject: int[], rejectFeedback?: string }
Batch approve/reject. Feedback applies to all rejected proposals.
Returns: { approved: int, rejected: int, errors: [] }
Diff
GET /sessions/{sessionId}/diff
Compare snapshot to current lorebook state.
Returns: { snapshotEntryCount, currentEntryCount, changes[] }
Each change: { entryId, entryName, changeType, originalData, currentData }
Frontend Design
Page Layout
The lorebook assistant lives at /creator/lorebooks/{id}/assistant (or as a tab within the existing lorebook form page). Three-panel layout:
┌─────────────────────────────────────────────────────────────────┐
│ ◀ Back to Lorebook Session: "Faction worldbuilding" │
│ [Auto-approve: OFF] [Preset: ▼] │
├──────────────────────────┬──────────────────────────────────────┤
│ │ │
│ Chat Panel │ Side Panel (tabs) │
│ │ │
│ ┌──────────────────┐ │ [Proposals] [Diff] [Entries] │
│ │ System: Session │ │ │
│ │ started... │ │ ┌──────────────────────────────┐ │
│ ├──────────────────┤ │ │ Proposal #1: Create │ │
│ │ You: Add entries │ │ │ "The Iron Covenant" │ │
│ │ for the three │ │ │ │ │
│ │ main factions │ │ │ + Name: The Iron Covenant │ │
│ ├──────────────────┤ │ │ + Keywords: iron covenant... │ │
│ │ 🔧 search_entries │ │ │ + Content: A militaristic... │ │
│ │ "factions" │ │ │ + Priority: 80 │ │
│ ├──────────────────┤ │ │ │ │
│ │ Assistant: I've │ │ │ [✓ Approve] [✗ Reject] [↻] │ │
│ │ proposed 3 new │ │ └──────────────────────────────┘ │
│ │ entries for... │ │ │
│ └──────────────────┘ │ ┌──────────────────────────────┐ │
│ │ │ Proposal #2: Create │ │
│ ┌──────────────────┐ │ │ "Verdant Circle" │ │
│ │ Type a message... │ │ │ ... │ │
│ │ [Send] │ │ └──────────────────────────────┘ │
│ └──────────────────┘ │ │
│ │ [✓ Approve All] [✗ Reject All] │
├──────────────────────────┴──────────────────────────────────────┤
│ 3 pending proposals │ 12 entries total │ Session: 5 min ago │
└─────────────────────────────────────────────────────────────────┘
Chat Panel
- Standard chat message list with user/assistant bubbles
- Tool call indicators shown inline (collapsible):
🔧 search_entries("factions") → 2 results 🔧 get_entry(42) → "Ancient Dragon" (487 tokens) 🔧 propose_create_entry("The Iron Covenant", ...) → Proposal #1 (pending) - Streaming assistant text with typing indicator
- Message input with send button (Enter to send, Shift+Enter for newline)
Proposal Review Panel
Each proposal card shows:
- Operation badge:
+ Create,~ Edit,⊘ Disable - Entry name (existing name for edits/deletes, proposed name for creates)
- Diff view for edits: side-by-side or inline diff of changed fields
- Full content preview for creates
- Action buttons: Approve, Reject (with optional feedback textarea), Redo
- Batch actions at the bottom: Approve All, Reject All
Diff Panel
Shows the cumulative changes from this session:
- Summary counts: N added, N modified, N deleted
- Per-entry change cards with field-level diffs
- Content diffs rendered with add/remove highlighting (green/red)
Entries Panel
Quick-reference view of all entries in the lorebook. Identical to the existing entries table in the lorebook form but read-only. Allows the user to browse existing content while chatting.
State Management
A Zustand store for the assistant session:
interface LorebookAssistantStore {
// Session
sessionId: number | null
autoApprove: boolean
presetId: number | null
// Chat
messages: AssistantMessage[]
isStreaming: boolean
streamingContent: string
// Proposals
pendingProposals: Proposal[]
reviewedProposals: Proposal[]
// Diff
sessionDiff: DiffEntry[] | null
// Actions
sendMessage(content: string): Promise<void>
approveProposal(id: number): Promise<void>
rejectProposal(id: number, feedback?: string): Promise<void>
batchApprove(ids: number[]): Promise<void>
batchReject(ids: number[], feedback?: string): Promise<void>
loadDiff(): Promise<void>
setAutoApprove(enabled: boolean): Promise<void>
}
LLM Preset Integration
The assistant uses the existing LLM preset system. Users can:
- Use their default preset -- the session inherits the user's configured LLM preset
- Override per session -- select a different preset when creating the session
- Change mid-session -- update the preset via
PUT /sessions/{id}
The preset determines provider, API key, model, and generation settings. This reuses the existing llm_presets table and LlmPresetEnricher service.
Tool-calling model requirements:
- The selected model must support function calling (most modern models do)
- If a model doesn't support tools, the endpoint returns an error on session creation
- Recommended models: Claude 3.5+, GPT-4+, Gemini 1.5+
Import/Export Integration
The existing lorebook import/export system (ExportEnvelope<LorebookExportData>) works alongside the assistant:
- Import then assist: User imports a lorebook JSON, then opens the assistant to refine entries
- Assist then export: User builds entries via assistant, then exports the final lorebook
- Import as context: Future enhancement -- user pastes/uploads a JSON file in the chat, and the LLM parses it into proposals using the import format
The assistant doesn't need to know about import/export directly. The existing /export and /import endpoints handle that independently.
Error Handling
LLM Failures
| Failure | Handling |
|---|---|
| LLM returns invalid tool call args | Return error event to client, log, continue session |
| LLM timeout / rate limit | Return error event with retry suggestion |
| Tool execution fails (DB error) | Return structured ToolError in tool result (see below); LLM sees the error and can adapt |
| Model doesn't support tools | Error on session creation, suggest compatible model |
Structured Tool Errors
When a tool fails, return a structured error as the tool result so the LLM can respond intelligently instead of hallucinating:
public record ToolError(
string Error, // "entry_not_found", "version_conflict", "db_error", "validation_error"
string Message // Human-readable: "Entry 42 no longer exists"
);
// Example: LLM calls get_entry(999) → tool returns:
// { "error": "entry_not_found", "message": "Entry 999 does not exist in this lorebook." }
// LLM can then say: "That entry doesn't exist. Did you mean entry 42 (Ancient Dragon)?"
Proposal Conflicts (Optimistic Locking)
Proposals carry the entry_version at time of creation. On approval, the stored procedure checks:
| Conflict | Handling |
|---|---|
entry.version != proposal.entry_version |
Reject with "entry was modified since this proposal was created". UI shows what changed. User can re-request from the LLM. |
| Entry was deleted/disabled since proposal | Reject with "entry no longer exists" message |
| Approve disable on already-disabled entry | No-op, mark as approved |
| Two proposals for the same entry, first approved | Second proposal's version check fails on apply. User sees conflict notification. |
Security & Authorization
- All endpoints require authentication (same as existing creator endpoints)
- User must own the lorebook (or have
can_editpermission via entity sharing) to create sessions - Entity sharing permissions: users with the
can_editflag on a shared lorebook can create assistant sessions. Read-only shared lorebooks (can_viewonly) allow browsing entries but not creating sessions or proposals. - Cross-lorebook reads: Read tools accept an optional
lorebookIdto inspect other lorebooks. Permission is checked viaIEntityPermissionRepositoryon every call -- the user must own the target lorebook or have at leastcan_viewpermission (entity_type=2). Attempts to read inaccessible lorebooks returnToolError("permission_denied"). Write tools always target the session's lorebook only. - Tool plugin validates lorebook ownership/permission on every operation
- API key for LLM comes from the user's preset (never from server-side keys for creator tools)
- Session messages may contain user content -- same data retention policy as chat messages
- Field validation in tool methods: entry names capped at 60 chars, keywords capped at 20 per entry, content size checked against a reasonable maximum (e.g., 10,000 chars). Invalid inputs return
ToolErrorwithvalidation_errortype.
Implementation Phases
Phase 1: Core Loop — Implemented
- Database schema (sessions, messages, proposals, snapshot + snapshot_entries,
versioncolumn on entries) SearchByLorebookIdAsyncmethod onILorebookSearchRepository(direct partition-scoped search)ISubscriptionLimitsServicestub (always permits; real implementation comes with Tiers & Limits feature)LorebookToolPluginwith read tools (get_lorebook_info,list_entries,get_entry,estimate_tokens) +propose_create_entry- Cross-lorebook read permission checks via
IEntityPermissionRepository LorebookAssistantServicewith SK tool-calling loop- SSE streaming endpoint
- Basic chat UI with message list and input
- Proposal list with approve/reject
- Structured tool error responses
- Per-message token usage display
Phase 2: Full Edit Suite — Implemented
propose_edit_entryandpropose_disable_entrytoolssearch_entrieswired to newSearchByLorebookIdAsyncmethod onILorebookSearchRepository- Batch approve/reject
- Optimistic locking enforcement on proposal apply
- Session diff computation and UI
- Rejection feedback → LLM redo flow
- Auto-approve mode
- Auto-reindex after batch approval (fire-and-forget)
Phase 3: Polish & Scale — Implemented
- Session history and resume
- Inline diff rendering for edits (field-level)
- Session list/management page
- Preset selector in assistant UI
- Quality analysis tools (
analyze_lorebook, keyword-content mismatch detection, embedding status) - Keyword cross-references and high-influence entry detection
- Include/exclude keyword filters and trigger regex support in tools
- Entries panel with pagination, search, and sorting
- Entry editor with tag-based keyword management
- Per-panel error boundaries
Phase 4: Living Lorebook Bridge — Planned
- Journal materialization uses the same proposal infrastructure
- Auto-generated proposals from journal profiles
- Periodic materialization (background job creates proposals for review)
- System sessions: Automated materialization creates proposals under a special "system" session type (distinct from user-initiated sessions). System sessions are visible in the session list with a "materialized" badge and can be reviewed/approved like normal sessions, but they aren't counted against the user's session limits.
- This phase connects to the Journal feature
Resolved Design Decisions
Message History Management
Long sessions will exceed context windows. Strategy: sliding window with anchored context.
On each turn, the chat history sent to the LLM is constructed as:
- System prompt (always present, ~300-500 tokens)
- Lorebook info summary (always injected at turn start via
get_lorebook_inforesult, ~100 tokens) - Last 3-5 pending proposals as context (so the LLM knows what's outstanding)
- Last N messages (sliding window, default 40-60 messages including tool calls/results)
SK's ChatHistory supports trimming via ChatHistoryTruncationReducer -- configure to keep the most recent messages within a token budget. Messages are still stored in the database for full session review; only the LLM's working context is truncated.
If the model's context is small (e.g., 8k), reduce the window. The estimate_tokens tool helps the LLM self-regulate entry sizes.
Concurrent Editing
Handled via optimistic locking (see Proposal Conflicts above).
- Each entry carries a
versioncounter, incremented on every write - Proposals capture the version at creation time
- On approval, version mismatch triggers a conflict error
- UI shows: "This entry was modified outside this session. [View changes] [Re-propose]"
No pessimistic locks, no session-level entry locking. Multiple sessions can coexist; conflicts are rare and resolved at apply-time.
Embedding Regeneration
Auto-trigger on batch approval (fire-and-forget background task).
When proposals are approved (individually or in batch), the apply function queues affected entry IDs for reindexing. The existing IEmbeddingClient batch processing (10 entries per batch) handles the actual embedding generation. This matches the existing reindex flow in CreatorLorebookEndpoints.
The diff panel also shows a "Reindex now" button for manual trigger if the background job hasn't completed.
Cost Visibility
Show per-message token usage in the chat (from SK's Usage metadata) and a session total in the status bar.
Status bar: 3 pending | 12 entries | 2,847 tokens used | Session: 5 min ago
Add a warning indicator when the session approaches ~70% of the model's context window, signaling the history will start being truncated.
Rate Limiting
Tied to subscription plan (see Tiers & Limits):
| Plan | Messages per session | Active sessions | Sessions per day |
|---|---|---|---|
| Free | 30 | 1 | 5 |
| Pro | 200 | 3 | Unlimited |
Note: These are subscription-based limits, not rights-based. A Creator on the Free plan has the same assistant limits as a Dreamer on the Free plan. Rights (Dreamer/Creator) control creation limits and publishing, not feature depth.
The LLM call is the expensive resource, not session storage. Rate limits prevent runaway tool loops and excessive API costs. Limits are enforced server-side in LorebookAssistantService via SubscriptionLimitsService before invoking the SK loop.
Note: SubscriptionLimitsService is a planned service (see Tiers & Limits) that does not exist yet. The existing CreationLimitsService handles entity creation quotas (characters, lorebooks, etc.) but not session/message rate limits. For Phase 1-2, implement a stub ISubscriptionLimitsService that always permits operations, with the interface defined to match the planned contract:
public interface ISubscriptionLimitsService
{
Task<bool> CanStartSessionAsync(int userId, CancellationToken ct = default);
Task<bool> CanSendMessageAsync(int userId, int sessionId, CancellationToken ct = default);
Task<LimitInfo> GetLimitsAsync(int userId, CancellationToken ct = default);
}
// Stub implementation (always permits) until Tiers & Limits feature lands
public class StubSubscriptionLimitsService : ISubscriptionLimitsService
{
public Task<bool> CanStartSessionAsync(int userId, CancellationToken ct) => Task.FromResult(true);
public Task<bool> CanSendMessageAsync(int userId, int sessionId, CancellationToken ct) => Task.FromResult(true);
public Task<LimitInfo> GetLimitsAsync(int userId, CancellationToken ct)
=> Task.FromResult(new LimitInfo(MessagesPerSession: int.MaxValue, ActiveSessions: int.MaxValue, SessionsPerDay: int.MaxValue));
}
This way the assistant code integrates with the limits interface from day one, and the real implementation slots in without changes to calling code.
Future Considerations
Batch proposal tool -- A
propose_batch_createtool that returns multiple proposal IDs in a single call, reducing round-trips when parsing large notes. Add in Phase 3 once the single-proposal flow is proven.Import as chat context -- Allow users to upload/paste a lorebook JSON in the chat. The LLM parses it into proposals using the existing import format. Bridges the import/export system with the assistant.
Proposal templates -- Pre-built tool chains for common operations ("split this entry into N entries", "add keywords to all entries in category X"). Could be implemented as canned prompts or as additional tools.