[PR #3765] [MERGED] fix(prompt): pass prompt leaf content to the model verbatim (stop escaping angle brackets) #6092

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

📋 Pull Request Information

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

Base: staging ← Head: fix/prompt-leaf-verbatim-tags


📝 Commits (3)

  • b926026 fix(prompt): stop escaping angle brackets in prompt leaf content
  • 7510d36 fix(prompt): harden verbatim prompt-leaf contract against re-escaping
  • 0ac038e Merge branch 'staging' into fix/prompt-leaf-verbatim-tags

📊 Changes

6 files changed (+194 additions, -53 deletions)

View changed files

📝 CHANGELOG.md (+1 -0)
📝 CONTRIBUTING.md (+12 -0)
📝 packages/server/src/services/generation/scene-context-runtime.ts (+7 -7)
📝 packages/server/src/services/prompt/prompt-escaping.ts (+67 -8)
📝 scripts/regressions/open-issues.regression.ts (+2 -2)
📝 scripts/regressions/prompt.regression.ts (+105 -36)

📄 Description

Linked issue

Closes #3766

What this does

Prompt leaf content — character card fields, persona, lorebook entries, memories, scene text, and example dialogue — now reaches the model verbatim. Angle-bracket and HTML-style tags (<thinking>, <scenario>, <div style="...">) are passed through exactly as authored instead of arriving at the model as &lt;thinking&gt;.

This fixes a recurring user-visible bug: <test> typed in a persona or card showed up as &lt;test> in Peek Prompt / the assembled prompt, roleplay HTML formatting broke, the editor displayed raw &lt;, and tokens were wasted on entities.

The change itself is one line of behavior (the XML leaf path stops HTML-escaping). The bulk of this PR is hardening so it stops getting silently re-broken.


Why this regression keeps happening

Leaf-content escaping has flip-flopped across many versions. The reason it keeps coming back is that the guard was never actually deleted before this branch — every prior "fix" only carved out an exception rather than removing the escaping:

  • the escaper was born escaping all of &, <, >;
  • one change dropped only >, a later one re-added >, another dropped it again;
  • <START> example-dialogue carve-outs were added (#3441, #3623);
  • a display-layer band-aid decoded &lt;font…&gt; before rendering (#3206) so the escaping merely looked harmless while the model still received the mangled &lt;.

The < escaping survived all of that. Because the underlying injection-guard framing was never removed, three renewable sources kept regenerating the belief that escaping is correct and kept re-attracting it:

  1. The function name. escapeXmlText reads as "an XML escaper," so making its body escape again looks like a bug fix, not a regression. (There is even a second, unrelated local escapeXmlText in knowledge-router.ts that legitimately does escape — an identical name with opposite behavior.)
  2. The CHANGELOG. It still declares </& escaping deliberate "prompt-boundary safety" (#3108) and "Hardened prompt assembly … by escaping untrusted character/persona card text," with no countervailing entry. Release notes are the first thing a contributor reads, and they argued for escaping.
  3. No recorded decision. CONTRIBUTING.md never mentioned this; the only rationale lived in a file header a re-escape PR's author might never open.

This PR is the first true removal, and it closes all three sources (see Hardening below).


Why verbatim is the correct final state

Threat model. Marinara Engine is local, single-user roleplay. The person who authors or imports a card is the same person the card would "attack." The worst realistic outcome of an unescaped <system>-looking tag is the model role-playing something odd — which the user sees immediately in their own chat and fixes by editing their own card. That is a rare, self-inflicted, self-correcting annoyance, not a security boundary. Escaping traded that non-threat for a constant, real harm: the very common, legitimate use of angle-bracket/HTML tags in cards and lorebooks arrived mangled.

The model is not an XML parser. Escaping treated the LLM as if a stray < could "break out" of a structural element the way it would in a real XML document. An LLM reads tokens; there is no parser to break out of. Turning < into &lt; closes no injection surface — it only corrupts text.

Structure is not at risk. The framework's own section wrappers (<description>…</description>, <last_message>…, etc.) are emitted by wrapContent around leaf content, from fixed section names, independent of what the content contains. Verbatim leaf content therefore cannot alter the structural tags — it only changes what sits inside them, as intended.

Honest residual limitation. Verbatim does mean a self-authored/imported card can paste a convincing framework-style closing tag plus fake instructions into context. In a local single-user tool that is self-inflicted and self-fixable, and it is no stronger than writing those instructions in plain prose (which the model reads either way). If a future multi-tenant or shared-marketplace deployment ever changes the threat model, the right response is a validation/consent step at the import boundary, not silent per-token escaping of everyone's content at prompt-assembly time.


What deliberately stays escaped (out of scope)

The agent value/attribute escapers are unchanged and must stay:

  • escapeXml / escapeXmlAttribute in agent-executor.ts, the local escaper in knowledge-router.ts, and the storyboard/attachment escapers escape dynamic values into XML attributes and into strict, machine-parsed agent documents (world-state, entry catalogs, <turn_sections>, <attached_file name="…">). Those are parsed downstream, where a stray " or < genuinely breaks an attribute or element.

Note that agent-executor.ts also escapes some of the same card fields into element content of that parsed document. That is a different consumer with different rules — it is explicitly not a consistency argument for re-escaping the main prompt path (the SCOPE comment now says so).


Hardening (so this stops recurring)

  • Renamed the identity function escapeXmlText → passThroughLeaf (+ its callers in scene-context-runtime.ts and the regression). A function named "escapeXmlText" whose body is return value invites the one-line "obviously it should escape" change.
  • CHANGELOG [Unreleased] entry marks the #3108 and "Hardened prompt assembly" escaping entries as superseded for the local single-user model, so the release notes no longer read as evidence that escaping is correct. (Historical entries left intact.)
  • CONTRIBUTING.md decision record ("Prompt Leaf Content Is Verbatim") states the invariant, the threat model, and what stays escaped — something a reviewer can cite when rejecting a re-add.
  • Assembled-prompt canary test feeds a persona and a character description containing <test> + inline HTML through the real assembly path and asserts they arrive verbatim with no &lt;/&amp;/&gt; anywhere. The prior lock test only proved the leaf helper is identity, not the whole path.
  • Renamed the misleading "identity fallback escapes … delimiters" test to "… passes … verbatim" and extended the file-header SCOPE comment.

Validation

  • pnpm check (TypeScript + ESLint + build): passes.
  • pnpm regression:prompt: passes for all prompt-escaping tests, including the new canary and the renamed verbatim tests. (One unrelated, pre-existing failure exists on this tree — the "Professor Mari … public reference … Prose Guardian" agent-catalog completeness check — and reproduces without any change in this PR.)
  • pnpm --filter @marinara-engine/server exec tsx ../../scripts/regressions/open-issues.regression.ts: passes.

Manual verification (please confirm)

  • In Peek Prompt / Assembled Prompt, a persona description containing <test> shows <test> verbatim (not &lt;test>).
  • A character card / lorebook entry using <thinking> or inline HTML reaches the model and renders as authored (roleplay HTML no longer breaks).
  • Example dialogue <START> separators still work, including cards imported with the marker already entity-encoded.
  • Agent-driven features that emit machine-parsed XML (world-state trackers, knowledge/entry catalogs, storyboard sections) still parse correctly — those paths intentionally remain escaped.

Notes

  • Targets staging per the contributor workflow.
  • Tracked by #3766 (from a direct user report with screenshots). Because this PR targets staging rather than the default branch, the Fixes keyword won't auto-close #3766 on merge — the in-pr → fixed-in-staging label flow covers closure when staging merges to main.

Summary by CodeRabbit

  • Bug Fixes
    • Prompt content now preserves angle brackets and inline HTML verbatim, including character and persona details, lorebook entries, memories, scene text, and chat context.
    • Tag-like content such as <thinking> and <scenario> is no longer converted into escaped entities like &lt;...&gt;.
    • Example dialogue markers continue to be recognized correctly while surrounding content remains unchanged.

🔄 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/3765 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 7/18/2026 **Status:** ✅ Merged **Merged:** 7/18/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/prompt-leaf-verbatim-tags` --- ### 📝 Commits (3) - [`b926026`](https://github.com/Pasta-Devs/Marinara-Engine/commit/b926026b8877d1652fb776c110a879ec9cb79a99) fix(prompt): stop escaping angle brackets in prompt leaf content - [`7510d36`](https://github.com/Pasta-Devs/Marinara-Engine/commit/7510d366028918f4d199c49baded75e68e570500) fix(prompt): harden verbatim prompt-leaf contract against re-escaping - [`0ac038e`](https://github.com/Pasta-Devs/Marinara-Engine/commit/0ac038e0a6a7db1e01e5612155a6c67e6de39957) Merge branch 'staging' into fix/prompt-leaf-verbatim-tags ### 📊 Changes **6 files changed** (+194 additions, -53 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+1 -0) 📝 `CONTRIBUTING.md` (+12 -0) 📝 `packages/server/src/services/generation/scene-context-runtime.ts` (+7 -7) 📝 `packages/server/src/services/prompt/prompt-escaping.ts` (+67 -8) 📝 `scripts/regressions/open-issues.regression.ts` (+2 -2) 📝 `scripts/regressions/prompt.regression.ts` (+105 -36) </details> ### 📄 Description ## Linked issue Closes #3766 ## What this does Prompt **leaf** content — character card fields, persona, lorebook entries, memories, scene text, and example dialogue — now reaches the model **verbatim**. Angle-bracket and HTML-style tags (`<thinking>`, `<scenario>`, `<div style="...">`) are passed through exactly as authored instead of arriving at the model as `&lt;thinking&gt;`. This fixes a recurring user-visible bug: `<test>` typed in a persona or card showed up as `&lt;test>` in Peek Prompt / the assembled prompt, roleplay HTML formatting broke, the editor displayed raw `&lt;`, and tokens were wasted on entities. The change itself is one line of behavior (the XML leaf path stops HTML-escaping). The bulk of this PR is **hardening** so it stops getting silently re-broken. --- ## Why this regression keeps happening Leaf-content escaping has flip-flopped across many versions. The reason it keeps coming back is that **the guard was never actually deleted before this branch** — every prior "fix" only carved out an *exception* rather than removing the escaping: - the escaper was born escaping all of `&`, `<`, `>`; - one change dropped only `>`, a later one re-added `>`, another dropped it again; - `<START>` example-dialogue carve-outs were added (#3441, #3623); - a display-layer band-aid decoded `&lt;font…&gt;` before rendering (#3206) so the escaping merely *looked* harmless while the model still received the mangled `&lt;`. The `<` escaping survived all of that. Because the underlying injection-guard framing was never removed, three renewable sources kept regenerating the belief that escaping is correct and kept re-attracting it: 1. **The function name.** `escapeXmlText` reads as "an XML escaper," so making its body escape again looks like a bug fix, not a regression. (There is even a second, unrelated local `escapeXmlText` in `knowledge-router.ts` that legitimately *does* escape — an identical name with opposite behavior.) 2. **The CHANGELOG.** It still declares `<`/`&` escaping deliberate "prompt-boundary safety" (#3108) and "Hardened prompt assembly … by escaping untrusted character/persona card text," with no countervailing entry. Release notes are the first thing a contributor reads, and they argued *for* escaping. 3. **No recorded decision.** `CONTRIBUTING.md` never mentioned this; the only rationale lived in a file header a re-escape PR's author might never open. This PR is the first *true* removal, and it closes all three sources (see Hardening below). --- ## Why verbatim is the correct final state **Threat model.** Marinara Engine is local, single-user roleplay. The person who authors or imports a card is the same person the card would "attack." The worst realistic outcome of an unescaped `<system>`-looking tag is the model role-playing something odd — which the user sees immediately in their own chat and fixes by editing their own card. That is a rare, self-inflicted, self-correcting annoyance, not a security boundary. Escaping traded that non-threat for a *constant, real* harm: the very common, legitimate use of angle-bracket/HTML tags in cards and lorebooks arrived mangled. **The model is not an XML parser.** Escaping treated the LLM as if a stray `<` could "break out" of a structural element the way it would in a real XML document. An LLM reads tokens; there is no parser to break out of. Turning `<` into `&lt;` closes no injection surface — it only corrupts text. **Structure is not at risk.** The framework's own section wrappers (`<description>…</description>`, `<last_message>…`, etc.) are emitted by `wrapContent` *around* leaf content, from fixed section names, independent of what the content contains. Verbatim leaf content therefore cannot alter the structural tags — it only changes what sits inside them, as intended. **Honest residual limitation.** Verbatim does mean a self-authored/imported card can paste a convincing framework-style closing tag plus fake instructions into context. In a local single-user tool that is self-inflicted and self-fixable, and it is no stronger than writing those instructions in plain prose (which the model reads either way). If a future multi-tenant or shared-marketplace deployment ever changes the threat model, the right response is a validation/consent step at the **import boundary**, not silent per-token escaping of everyone's content at prompt-assembly time. --- ## What deliberately stays escaped (out of scope) The agent value/attribute escapers are **unchanged** and must stay: - `escapeXml` / `escapeXmlAttribute` in `agent-executor.ts`, the local escaper in `knowledge-router.ts`, and the storyboard/attachment escapers escape dynamic values into XML **attributes** and into strict, **machine-parsed** agent documents (world-state, entry catalogs, `<turn_sections>`, `<attached_file name="…">`). Those are parsed downstream, where a stray `"` or `<` genuinely breaks an attribute or element. Note that `agent-executor.ts` also escapes some of the *same* card fields into element content of that parsed document. That is a different consumer with different rules — it is explicitly **not** a consistency argument for re-escaping the main prompt path (the SCOPE comment now says so). --- ## Hardening (so this stops recurring) - **Renamed the identity function** `escapeXmlText` → `passThroughLeaf` (+ its callers in `scene-context-runtime.ts` and the regression). A function named "escapeXmlText" whose body is `return value` invites the one-line "obviously it should escape" change. - **CHANGELOG [Unreleased] entry** marks the #3108 and "Hardened prompt assembly" escaping entries as **superseded** for the local single-user model, so the release notes no longer read as evidence that escaping is correct. (Historical entries left intact.) - **CONTRIBUTING.md decision record** ("Prompt Leaf Content Is Verbatim") states the invariant, the threat model, and what stays escaped — something a reviewer can cite when rejecting a re-add. - **Assembled-prompt canary test** feeds a persona **and** a character description containing `<test>` + inline HTML through the real assembly path and asserts they arrive verbatim with no `&lt;`/`&amp;`/`&gt;` anywhere. The prior lock test only proved the leaf helper is identity, not the whole path. - **Renamed the misleading** "identity fallback escapes … delimiters" test to "… passes … verbatim" and extended the file-header SCOPE comment. --- ## Validation - `pnpm check` (TypeScript + ESLint + build): passes. - `pnpm regression:prompt`: passes for all prompt-escaping tests, including the new canary and the renamed verbatim tests. (One unrelated, pre-existing failure exists on this tree — the "Professor Mari … public reference … Prose Guardian" agent-catalog completeness check — and reproduces without any change in this PR.) - `pnpm --filter @marinara-engine/server exec tsx ../../scripts/regressions/open-issues.regression.ts`: passes. ## Manual verification (please confirm) - [x] In Peek Prompt / Assembled Prompt, a persona description containing `<test>` shows `<test>` verbatim (not `&lt;test>`). - [x] A character card / lorebook entry using `<thinking>` or inline HTML reaches the model and renders as authored (roleplay HTML no longer breaks). - [x] Example dialogue `<START>` separators still work, including cards imported with the marker already entity-encoded. - [x] Agent-driven features that emit machine-parsed XML (world-state trackers, knowledge/entry catalogs, storyboard sections) still parse correctly — those paths intentionally remain escaped. ## Notes - Targets `staging` per the contributor workflow. - Tracked by #3766 (from a direct user report with screenshots). Because this PR targets `staging` rather than the default branch, the `Fixes` keyword won't auto-close #3766 on merge — the `in-pr` → `fixed-in-staging` label flow covers closure when staging merges to main. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Prompt content now preserves angle brackets and inline HTML verbatim, including character and persona details, lorebook entries, memories, scene text, and chat context. * Tag-like content such as `<thinking>` and `<scenario>` is no longer converted into escaped entities like `&lt;...&gt;`. * Example dialogue markers continue to be recognized correctly while surrounding content remains unchanged. <!-- 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:07:00 +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#6092
No description provided.