[PR #4778] [MERGED] feat(mari): tiered semantic entity discovery for [fetch:] (#4768 phase 2) #6494

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

📋 Pull Request Information

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

Base: staging ← Head: feat/4768-semantic-discovery


📝 Commits (8)

  • 0cc499e feat(mari): tiered entity resolution module for [fetch:] (#4768)
  • 7496529 feat(db): add nullable embedding columns for entity semantic search (#4768)
  • 4393e42 feat(mari): persisted embedding store with content-hash invalidation (#4768)
  • e1fec9b feat(mari): tiered fetch resolution + candidate disambiguation (#4768)
  • 04af212 fix(mari): address adversarial review of the #4768 semantic feature
  • 312d12b feat(mari): disambiguate same-named entities by id (#4768)
  • 0934f1f Merge branch 'staging' into feat/4768-semantic-discovery
  • 084a7cc fix(mari): address CodeRabbit review of the #4768 semantic PR

📊 Changes

15 files changed (+1117 additions, -20 deletions)

View changed files

📝 package.json (+1 -1)
📝 packages/server/src/db/schema/characters.ts (+4 -0)
📝 packages/server/src/db/schema/chats.ts (+2 -0)
📝 packages/server/src/db/schema/lorebooks.ts (+2 -0)
📝 packages/server/src/db/schema/prompts.ts (+2 -0)
📝 packages/server/src/db/seed-mari.ts (+6 -1)
📝 packages/server/src/routes/generate.routes.ts (+2 -0)
➕ packages/server/src/services/entity-embedding-store.ts (+259 -0)
➕ packages/server/src/services/entity-semantic-search.ts (+282 -0)
📝 packages/server/src/services/generation/professor-mari-command-runtime.ts (+111 -18)
📝 packages/server/src/services/storage/lorebooks.storage.ts (+4 -0)
➕ scripts/regressions/entity-embedding-store.regression.ts (+121 -0)
➕ scripts/regressions/helpers/bow-stub-embedder.ts (+36 -0)
➕ scripts/regressions/professor-mari-fetch-integration.regression.ts (+164 -0)
➕ scripts/regressions/professor-mari-fetch-tiers.regression.ts (+121 -0)

📄 Description

Note

Stacks on #4771 (the phase-1 cache/noise fix for this same issue). This PR is branched off #4771, so until that merges the diff here also shows its two commits (relocate the name lists to a stable tail injection + the wiring-pin test). Merge #4771 first, then this. Kept as a draft until then and until the manual browser pass below.

Linked issue

Part of #4768 (phase 2 — the discovery half; see the roadmap comment on the issue).

Why this change

Phase 1 (#4771) fixed the cost of Mari's name lists but not discovery: conversation-mode Mari resolved a [fetch:] by exact normalized name only. So a character buried past the injected-list cap ("Zander", when there are hundreds), or any fuzzy reference ("my chat with the vampire guy"), failed — and a wrong guess set fetchSucceeded=false, which meant the follow-up never fired and Mari went silent. A capped name list can never solve this; it needs search.

What changed

Mari's [fetch:] now resolves in tiers, entirely server-side (the [fetch:] grammar is unchanged — the existing name is treated as a query):

  1. exact name (unchanged behavior),
  2. substring over name/description/tags,
  3. semantic embedding shortlist.

On a single confident hit it opens the item as before. On a weak/ambiguous match it returns a ranked candidate list ("Several character matches for 'vampire' — ask which one, do not guess") instead of guessing. Both ride the existing mariContext slot — which #4771 moved into the volatile tail, so a candidate list causes no cache-prefix churn — and both trigger the existing fetch follow-up so Mari speaks to what she pulled.

Semantic search reuses the engine's existing embed→cosine pipeline (the same one powering lorebook-entry matching), extended to all five entity types:

  • 5 nullable embedding columns (characters, personas, chats, prompt_presets, lorebook books). Backward-compatible and layout-neutral — no migrate, no STORAGE_VERSION/storage-format bump (the file-native store derives column metadata from the schema; these tables aren't sharded).
  • Content-addressed staleness: the column stores {hash(embedText), source, vector}, and a read whose hash/source no longer matches is treated as absent → re-embedded. This needs zero invalidation hooks in any entity's write path and is structurally immune to the drift bug it replaces (which I also fixed in passing: the lorebook invalidation predicate omitted description).
  • The embedding setter writes only the embedding column — no version snapshot, no updatedAt bump — so background vectorization never churns recency order or the chat sidebar. Embedding compute is bounded per fetch; the substring tier covers the common case with no embeddings at all, and semantic warms lazily.

The seed <data_access> prompt teaches the flexible resolution and the disambiguation protocol.

Deliberate choices / tradeoffs (flagged for your read):

  • Auto-open thresholds (calibrated cosine ≥ 0.55 with a margin) are code constants, tuned against the calibration baseline — worth tuning against real libraries; pinned in the regression.
  • Cold-start warming: a fresh, large, never-searched library warms its embeddings over the first several fetches (bounded per fetch). The always-available substring tier covers most cases meanwhile; a background revectorize pass could remove the cold start as a follow-up.
  • Chats are included (weakest signal — name + tags/summary only).
  • Client affordance deferred: the server emits a data_candidates action but there's no toast yet; Mari presents the list in her follow-up text (server-first MVP, per our discussion).

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) — not a substitute for the human pass below:

  • pnpm check (TypeScript + ESLint + build) green.
  • New regressions, all wired into regression:issues and green: professor-mari-fetch-tiers (every tier + the auto-open-vs-disambiguate boundary, via a deterministic collision-free stub embedder — no ONNX), entity-embedding-store (content-hash + source staleness, no-updatedAt-bump, flat-column table via the real db.update path, Mari self-exclusion), professor-mari-fetch-integration (end-to-end handleProfessorMariCommand: exact, fuzzy auto-open, ambiguous→candidates, miss, options-eviction).
  • Full regression:issues + regression:prompt + professor-mari lanes green.
  • A 3-lens adversarial review was run against the feature; all confirmed findings were fixed (options-block eviction, same-name auto-open, bounded/persisted embedding, name-vs-description substring gating, source-tagged staleness, exact-id tier, embedder-throw degradation).

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

  • Manually verify in the Home Mari chat: with a library of many characters, [fetch:] a buried one by exact name, by a partial/approximate name, and by a description ("the vampire guy") — confirm each resolves.
  • Manually verify an ambiguous reference lists candidates and Mari asks which one, then resolving it opens the right entity and the options prompt does not linger.
  • Manually verify with no embedder configured (or a Lite build): exact + substring fetch still work; nothing errors.
  • Manually verify a fetch behaves as before for the everyday exact-name case (no regression).

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 prompt text is model-facing, not user docs. If the Mari/assistant user docs describe fetch behavior, a short mention that fetch now resolves fuzzily could be worth a follow-up — flagging for your call.

Summary by CodeRabbit

  • New Features

    • Professor Mari can find characters, personas, lorebooks, chats, and presets using exact names, partial matches, descriptions, or semantic queries.
    • Ambiguous results display selectable candidates, while confirmed selections open the exact matching record.
    • Improved handling of unavailable or unmatched requests with clearer clarification behavior.
    • Search embeddings are persisted and refreshed automatically when relevant content changes.
  • Bug Fixes

    • Prevented stale or incorrect matches after entity updates.
  • Tests

    • Added regression coverage for matching, disambiguation, persistence, and fallback behavior.

🔄 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/4778 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/8/2026 **Status:** ✅ Merged **Merged:** 8/9/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `feat/4768-semantic-discovery` --- ### 📝 Commits (8) - [`0cc499e`](https://github.com/Pasta-Devs/Marinara-Engine/commit/0cc499e490678c27bda2b09919dabdc992953aba) feat(mari): tiered entity resolution module for [fetch:] (#4768) - [`7496529`](https://github.com/Pasta-Devs/Marinara-Engine/commit/749652977f2beda2c371e90cbf56b82ee0507afe) feat(db): add nullable embedding columns for entity semantic search (#4768) - [`4393e42`](https://github.com/Pasta-Devs/Marinara-Engine/commit/4393e42f530e3caa1305d22235bd11462ba603f7) feat(mari): persisted embedding store with content-hash invalidation (#4768) - [`e1fec9b`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e1fec9b110ab617068991e9c0961d0bf84924679) feat(mari): tiered fetch resolution + candidate disambiguation (#4768) - [`04af212`](https://github.com/Pasta-Devs/Marinara-Engine/commit/04af21215929871a0e37732cd021ad42f96a52de) fix(mari): address adversarial review of the #4768 semantic feature - [`312d12b`](https://github.com/Pasta-Devs/Marinara-Engine/commit/312d12b9c1f7f55ac9d954e0056fd39cc6b283db) feat(mari): disambiguate same-named entities by id (#4768) - [`0934f1f`](https://github.com/Pasta-Devs/Marinara-Engine/commit/0934f1f4ba1e7d85e687c4d52dcb42a41da05e11) Merge branch 'staging' into feat/4768-semantic-discovery - [`084a7cc`](https://github.com/Pasta-Devs/Marinara-Engine/commit/084a7ccc585c7cfd932db21388d1d06c7a94a772) fix(mari): address CodeRabbit review of the #4768 semantic PR ### 📊 Changes **15 files changed** (+1117 additions, -20 deletions) <details> <summary>View changed files</summary> 📝 `package.json` (+1 -1) 📝 `packages/server/src/db/schema/characters.ts` (+4 -0) 📝 `packages/server/src/db/schema/chats.ts` (+2 -0) 📝 `packages/server/src/db/schema/lorebooks.ts` (+2 -0) 📝 `packages/server/src/db/schema/prompts.ts` (+2 -0) 📝 `packages/server/src/db/seed-mari.ts` (+6 -1) 📝 `packages/server/src/routes/generate.routes.ts` (+2 -0) ➕ `packages/server/src/services/entity-embedding-store.ts` (+259 -0) ➕ `packages/server/src/services/entity-semantic-search.ts` (+282 -0) 📝 `packages/server/src/services/generation/professor-mari-command-runtime.ts` (+111 -18) 📝 `packages/server/src/services/storage/lorebooks.storage.ts` (+4 -0) ➕ `scripts/regressions/entity-embedding-store.regression.ts` (+121 -0) ➕ `scripts/regressions/helpers/bow-stub-embedder.ts` (+36 -0) ➕ `scripts/regressions/professor-mari-fetch-integration.regression.ts` (+164 -0) ➕ `scripts/regressions/professor-mari-fetch-tiers.regression.ts` (+121 -0) </details> ### 📄 Description > [!NOTE] > **Stacks on #4771** (the phase-1 cache/noise fix for this same issue). This PR is branched off #4771, so until that merges the diff here also shows its two commits (`relocate the name lists to a stable tail injection` + the wiring-pin test). **Merge #4771 first**, then this. Kept as a draft until then and until the manual browser pass below. ## Linked issue Part of #4768 (phase 2 — the discovery half; see the roadmap comment on the issue). ## Why this change Phase 1 (#4771) fixed the *cost* of Mari's name lists but not *discovery*: conversation-mode Mari resolved a `[fetch:]` by **exact normalized name only**. So a character buried past the injected-list cap ("Zander", when there are hundreds), or any fuzzy reference ("my chat with the vampire guy"), failed — and a wrong guess set `fetchSucceeded=false`, which meant the follow-up never fired and Mari went **silent**. A capped name list can never solve this; it needs search. ## What changed Mari's `[fetch:]` now resolves in **tiers**, entirely server-side (the `[fetch:]` grammar is unchanged — the existing `name` is treated as a query): 1. **exact name** (unchanged behavior), 2. **substring** over name/description/tags, 3. **semantic** embedding shortlist. On a single confident hit it opens the item as before. On a weak/ambiguous match it returns a ranked **candidate list** ("Several character matches for 'vampire' — ask which one, do not guess") instead of guessing. Both ride the existing `mariContext` slot — which #4771 moved into the volatile tail, so a candidate list causes **no cache-prefix churn** — and both trigger the existing fetch follow-up so Mari speaks to what she pulled. Semantic search reuses the engine's existing embed→cosine pipeline (the same one powering lorebook-entry matching), extended to all five entity types: - **5 nullable `embedding` columns** (characters, personas, chats, prompt_presets, lorebook books). Backward-compatible and layout-neutral — **no `migrate`, no `STORAGE_VERSION`/storage-format bump** (the file-native store derives column metadata from the schema; these tables aren't sharded). - **Content-addressed staleness**: the column stores `{hash(embedText), source, vector}`, and a read whose hash/source no longer matches is treated as absent → re-embedded. This needs **zero invalidation hooks** in any entity's write path and is structurally immune to the drift bug it replaces (which I also fixed in passing: the lorebook invalidation predicate omitted `description`). - The embedding setter writes **only** the embedding column — no version snapshot, no `updatedAt` bump — so background vectorization never churns recency order or the chat sidebar. Embedding compute is **bounded per fetch**; the substring tier covers the common case with no embeddings at all, and semantic warms lazily. The seed `<data_access>` prompt teaches the flexible resolution and the disambiguation protocol. **Deliberate choices / tradeoffs** (flagged for your read): - **Auto-open thresholds** (calibrated cosine ≥ 0.55 with a margin) are code constants, tuned against the calibration baseline — worth tuning against real libraries; pinned in the regression. - **Cold-start warming**: a fresh, large, never-searched library warms its embeddings over the first several fetches (bounded per fetch). The always-available substring tier covers most cases meanwhile; a background revectorize pass could remove the cold start as a follow-up. - **Chats** are included (weakest signal — name + tags/summary only). - **Client affordance deferred**: the server emits a `data_candidates` action but there's no toast yet; Mari presents the list in her follow-up text (server-first MVP, per our discussion). ## 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) — **not** a substitute for the human pass below: - `pnpm check` (TypeScript + ESLint + build) green. - New regressions, all wired into `regression:issues` and green: `professor-mari-fetch-tiers` (every tier + the auto-open-vs-disambiguate boundary, via a deterministic collision-free stub embedder — no ONNX), `entity-embedding-store` (content-hash + source staleness, no-`updatedAt`-bump, flat-column table via the real `db.update` path, Mari self-exclusion), `professor-mari-fetch-integration` (end-to-end `handleProfessorMariCommand`: exact, fuzzy auto-open, ambiguous→candidates, miss, options-eviction). - Full `regression:issues` + `regression:prompt` + `professor-mari` lanes green. - A 3-lens adversarial review was run against the feature; all confirmed findings were fixed (options-block eviction, same-name auto-open, bounded/persisted embedding, name-vs-description substring gating, source-tagged staleness, exact-id tier, embedder-throw degradation). Still needs a human pass in the app with a real embedder + LLM connection (behavior isn't observable without live generation): - **Manually verify** in the Home Mari chat: with a library of many characters, `[fetch:]` a buried one by exact name, by a partial/approximate name, and by a description ("the vampire guy") — confirm each resolves. - **Manually verify** an ambiguous reference lists candidates and Mari asks which one, then resolving it opens the right entity and the options prompt does not linger. - **Manually verify** with **no embedder configured** (or a Lite build): exact + substring fetch still work; nothing errors. - **Manually verify** a fetch behaves as before for the everyday exact-name case (no regression). ## 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 prompt text is model-facing, not user docs. If the Mari/assistant user docs describe fetch behavior, a short mention that fetch now resolves fuzzily could be worth a follow-up — flagging for your call. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Professor Mari can find characters, personas, lorebooks, chats, and presets using exact names, partial matches, descriptions, or semantic queries. * Ambiguous results display selectable candidates, while confirmed selections open the exact matching record. * Improved handling of unavailable or unmatched requests with clearer clarification behavior. * Search embeddings are persisted and refreshed automatically when relevant content changes. * **Bug Fixes** * Prevented stale or incorrect matches after entity updates. * **Tests** * Added regression coverage for matching, disambiguation, persistence, and fallback behavior. <!-- 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:57 +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#6494
No description provided.