[PR #4771] [MERGED] feat(mari): stable, capped Home-Mari name lists (relocate out of the system prefix) (#4768) #6491

Closed
opened 2026-10-23 04:10:56 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/4771
Author: @kolacheee
Created: 8/8/2026
Status: ✅ Merged
Merged: 8/8/2026
Merged by: @kolacheee

Base: staging ← Head: feat/4768-available-names


📝 Commits (3)

  • 81d281c feat(mari): relocate Home-Mari name lists to a stable tail injection (#4768)
  • 26baf8b test(mari): pin the #4768 call-site wiring; tighten naming and comments
  • b9c405f test(mari): make the #4768 wiring pin match structurally, not by fixed window

📊 Changes

5 files changed (+316 additions, -41 deletions)

View changed files

📝 package.json (+1 -1)
📝 packages/server/src/db/seed-mari.ts (+1 -1)
📝 packages/server/src/routes/generate.routes.ts (+29 -2)
📝 packages/server/src/routes/generate/professor-mari-prompt-context.ts (+71 -37)
➕ scripts/regressions/professor-mari-prompt-context.regression.ts (+214 -0)

📄 Description

Linked issue

Closes #4768 (cache-half of the issue)

Why this change

Home Professor Mari's prompt injected a flat <available_names> list of every character, persona, lorebook, chat, and preset — plus any [fetch:]-loaded data — inside the system message. Two costs:

  1. Token noise on large libraries. The full name list grows unbounded (roughly a few thousand tokens at ~1,000 entities), spent on every turn.
  2. Prompt-cache churn. Every store lists desc(updatedAt), so any entity Mari herself creates or edits mid-conversation jumps to the head of its category and reorders the block. Because the block sat in the system prefix, that rewrite invalidated the static prompt prefix each turn — and with provider prompt caching enabled, forced a cache write every turn instead of a hit.

The name list and fetched data are reference data, not instructions, so they don't need to live in the system message at all.

What changed

  • Split resolveProfessorMariPromptContext into { stablePrompt, volatileContext }. The instruction block (MARI_ASSISTANT_PROMPT) stays on the system message as a static, cacheable prefix; the name lists + fetched data become volatileContext.
  • Inject volatileContext as a tail role:"user" message (contextKind:"injection") in generate.routes.ts, rebuilt each follow-up-loop iteration so a [fetch:] still surfaces its data on the follow-up turn. contextKind:"injection" keeps the normal history-trim pass from dropping it.
  • Dedupe + sort + cap each category at MAX_MARI_AVAILABLE_NAMES_PER_TYPE = 100, with an overflow hint. The sort is ICU-independent (UTF-16 code-unit order), so the block is byte-identical across turns and across Node builds — that determinism is what actually stabilizes the prefix.
  • Reworded the seed <data_access> block so Mari fetches any item by its exact name even when it isn't shown, and never tells the user an item doesn't exist just because it's past the cap.
  • New regression scripts/regressions/professor-mari-prompt-context.regression.ts (wired into regression:issues) pinning: the stable/volatile split, order-independence, the cap + overflow hint, byte-determinism, and — via a source scan — that the caller never folds the volatile half back onto the system prompt.

Deliberate choices flagged for maintainer input:

  • Uniform cap of 100 per category. Previously only chats were capped (at 50) and the other four were unbounded. This unifies them at 100. Open to per-category values if you'd prefer.
  • Order changes from recency to alphabetical, and for a library with >100 of a given type the visible window is the alphabetically-first 100 rather than the most-recent. This is a deliberate tradeoff: recency-ordering is exactly what caused the cache churn, so selecting/emitting by name is what makes the block stable. It's regression-safe because [fetch:] matches the full store by exact name (not the injected list) and the overflow hint tells Mari to try — but heavy-library users lose proactive enumeration beyond 100/type, and a fuzzy reference ("my chat with the vampire guy", no exact name) to a recent-but-unlisted item may miss where recency-ordering would have surfaced it.
  • Code constant, not a user setting (mirrors MAX_MARI_FETCHED_PRESET_CONTEXT_CHARS). A configurable version would pull in shared schema + client UI + locale keys; happy to do that as a stacked PR if wanted.

No migration needed: MARI_ASSISTANT_PROMPT is a compiled code constant (never persisted), so existing installs pick up the new text on upgrade.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

Automated checks already run by the author (green), listed as evidence — not a substitute for the human browser pass below:

  • pnpm check (TypeScript + ESLint + build) green; pnpm lint exit 0.
  • New professor-mari-prompt-context regression green; full pnpm regression:issues chain green (incl. open-issues and message-sharding); pnpm regression:prompt, professor-mari-shell-sandbox, professor-mari-wiki green.

Still needs a human pass in a real browser with a live LLM connection (the behavior isn't observable without real generation):

  • Manually verify in the Home Professor Mari chat that asking "what characters do I have?" lists names correctly (from the tail block, no extra round-trip).
  • Manually verify a [fetch:] by name still fires the fetch snackbar and Mari speaks to the fetched data on the follow-up turn (the #898 silent-Mari guard — this is the wiring most worth eyeballing).
  • Manually verify creating a character mid-conversation, then sending another message: Mari still lists correctly and doesn't lose track.
  • Manually verify (with >100 of a type) that fetching a name not shown in the list still succeeds.
  • Optional cache proof: with an Anthropic connection and caching enabled, watch usage.cachedPromptTokens across a turn where a character is created mid-chat — before this change the next turn's cached tokens collapse; after, they should hold.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

The changed strings are prompt text sent to a model, not user-facing UI or docs — nothing under docs/ references them, so there's no docs or docs-i18n obligation.

Summary by CodeRabbit

  • Improvements

    • Improved Professor Mari’s handling of available names and fetched information.
    • Large name lists are now organized consistently, with overflow guidance while preserving exact-name lookups.
    • Contextual information is retained more reliably during conversations, improving response accuracy.
  • Bug Fixes

    • Improved behavior for empty libraries, unavailable data, invalid names, and data-access failures.
  • Tests

    • Added regression coverage for prompt context, filtering, ordering, limits, and route integration.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/4771 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/8/2026 **Status:** ✅ Merged **Merged:** 8/8/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `feat/4768-available-names` --- ### 📝 Commits (3) - [`81d281c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/81d281ccc62d224ed46685ed10d0fc89389b0345) feat(mari): relocate Home-Mari name lists to a stable tail injection (#4768) - [`26baf8b`](https://github.com/Pasta-Devs/Marinara-Engine/commit/26baf8b2072da78144713eb8dc78a6c8ee06d1de) test(mari): pin the #4768 call-site wiring; tighten naming and comments - [`b9c405f`](https://github.com/Pasta-Devs/Marinara-Engine/commit/b9c405ff0cf7fd15d19460184d3bfa775c9a0f95) test(mari): make the #4768 wiring pin match structurally, not by fixed window ### 📊 Changes **5 files changed** (+316 additions, -41 deletions) <details> <summary>View changed files</summary> 📝 `package.json` (+1 -1) 📝 `packages/server/src/db/seed-mari.ts` (+1 -1) 📝 `packages/server/src/routes/generate.routes.ts` (+29 -2) 📝 `packages/server/src/routes/generate/professor-mari-prompt-context.ts` (+71 -37) ➕ `scripts/regressions/professor-mari-prompt-context.regression.ts` (+214 -0) </details> ### 📄 Description ## Linked issue Closes #4768 (cache-half of the issue) ## Why this change Home Professor Mari's prompt injected a flat `<available_names>` list of every character, persona, lorebook, chat, and preset — plus any `[fetch:]`-loaded data — **inside the system message**. Two costs: 1. **Token noise on large libraries.** The full name list grows unbounded (roughly a few thousand tokens at ~1,000 entities), spent on every turn. 2. **Prompt-cache churn.** Every store lists `desc(updatedAt)`, so any entity Mari *herself* creates or edits mid-conversation jumps to the head of its category and reorders the block. Because the block sat in the system prefix, that rewrite invalidated the static prompt prefix each turn — and with provider prompt caching enabled, forced a cache write every turn instead of a hit. The name list and fetched data are *reference data*, not instructions, so they don't need to live in the system message at all. ## What changed - **Split `resolveProfessorMariPromptContext` into `{ stablePrompt, volatileContext }`.** The instruction block (`MARI_ASSISTANT_PROMPT`) stays on the system message as a static, cacheable prefix; the name lists + fetched data become `volatileContext`. - **Inject `volatileContext` as a tail `role:"user"` message** (`contextKind:"injection"`) in `generate.routes.ts`, rebuilt each follow-up-loop iteration so a `[fetch:]` still surfaces its data on the follow-up turn. `contextKind:"injection"` keeps the normal history-trim pass from dropping it. - **Dedupe + sort + cap each category** at `MAX_MARI_AVAILABLE_NAMES_PER_TYPE = 100`, with an overflow hint. The sort is ICU-independent (UTF-16 code-unit order), so the block is byte-identical across turns and across Node builds — that determinism is what actually stabilizes the prefix. - **Reworded the seed `<data_access>` block** so Mari fetches any item by its *exact* name even when it isn't shown, and never tells the user an item doesn't exist just because it's past the cap. - **New regression** `scripts/regressions/professor-mari-prompt-context.regression.ts` (wired into `regression:issues`) pinning: the stable/volatile split, order-independence, the cap + overflow hint, byte-determinism, and — via a source scan — that the caller never folds the volatile half back onto the system prompt. **Deliberate choices flagged for maintainer input:** - **Uniform cap of 100 per category.** Previously only chats were capped (at 50) and the other four were unbounded. This unifies them at 100. Open to per-category values if you'd prefer. - **Order changes from recency to alphabetical**, and for a library with **>100 of a given type** the visible window is the alphabetically-first 100 rather than the most-recent. This is a deliberate tradeoff: recency-ordering is exactly what caused the cache churn, so selecting/emitting by name is what makes the block stable. It's regression-safe because `[fetch:]` matches the full store by exact name (not the injected list) and the overflow hint tells Mari to try — but heavy-library users lose *proactive* enumeration beyond 100/type, and a fuzzy reference ("my chat with the vampire guy", no exact name) to a recent-but-unlisted item may miss where recency-ordering would have surfaced it. - **Code constant, not a user setting** (mirrors `MAX_MARI_FETCHED_PRESET_CONTEXT_CHARS`). A configurable version would pull in shared schema + client UI + locale keys; happy to do that as a stacked PR if wanted. No migration needed: `MARI_ASSISTANT_PROMPT` is a compiled code constant (never persisted), so existing installs pick up the new text on upgrade. ## Validation - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes Automated checks already run by the author (green), listed as evidence — **not** a substitute for the human browser pass below: - `pnpm check` (TypeScript + ESLint + build) green; `pnpm lint` exit 0. - New `professor-mari-prompt-context` regression green; full `pnpm regression:issues` chain green (incl. `open-issues` and `message-sharding`); `pnpm regression:prompt`, `professor-mari-shell-sandbox`, `professor-mari-wiki` green. Still needs a human pass in a real browser with a live LLM connection (the behavior isn't observable without real generation): - **Manually verify** in the Home Professor Mari chat that asking "what characters do I have?" lists names correctly (from the tail block, no extra round-trip). - **Manually verify** a `[fetch:]` by name still fires the fetch snackbar **and** Mari speaks to the fetched data on the follow-up turn (the #898 silent-Mari guard — this is the wiring most worth eyeballing). - **Manually verify** creating a character mid-conversation, then sending another message: Mari still lists correctly and doesn't lose track. - **Manually verify** (with >100 of a type) that fetching a name **not** shown in the list still succeeds. - **Optional cache proof:** with an Anthropic connection and caching enabled, watch `usage.cachedPromptTokens` across a turn where a character is created mid-chat — before this change the next turn's cached tokens collapse; after, they should hold. ## Docs and release impact - [x] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) The changed strings are prompt text sent to a model, not user-facing UI or docs — nothing under `docs/` references them, so there's no docs or `docs-i18n` obligation. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Improvements** * Improved Professor Mari’s handling of available names and fetched information. * Large name lists are now organized consistently, with overflow guidance while preserving exact-name lookups. * Contextual information is retained more reliably during conversations, improving response accuracy. * **Bug Fixes** * Improved behavior for empty libraries, unavailable data, invalid names, and data-access failures. * **Tests** * Added regression coverage for prompt context, filtering, ordering, limits, and route integration. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:10:56 +07:00
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#6491
No description provided.