[PR #3343] [MERGED] feat(lorebooks): embed a linked character lorebook into the card (#3341) #5889

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

📋 Pull Request Information

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

Base: staging ← Head: feat/3341-embed-lorebook-into-card


📝 Commits (5)

  • aaa00a9 feat(lorebooks): embed a linked character lorebook into the card (#3341)
  • 97f67a5 fix(lorebooks): harden embed-lorebook from adversarial review (#3341)
  • 62524d5 Merge branch 'staging' into feat/3341-embed-lorebook-into-card
  • 763f75d Merge branch 'staging' into feat/3341-embed-lorebook-into-card
  • dfc2437 Address embedded lorebook review feedback

📊 Changes

6 files changed (+362 additions, -25 deletions)

View changed files

📝 packages/client/src/components/characters/CharacterEditor.tsx (+72 -7)
📝 packages/client/src/components/lorebooks/LorebookAssignmentSection.tsx (+69 -2)
📝 packages/client/src/hooks/use-lorebooks.ts (+16 -0)
📝 packages/server/src/routes/characters.routes.ts (+75 -0)
📝 packages/server/src/routes/lorebooks.routes.ts (+8 -6)
📝 packages/server/src/services/lorebook/character-book-sync.ts (+122 -10)

📄 Description

Linked issue

Closes #3341.

Why this change

Character cards can carry an embedded lorebook (V2 data.character_book) that exports with the card, but there was no way to create that from inside Marinara. A lorebook attached via Assign Lorebook is only linked — a separate row referenced by the character — and linked lorebooks are not written into the card, so they get dropped on export (/characters/:id/export serializes charData as-is). The only characters that exported with a working lorebook were ones imported with an embedded book already; anything you authored couldn't be shared as a self-contained card.

What changed

Adds an "Embed into card" action — the inverse of the existing Import Embedded Lorebook (card → standalone). After embedding, the lorebook exports with the character (native + compatible) and future /lorebooks edits keep the embedded copy in sync, exactly like an imported embedded book.

Server

  • character-book-sync.ts: export the existing toCharacterBook; add embedLorebookIntoCharacter (writes character_book + the extensions.importMetadata.embeddedLorebook forward pointer in one atomic, skipVersionSnapshot update) and resolveEmbeddedCharacterId.
  • POST /characters/:id/embedded-lorebook/embed with guards: reject persona / non-character-category books (400); refuse to clobber a different embedded book in the single character_book slot (409); additively union the character into the lorebook's links (never a bare replace) so it auto-activates and stays syncable. Returns the written character_book.

Latent bug fixed in the same area (this touches the recently-fixed embedded-lorebook sync — #554/#1551/#2971): syncCharacterBookFromLorebook and the lorebook DELETE resolved the target character from the lorebook's hydrated characterId, which is only the alphabetically-first linked character — wrong for a book linked to several characters. Both now resolve the embedding character via the authoritative forward pointer (resolveEmbeddedCharacterId). It's fast-path-first (the derived id, identical to the old behaviour on the common single-link path) and only scans the characters table when the book has >1 character link — so world / single-linked lorebook edits stay scan-free.

Client

  • useEmbedLorebook hook.
  • An "Embed into card" / "Embedded" + "Refresh" / disabled-when-slot-taken affordance on assigned character lorebooks, gated to character owners (personas never show it). On embed, the editor patches its local formData from the returned character_book so a dirty editor's next Save can't revert the embed.

Hardening from an adversarial self-review (2nd commit)

  • Silent-data-loss fix: embedding while the editor was dirty could let a later Save send stale pre-embed data and revert the write — now the editor patches formData on embed.
  • Kept the sync path scan-free on the common case (only >1-link books scan).
  • parseCharacterData is try/catch-guarded so a corrupt character row can't 500 a lorebook delete.
  • Client affordance matches the server 409 (disabled when the slot holds an unpointered baked book).

Accepted limitation (documented, not silent)

There's no reverse lorebook→characters index, so two cards can each embed the same standalone book (e.g. via character duplication, or embedding a book already embedded elsewhere). Each keeps its own character_book snapshot; a later entry edit refreshes the first forward-pointer match, so a second card's copy can drift until its Refresh. This matches the pre-existing multi-embed behaviour; a real exclusivity index is follow-up scope.

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

Done by the agent:

  • Server typecheck (tsc -b ../shared && tsc --noEmit), shared typecheck, client build (tsc -b && vite build), and client ESLint all pass.
  • ⚠️ Full pnpm check currently fails at the server build step on Windows — a pre-existing v2.1.0 bug in packages/server/scripts/build.mjs (spawns Node via an unquoted "C:\Program Files\…" path), reproduced on clean staging with this branch's changes stashed. Not caused by this PR; flagged separately.

Still needs manual verification (no automated server test suite in-repo):

  • Embed (empty slot): assign a 3-entry character lorebook, click Embed into card → toast, row shows Embedded; reopen the character → character_book has 3 entries; export the card → the lorebook is present.
  • Dirty-editor safety: edit a character field, Embed into card, then Save → the embed survives (character_book + pointer intact, not reverted).
  • Refresh: edit an entry via Edit Linked Lorebook, click Refresh → character_book reflects the edit.
  • Reject different / persona: with book A embedded, Embed on book B is disabled (server 409s); a persona lorebook is 400-rejected via direct API.
  • Multi-link preserved: a lorebook linked to X and Y (Y alphabetically first), embed into X → links still contain both X and Y (not collapsed), and adding an entry then reopening X shows it in character_book (regression: the old code synced to Y).
  • Delete/clear: delete a lorebook embedded into a non-first-linked character → that card's character_book and pointer are cleared.
  • Personas unaffected: a persona editor's lorebook section shows no embed/refresh/badge.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

UI evidence (if applicable)

New per-lorebook affordance on the character Lorebook tab: Embed into card → Embedded + Refresh. No other visual change. (Screenshots to be added on manual verification.)

Summary by CodeRabbit

  • New Features

    • Characters can now embed a lorebook directly into a card from the editor.
    • The lorebook list now shows embed status and offers embed/refresh actions for character cards.
  • Bug Fixes

    • Improved handling of embedded lorebooks when a character has unsaved edits, so changes are preserved correctly.
    • Lorebook updates and removals now stay in sync more reliably, even when a lorebook is linked to multiple characters.
    • Better resilience when character data is malformed, preventing related actions from failing unexpectedly.

🔄 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/3343 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 7/7/2026 **Status:** ✅ Merged **Merged:** 7/7/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `feat/3341-embed-lorebook-into-card` --- ### 📝 Commits (5) - [`aaa00a9`](https://github.com/Pasta-Devs/Marinara-Engine/commit/aaa00a95bae2e7db532764eca07c94afaa9fc98b) feat(lorebooks): embed a linked character lorebook into the card (#3341) - [`97f67a5`](https://github.com/Pasta-Devs/Marinara-Engine/commit/97f67a531ee832412f7b90586b238c01d119dac3) fix(lorebooks): harden embed-lorebook from adversarial review (#3341) - [`62524d5`](https://github.com/Pasta-Devs/Marinara-Engine/commit/62524d56d9bd6dd05f2d983f20858e756536f223) Merge branch 'staging' into feat/3341-embed-lorebook-into-card - [`763f75d`](https://github.com/Pasta-Devs/Marinara-Engine/commit/763f75da76c759d8ca1de6938542a67275c8f0f8) Merge branch 'staging' into feat/3341-embed-lorebook-into-card - [`dfc2437`](https://github.com/Pasta-Devs/Marinara-Engine/commit/dfc2437ac8c0d9d23465b10365226f06a942450d) Address embedded lorebook review feedback ### 📊 Changes **6 files changed** (+362 additions, -25 deletions) <details> <summary>View changed files</summary> 📝 `packages/client/src/components/characters/CharacterEditor.tsx` (+72 -7) 📝 `packages/client/src/components/lorebooks/LorebookAssignmentSection.tsx` (+69 -2) 📝 `packages/client/src/hooks/use-lorebooks.ts` (+16 -0) 📝 `packages/server/src/routes/characters.routes.ts` (+75 -0) 📝 `packages/server/src/routes/lorebooks.routes.ts` (+8 -6) 📝 `packages/server/src/services/lorebook/character-book-sync.ts` (+122 -10) </details> ### 📄 Description ## Linked issue Closes #3341. ## Why this change Character cards can carry an **embedded** lorebook (V2 `data.character_book`) that exports with the card, but there was no way to *create* that from inside Marinara. A lorebook attached via **Assign Lorebook** is only *linked* — a separate row referenced by the character — and linked lorebooks are **not** written into the card, so they get dropped on export (`/characters/:id/export` serializes `charData` as-is). The only characters that exported with a working lorebook were ones imported with an embedded book already; anything you authored couldn't be shared as a self-contained card. ## What changed Adds an **"Embed into card"** action — the inverse of the existing *Import Embedded Lorebook* (card → standalone). After embedding, the lorebook exports with the character (native + compatible) and future `/lorebooks` edits keep the embedded copy in sync, exactly like an imported embedded book. **Server** - `character-book-sync.ts`: export the existing `toCharacterBook`; add `embedLorebookIntoCharacter` (writes `character_book` + the `extensions.importMetadata.embeddedLorebook` forward pointer in one atomic, `skipVersionSnapshot` update) and `resolveEmbeddedCharacterId`. - `POST /characters/:id/embedded-lorebook/embed` with guards: reject persona / non-`character`-category books (400); refuse to clobber a *different* embedded book in the single `character_book` slot (409); additively **union** the character into the lorebook's links (never a bare replace) so it auto-activates and stays syncable. Returns the written `character_book`. **Latent bug fixed in the same area** (this touches the recently-fixed embedded-lorebook sync — #554/#1551/#2971): `syncCharacterBookFromLorebook` and the lorebook `DELETE` resolved the target character from the lorebook's *hydrated* `characterId`, which is only the **alphabetically-first linked** character — wrong for a book linked to several characters. Both now resolve the embedding character via the authoritative forward pointer (`resolveEmbeddedCharacterId`). It's fast-path-first (the derived id, identical to the old behaviour on the common single-link path) and only scans the characters table when the book has **>1** character link — so world / single-linked lorebook edits stay scan-free. **Client** - `useEmbedLorebook` hook. - An **"Embed into card"** / **"Embedded" + "Refresh"** / disabled-when-slot-taken affordance on assigned character lorebooks, gated to character owners (personas never show it). On embed, the editor patches its local `formData` from the returned `character_book` so a dirty editor's next Save can't revert the embed. ### Hardening from an adversarial self-review (2nd commit) - **Silent-data-loss fix:** embedding while the editor was dirty could let a later Save send stale pre-embed data and revert the write — now the editor patches `formData` on embed. - Kept the sync path scan-free on the common case (only >1-link books scan). - `parseCharacterData` is `try/catch`-guarded so a corrupt character row can't 500 a lorebook delete. - Client affordance matches the server 409 (disabled when the slot holds an unpointered baked book). ### Accepted limitation (documented, not silent) There's no reverse lorebook→characters index, so two cards *can* each embed the same standalone book (e.g. via character duplication, or embedding a book already embedded elsewhere). Each keeps its own `character_book` snapshot; a later entry edit refreshes the first forward-pointer match, so a second card's copy can drift until its **Refresh**. This matches the pre-existing multi-embed behaviour; a real exclusivity index is follow-up scope. ## 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 Done by the agent: - Server typecheck (`tsc -b ../shared && tsc --noEmit`), shared typecheck, client build (`tsc -b && vite build`), and client ESLint all pass. - ⚠️ Full `pnpm check` currently fails at the **server build** step on Windows — a **pre-existing v2.1.0 bug** in `packages/server/scripts/build.mjs` (spawns Node via an unquoted `"C:\Program Files\…"` path), reproduced on clean `staging` with this branch's changes stashed. Not caused by this PR; flagged separately. Still needs manual verification (no automated server test suite in-repo): - **Embed (empty slot):** assign a 3-entry character lorebook, click *Embed into card* → toast, row shows *Embedded*; reopen the character → `character_book` has 3 entries; export the card → the lorebook is present. - **Dirty-editor safety:** edit a character field, *Embed into card*, then **Save** → the embed survives (character_book + pointer intact, not reverted). - **Refresh:** edit an entry via *Edit Linked Lorebook*, click *Refresh* → `character_book` reflects the edit. - **Reject different / persona:** with book A embedded, *Embed* on book B is disabled (server 409s); a persona lorebook is 400-rejected via direct API. - **Multi-link preserved:** a lorebook linked to X and Y (Y alphabetically first), embed into X → links still contain both X and Y (not collapsed), and adding an entry then reopening X shows it in `character_book` (regression: the old code synced to Y). - **Delete/clear:** delete a lorebook embedded into a non-first-linked character → that card's `character_book` and pointer are cleared. - **Personas unaffected:** a persona editor's lorebook section shows no embed/refresh/badge. ## Docs and release impact - [ ] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Version/release files updated (only if this PR includes a version bump) ## UI evidence (if applicable) New per-lorebook affordance on the character Lorebook tab: *Embed into card* → *Embedded* + *Refresh*. No other visual change. (Screenshots to be added on manual verification.) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Characters can now embed a lorebook directly into a card from the editor. * The lorebook list now shows embed status and offers embed/refresh actions for character cards. * **Bug Fixes** * Improved handling of embedded lorebooks when a character has unsaved edits, so changes are preserved correctly. * Lorebook updates and removals now stay in sync more reliably, even when a lorebook is linked to multiple characters. * Better resilience when character data is malformed, preventing related actions from failing unexpectedly. <!-- 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:04:50 +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#5889
No description provided.