[GH-ISSUE #4768] [Feature]: Replace flat entity name injection with a stable, searchable mechanism — reduce noise and enable prompt caching #2627

Closed
opened 2026-10-21 05:51:43 +07:00 by bsakaguchi · 3 comments
Owner

Originally created by @xDanteMD on GitHub (Aug 8, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/4768

Originally assigned to: @kolacheee on GitHub.

What problem does this solve?

Professor Mari's conversation mode has two interconnected problems with the <available_names> block in her system message:

  1. Noise at scale: Every generation injects ALL entity names (characters, personas, lorebooks, chats, presets) as a flat, unfiltered list. For users with large collections, this becomes thousands of tokens of context noise that the model cannot meaningfully process.

  2. Cache invalidation: The name list is rebuilt from the DB on every generation (professor-mari-prompt-context.ts:30-73). Even when no entities change, DB query ordering differences and re-serialization produce a different string, invalidating provider-side prompt caching.

Both problems stem from the same design: a flat, dynamically-rebuilt name list injected into the system message on every generation.

Scale of the name list problem

Collection size Name list tokens (est.) % of 128K context
50 characters ~240 tokens 0.2%
200 characters ~960 tokens 0.7%
1,000 characters ~4,740 tokens 3.7%
1,000 chars + personas + lorebooks + chats + presets ~5,500+ tokens 4.3%+

These are comma-separated name lists wrapped in <available_names> XML blocks — no descriptions, no metadata, just names. The model receives them regardless of whether the user's current conversation involves any of these entities.

Cache impact

Provider Cache granularity Cost of invalidation
Anthropic Prompt prefix (min 1,024 tokens for Claude) Full re-prompt cost on cache miss
OpenAI Prompt prefix (automatic for repeated prefixes) Full re-prompt cost on cache miss
Google Context caching (explicit cache creation) N/A (manual caching)

For a user with 1,000 characters, the system message is ~13,740 tokens. On Anthropic, this means ~13,740 tokens are re-priced on every generation instead of cache-hitting at the reduced rate. Over a conversation with 50 generations, that's ~687,000 tokens of unnecessary full-price billing.

The system message changes between generations because:

  • DEFAULT_CONVERSATION_PROMPT and MARI_ASSISTANT_PROMPT are stable
  • <available_names> blocks are rebuilt from DB every generation (lines 30-73)
  • <loaded_context> changes when new data is fetched via [fetch:]
  • DB queries may return rows in different orders across calls
  • Any entity change (add, edit, delete) between generations changes the entire block

Why this is a problem

  1. The model already has a fetch mechanism. Mari's <data_access> instructions already tell her to use [fetch: type="character", name="Luna"] to retrieve full card data. The name list exists so Mari knows what's available to fetch — but a flat list of 1,000 names is not a useful lookup mechanism.

  2. No filtering or search. The model receives ALL names regardless of relevance. If the user asks about Luna, the model still sees 999 other character names it doesn't need.

  3. Compounding cost. The noise problem and the caching problem compound each other — large name lists are both wasteful to inject AND wasteful to rebuild.

Proposed solution

Option A: Replace with searchable tool (recommended)

Replace the flat <available_names> injection with a lightweight search tool that Mari can call when she needs to discover entities:

[list_characters: filter=""] → returns first 20 character names
[list_characters: filter="luna"] → returns matching characters
[search_characters: query="fortune teller"] → searches descriptions/tags
[list_lorebooks: filter=""] → returns lorebook names

This eliminates both problems: no names in the system message (no noise, no cache invalidation). The existing [fetch:] command and <data_access> instructions provide the retrieval mechanism; this adds discovery.

What already exists and can be reused:

  • The [fetch:] command already retrieves full entity data by name
  • The <data_access> instruction block already teaches Mari the fetch pattern
  • The workspace assistant's app_data tool schema covers CRUD operations
  • The DB query infrastructure (chars.list(), lorebooksStore.list(), etc.) already exists

What would need to be added:

  • A [list_characters] / [search_characters] command handler in character-commands.ts
  • A reduced default name list (e.g., first 20 characters, or recently used) instead of all entities
  • Instructions in MARI_ASSISTANT_PROMPT teaching Mari to use the search tool

Option B: Cap + cache (minimal change)

Keep the <available_names> blocks but:

  1. Cap at 50 names per category with a note: "and 950 more — use [list_characters: filter='...'] to search"
  2. Cache the serialized string in memory; invalidate on entity CRUD
  3. Sort alphabetically before joining for deterministic serialization

This reduces noise from ~4,740 tokens to ~240 tokens and ensures cache hits when no entities change. Lower blast radius than Option A.

Option C: Stable prefix isolation

Move <available_names> and <loaded_context> to separate messages at stable positions. This isolates changing content from stable content (MARI_ASSISTANT_PROMPT, ~9,000 tokens), allowing the provider to cache the stable prefix. The changing blocks would still miss cache, but the stable prefix (~9K tokens) would cache consistently.

Recommended: Option A + B combined. Replace the flat list with a searchable tool for new users, with a capped fallback for backward compatibility. Cache the reduced list deterministically.

Alternatives considered

  • Keep injecting all names — works for small collections (<100 entities) but doesn't scale. A user with 1,000 characters sends ~4,740 tokens of noise every generation.
  • Inject only recently used entities — reduces noise but loses discoverability. Mari wouldn't know about characters the user hasn't chatted with recently.
  • Inject names in a separate system message — doesn't reduce token usage, just reorganizes the prompt. The core problem (flat list of 1,000 names) remains. (See Option C for a variant that does help with caching.)
  • Truncate the name list — hides the problem without solving it. Mari would silently lose access to entities beyond the truncation point.
  • Accept the cache miss — works for small collections but wastes money at scale. The cost compounds with every generation.
  • #4240 (Pre-processing agent context omitted from first generation): User reported that "Memory Recall or Secret Plot get injected right in the middle, right before the chat history. Since these are dynamic blocks, the cache breaks immediately after the system instructions." Same class of problem — dynamic blocks in the system message invalidating prompt caching.
  • Confirms that dynamic prompt content directly breaks provider-side caching.
  • #2302 (Full prompt assembly runs twice every turn): assembleGenerationPrompt invoked twice per turn, redoing all expensive work including storage reads and DB queries. The name list rebuild is one instance of this broader redundancy problem.
  • #2778 (Helper Functions for Professor Mari): LLM providers struggle formatting Mari's DB commands, racking up tokens. Shows the pattern of Mari's conversation mode needing better tooling for entity operations.
  • #3377 / #3380 (Identity auto-injection duplication): The identity auto-insert system has persistent duplication bugs — character info injected twice when detection fails. Shares the same architectural concern: auto-injected prompt content that's fragile and hard to control.
  • #3108 (XML escape wastes tokens): > unnecessarily escaped to &gt; in XML wrap format, wasting tokens on every turn. Same class: token waste in the system prompt.
  • #3379 / #3438 (Placement macros for auto-inserted blocks): The team has already addressed prompt structure issues with macros ({{context}}, {{status}}, etc.). The name list could follow a similar pattern — user-controllable placement and sizing.

Additional context

  • The name list is rebuilt from the DB on every generation (professor-mari-prompt-context.ts:30-34). This is a separate concern from token overhead — the caching problem exists even for small collections where the name list is trivial in size.
  • The PeekPromptModal already shows token estimates per prompt section. A user inspecting their prompt would see the <available_names> block consuming thousands of tokens.
  • The workspace assistant uses structured tool definitions (WORKSPACE_TOOL_DEFINITIONS) with proper JSON schemas. The pattern for tool-based entity discovery already exists in the codebase.
  • The LLMUsage interface already tracks cachedPromptTokens and cacheWritePromptTokens, confirming that provider-side caching is a supported concern.
  • This issue is complementary to #4767 (configurable output limits). That issue addresses truncation of large tool output; this issue addresses injection of large prompt content. Both reduce the token budget waste in Professor Mari.
  • The agent does conflate 128k with 1M context quite readily these days, but, the point remains.

*Research undertaken: codebase analysis of professor-mari-prompt-context.ts (name list assembly at lines 30-73, full function at lines 20-92), seed-mari.ts (MARI_ASSISTANT_PROMPT, ~9K tokens, 380 lines, data_access instructions), character-commands.ts (existing bracket command handlers, 1,436 lines), workspace-agent.service.ts (WORKSPACE_TOOL_DEFINITIONS, tool definitions and execution loop), generate.routes.ts (conversation system prompt construction at lines 2441-2466), base-provider.ts (LLMUsage interface, cachedPromptTokens field, fitMessagesToContext at lines 395-582). Token estimates based on average entity name lengths (characters: ~12 chars, personas: ~10, lorebooks: ~20, chats: ~30, presets: ~15) with comma separators and XML wrapper overhead. Provider caching behavior verified against Anthropic and OpenAI documentation. Repo-wide search for related issues: #4240 (dynamic blocks break cache), #2302 (double prompt assembly), #2778 (Mari helper functions), #3377/#3380 (identity auto-injection duplication), #3108 (XML escape token waste), #3379/#3438 (placement macros). Prior research documented in github-issues/README.md.

Originally created by @xDanteMD on GitHub (Aug 8, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/4768 Originally assigned to: @kolacheee on GitHub. ## What problem does this solve? Professor Mari's conversation mode has two interconnected problems with the `<available_names>` block in her system message: 1. **Noise at scale:** Every generation injects ALL entity names (characters, personas, lorebooks, chats, presets) as a flat, unfiltered list. For users with large collections, this becomes thousands of tokens of context noise that the model cannot meaningfully process. 2. **Cache invalidation:** The name list is rebuilt from the DB on every generation (`professor-mari-prompt-context.ts:30-73`). Even when no entities change, DB query ordering differences and re-serialization produce a different string, invalidating provider-side prompt caching. Both problems stem from the same design: a flat, dynamically-rebuilt name list injected into the system message on every generation. ### Scale of the name list problem | Collection size | Name list tokens (est.) | % of 128K context | | --- | --- | --- | | 50 characters | ~240 tokens | 0.2% | | 200 characters | ~960 tokens | 0.7% | | 1,000 characters | ~4,740 tokens | 3.7% | | 1,000 chars + personas + lorebooks + chats + presets | ~5,500+ tokens | 4.3%+ | These are comma-separated name lists wrapped in `<available_names>` XML blocks — no descriptions, no metadata, just names. The model receives them regardless of whether the user's current conversation involves any of these entities. ### Cache impact | Provider | Cache granularity | Cost of invalidation | | --- | --- | --- | | Anthropic | Prompt prefix (min 1,024 tokens for Claude) | Full re-prompt cost on cache miss | | OpenAI | Prompt prefix (automatic for repeated prefixes) | Full re-prompt cost on cache miss | | Google | Context caching (explicit cache creation) | N/A (manual caching) | For a user with 1,000 characters, the system message is ~13,740 tokens. On Anthropic, this means ~13,740 tokens are re-priced on every generation instead of cache-hitting at the reduced rate. Over a conversation with 50 generations, that's ~687,000 tokens of unnecessary full-price billing. The system message changes between generations because: - `DEFAULT_CONVERSATION_PROMPT` and `MARI_ASSISTANT_PROMPT` are stable - `<available_names>` blocks are **rebuilt from DB every generation** (lines 30-73) - `<loaded_context>` changes when new data is fetched via `[fetch:]` - DB queries may return rows in different orders across calls - Any entity change (add, edit, delete) between generations changes the entire block ### Why this is a problem 1. **The model already has a fetch mechanism.** Mari's `<data_access>` instructions already tell her to use `[fetch: type="character", name="Luna"]` to retrieve full card data. The name list exists so Mari knows what's *available* to fetch — but a flat list of 1,000 names is not a useful lookup mechanism. 2. **No filtering or search.** The model receives ALL names regardless of relevance. If the user asks about Luna, the model still sees 999 other character names it doesn't need. 3. **Compounding cost.** The noise problem and the caching problem compound each other — large name lists are both wasteful to inject AND wasteful to rebuild. ## Proposed solution **Option A: Replace with searchable tool (recommended)** Replace the flat `<available_names>` injection with a lightweight search tool that Mari can call when she needs to discover entities: ``` [list_characters: filter=""] → returns first 20 character names [list_characters: filter="luna"] → returns matching characters [search_characters: query="fortune teller"] → searches descriptions/tags [list_lorebooks: filter=""] → returns lorebook names ``` This eliminates both problems: no names in the system message (no noise, no cache invalidation). The existing `[fetch:]` command and `<data_access>` instructions provide the retrieval mechanism; this adds discovery. What already exists and can be reused: - The `[fetch:]` command already retrieves full entity data by name - The `<data_access>` instruction block already teaches Mari the fetch pattern - The workspace assistant's `app_data` tool schema covers CRUD operations - The DB query infrastructure (`chars.list()`, `lorebooksStore.list()`, etc.) already exists What would need to be added: - A `[list_characters]` / `[search_characters]` command handler in `character-commands.ts` - A reduced default name list (e.g., first 20 characters, or recently used) instead of all entities - Instructions in MARI_ASSISTANT_PROMPT teaching Mari to use the search tool **Option B: Cap + cache (minimal change)** Keep the `<available_names>` blocks but: 1. Cap at 50 names per category with a note: "and 950 more — use [list_characters: filter='...'] to search" 2. Cache the serialized string in memory; invalidate on entity CRUD 3. Sort alphabetically before joining for deterministic serialization This reduces noise from ~4,740 tokens to ~240 tokens and ensures cache hits when no entities change. Lower blast radius than Option A. **Option C: Stable prefix isolation** Move `<available_names>` and `<loaded_context>` to separate messages at stable positions. This isolates changing content from stable content (`MARI_ASSISTANT_PROMPT`, ~9,000 tokens), allowing the provider to cache the stable prefix. The changing blocks would still miss cache, but the stable prefix (~9K tokens) would cache consistently. **Recommended: Option A + B combined.** Replace the flat list with a searchable tool for new users, with a capped fallback for backward compatibility. Cache the reduced list deterministically. ## Alternatives considered - **Keep injecting all names** — works for small collections (<100 entities) but doesn't scale. A user with 1,000 characters sends ~4,740 tokens of noise every generation. - **Inject only recently used entities** — reduces noise but loses discoverability. Mari wouldn't know about characters the user hasn't chatted with recently. - **Inject names in a separate system message** — doesn't reduce token usage, just reorganizes the prompt. The core problem (flat list of 1,000 names) remains. (See Option C for a variant that does help with caching.) - **Truncate the name list** — hides the problem without solving it. Mari would silently lose access to entities beyond the truncation point. - **Accept the cache miss** — works for small collections but wastes money at scale. The cost compounds with every generation. ## Related issues - **#4240 (Pre-processing agent context omitted from first generation):** User reported that "Memory Recall or Secret Plot get injected right in the middle, right before the chat history. Since these are dynamic blocks, the cache breaks immediately after the system instructions." Same class of problem — dynamic blocks in the system message invalidating prompt caching. - Confirms that dynamic prompt content directly breaks provider-side caching. - **#2302 (Full prompt assembly runs twice every turn):** `assembleGenerationPrompt` invoked twice per turn, redoing all expensive work including storage reads and DB queries. The name list rebuild is one instance of this broader redundancy problem. - **#2778 (Helper Functions for Professor Mari):** LLM providers struggle formatting Mari's DB commands, racking up tokens. Shows the pattern of Mari's conversation mode needing better tooling for entity operations. - **#3377 / #3380 (Identity auto-injection duplication):** The identity auto-insert system has persistent duplication bugs — character info injected twice when detection fails. Shares the same architectural concern: auto-injected prompt content that's fragile and hard to control. - **#3108 (XML escape wastes tokens):** `>` unnecessarily escaped to `&gt;` in XML wrap format, wasting tokens on every turn. Same class: token waste in the system prompt. - **#3379 / #3438 (Placement macros for auto-inserted blocks):** The team has already addressed prompt structure issues with macros (`{{context}}`, `{{status}}`, etc.). The name list could follow a similar pattern — user-controllable placement and sizing. ## Additional context - The name list is rebuilt from the DB on every generation (`professor-mari-prompt-context.ts:30-34`). This is a separate concern from token overhead — the caching problem exists even for small collections where the name list is trivial in size. - The `PeekPromptModal` already shows token estimates per prompt section. A user inspecting their prompt would see the `<available_names>` block consuming thousands of tokens. - The workspace assistant uses structured tool definitions (`WORKSPACE_TOOL_DEFINITIONS`) with proper JSON schemas. The pattern for tool-based entity discovery already exists in the codebase. - The `LLMUsage` interface already tracks `cachedPromptTokens` and `cacheWritePromptTokens`, confirming that provider-side caching is a supported concern. - This issue is complementary to #4767 (configurable output limits). That issue addresses truncation of large tool output; this issue addresses injection of large prompt content. Both reduce the token budget waste in Professor Mari. - The agent does conflate 128k with 1M context quite readily these days, but, the point remains. --- *Research undertaken: codebase analysis of `professor-mari-prompt-context.ts` (name list assembly at lines 30-73, full function at lines 20-92), `seed-mari.ts` (MARI_ASSISTANT_PROMPT, ~9K tokens, 380 lines, data_access instructions), `character-commands.ts` (existing bracket command handlers, 1,436 lines), `workspace-agent.service.ts` (WORKSPACE_TOOL_DEFINITIONS, tool definitions and execution loop), `generate.routes.ts` (conversation system prompt construction at lines 2441-2466), `base-provider.ts` (LLMUsage interface, cachedPromptTokens field, fitMessagesToContext at lines 395-582). Token estimates based on average entity name lengths (characters: ~12 chars, personas: ~10, lorebooks: ~20, chats: ~30, presets: ~15) with comma separators and XML wrapper overhead. Provider caching behavior verified against Anthropic and OpenAI documentation. Repo-wide search for related issues: #4240 (dynamic blocks break cache), #2302 (double prompt assembly), #2778 (Mari helper functions), #3377/#3380 (identity auto-injection duplication), #3108 (XML escape token waste), #3379/#3438 (placement macros). Prior research documented in github-issues/README.md.
bsakaguchi 2026-10-21 05:51:43 +07:00
Author
Owner

@kolacheee commented on GitHub (Aug 8, 2026):

@xDanteMD this FR and #4767 look solid, I will handle them 👍

<!-- gh-comment-id:5227993222 --> @kolacheee commented on GitHub (Aug 8, 2026): @xDanteMD this FR and #4767 look solid, I will handle them 👍
Author
Owner

@kolacheee commented on GitHub (Aug 8, 2026):

Quick note on how this is landing, because the fix comes in two parts and I don't want the first PR to read as the whole answer.

PR #4771 (up now) is the "stop the bleeding" half. It removes the two costs this issue actually measured: it moves the <available_names> block and fetched data out of the system prefix into a stable tail injection, and dedupes + sorts + caps each list. That kills the per-turn prompt-cache invalidation and the token bloat on large libraries. What it deliberately does not claim to solve is discovery — a capped name list (any size, any ordering) can't help Mari find a character buried past the cap, and it was never going to resolve a fuzzy reference like "my chat with the vampire guy," since there's no name string to match. So please read #4771 as the caching/noise fix, not the discovery fix.

The discovery fix is a dedicated follow-up PR, and it's the one that actually addresses the "hundreds of entities" scenario. The plan there is to make Mari's fetch resolve in tiers instead of demanding an exact name:

  1. exact name (today),
  2. substring over name/description/tags (finds a buried "Zander", or "vampire" when it's literally in the card),
  3. semantic search for true paraphrases ("the brooding immortal one").

The good news is the semantic piece isn't from scratch — the engine already runs an embed → cosine-shortlist pipeline in production (it's what powers lorebook-entry matching today, via a zero-config local embedder). The follow-up extends that same machinery to characters, personas, lorebooks, chats, and presets. On a weak/ambiguous match Mari will be shown the actual list of semantic candidates ("I found three vampires — Dracula, Alucard, Vlad — which one?") rather than guessing from an alphabetical slice, and she'll only auto-open a result on a single strong hit.

tl;dr: #4771 fixes the cost, the next PR fixes the finding. Both are aimed at this issue.

<!-- gh-comment-id:5228396254 --> @kolacheee commented on GitHub (Aug 8, 2026): Quick note on how this is landing, because the fix comes in two parts and I don't want the first PR to read as the whole answer. **PR #4771 (up now) is the "stop the bleeding" half.** It removes the two costs this issue actually measured: it moves the `<available_names>` block and fetched data out of the system prefix into a stable tail injection, and dedupes + sorts + caps each list. That kills the per-turn prompt-cache invalidation and the token bloat on large libraries. What it deliberately does **not** claim to solve is *discovery* — a capped name list (any size, any ordering) can't help Mari find a character buried past the cap, and it was never going to resolve a fuzzy reference like "my chat with the vampire guy," since there's no name string to match. So please read #4771 as the caching/noise fix, not the discovery fix. **The discovery fix is a dedicated follow-up PR**, and it's the one that actually addresses the "hundreds of entities" scenario. The plan there is to make Mari's `fetch` resolve in tiers instead of demanding an exact name: 1. exact name (today), 2. substring over name/description/tags (finds a buried "Zander", or "vampire" when it's literally in the card), 3. **semantic search** for true paraphrases ("the brooding immortal one"). The good news is the semantic piece isn't from scratch — the engine already runs an embed → cosine-shortlist pipeline in production (it's what powers lorebook-entry matching today, via a zero-config local embedder). The follow-up extends that same machinery to characters, personas, lorebooks, chats, and presets. On a weak/ambiguous match Mari will be shown the actual list of semantic candidates ("I found three vampires — Dracula, Alucard, Vlad — which one?") rather than guessing from an alphabetical slice, and she'll only auto-open a result on a single strong hit. tl;dr: #4771 fixes the cost, the next PR fixes the finding. Both are aimed at this issue.
Author
Owner

@kolacheee commented on GitHub (Aug 9, 2026):

With #4778 and #4779 complete I think that solves the underlying problem so I'll be closing this issue, please do let us know if you have any feedback!

<!-- gh-comment-id:5229217142 --> @kolacheee commented on GitHub (Aug 9, 2026): With #4778 and #4779 complete I think that solves the underlying problem so I'll be closing this issue, please do let us know if you have any feedback!
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#2627
No description provided.