[GH-ISSUE #2931] [Issue]: Regex scripts that use {{user}}/{{char}} in the find or replace box break when the name (or replacement value) contains special characters #1508

Closed
opened 2026-10-21 05:37:31 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @kolacheee on GitHub (Jun 28, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2931

Originally assigned to: @SpicyMarinara on GitHub.

Regex scripts let you put macros like {{user}} or {{char}} inside the Find box and the Replace box. At save time these macros are blanked out before the safety check, but at run time the real name/value is dropped in literally — with no escaping. So as soon as a persona name, character name, or macro value contains a character that means something special to a regex (parentheses, +, *, braces, $, backslash), the script silently misbehaves: it does nothing, throws an error that's swallowed, matches the wrong text, or mangles the output. None of this surfaces to the user.

All four problems below were reproduced against v2.0.6 by running the actual shared regex modules.


Bug 1 — A macro in the Find box silently stops working when the name has special characters

How to reproduce (try it yourself)

  1. Create a prompt-side regex script: Find = \b{{user}}\b, Replace = REDACTED, placement AI output / user input, enabled. It saves fine.
  2. With persona name Bob, send/preview "Hi I am Bob here." → "Bob" is redacted. (control: works)
  3. Rename the persona to A(B (or Mr. [Smith], Alex (DM)).
  4. Send/preview the same message.

You'll see: the script does nothing — no redaction, no error message.
Expected: it redacts the name, or at least warns that the script can't run.

Where it is — packages/server/src/services/regex/regex-application.ts, applyRegexScriptsToPromptText: line 110 resolves {{user}} into the Find pattern with no escaping, line 114 skips the script if isPatternSafe returns false, line 118 compiles it, line 125 swallows any compile error. The display path in packages/client/src/hooks/use-apply-regex.ts lines 104-106 has the same flaw and doesn't even call isPatternSafe.

What's happening — The name is injected verbatim, so \b{{user}}\b becomes \bA(B\b. That has an unbalanced paren. isPatternSafe("\bA(B\b") returns false (confirmed) → silent skip. A name like A**B passes the safety check but then new RegExp throws "Nothing to repeat" (confirmed), which the catch on line 125 swallows. A name like A+B compiles but A+ is now "one or more A", so it matches the wrong text instead of the literal name.

Suggested fix — Regex-escape resolved macro values before they're spliced into the Find pattern (a \Q…\E-style literal escape on the substituted text), so a name is always matched literally. At minimum, surface a visible warning when a script is skipped because its resolved pattern failed the safety/compile gate, instead of silently doing nothing.


Bug 2 — Macro values in the Replace box get mangled (Windows paths, $, LaTeX)

How to reproduce (try it yourself)

  1. Create a regex script whose Replace box contains a macro that resolves to a Windows path, e.g. Replace = {{user}} where the persona name / value is C:\Users\bob.
  2. Make the Find pattern match somewhere in the text.

You'll see: the output is C:SERS\BOB instead of C:\Users\bob.
Expected: the literal value C:\Users\bob.

Same class of problem: a $& inside the resolved value comes out as the whole matched substring; $1, $`, $', $<name> are also re-interpreted.

Where it is — packages/shared/src/utils/regex-replacement.ts: line 145 resolves the macro first and then feeds the resulting literal string into expandRegexReplacement. Lines 83-115 treat \U \L \E \u \l as case-change commands; line 118 treats $ as the start of a capture token.

What's happening — \U (the \U in C:\Users) is read as "uppercase from here on", which eats the backslash+U and uppercases the rest → C:SERS\BOB (confirmed). The replacement grammar is applied to the resolved macro value, but it should only be applied to the script author's literal Replace string — not to data that a macro produced.

Suggested fix — Expand the \U/$1/etc. replacement tokens against the author's raw Replace string, and substitute macro values in as inert literals (escaped so $ and \U in a value are emitted verbatim). Resolve the token grammar before macro values are injected, not after.


Bug 3 — A script that saved fine is silently dropped at send time, but still runs in the displayed text

How to reproduce (try it yourself)

  1. Save a script with Find = {{user}} (it validates, because the save-time check replaces {{user}} with x).
  2. Set the persona name to D {Brave}.
  3. Send a message that contains that name.

You'll see: in the prompt actually sent to the model the script is skipped (name not transformed), but in the on-screen displayed message it still applies. What you see and what the model sees diverge.
Expected: consistent behavior, or a visible warning — not a silent split.

Where it is — packages/shared/src/schemas/regex.schema.ts line 19 runs isPatternSafe on the macro-stripped placeholder ({{...}} → x); packages/server/src/services/regex/regex-application.ts lines 110-114 run isPatternSafe on the macro-resolved string and continue (skip) on failure. The client display path (use-apply-regex.ts) has no isPatternSafe gate at all, so it never skips.

What's happening — isPatternSafe("x") is true (so it saves) but isPatternSafe("D {Brave}") is false, even though new RegExp("D {Brave}","gi") compiles fine (all confirmed). The safety heuristic reads the {Brave} brace as a malformed {n,m} quantifier. The server skips; the client doesn't — hence the divergence.

Suggested fix — Run the same resolution-then-validation on both paths, and don't reject a resolved pattern that actually compiles. Escaping resolved macro values (Bug 1's fix) also removes the brace problem here. If a script truly can't run, skip it consistently on both prompt and display sides and warn.


Bug 4 — A random macro in the Replace box rolls a fresh value for every match

How to reproduce (try it yourself)

  1. Create a global script: Find = \bHP\b (with the g flag), Replace = {{roll:1d6}}.
  2. Apply it to a message that contains "HP ... HP ... HP".

You'll see: three different roll results, one per "HP".
Expected: a single rolled value stamped in all three places (and matching a single-resolution preview).

Where it is — packages/shared/src/utils/regex-replacement.ts line 145: the macro resolver is called inside the text.replace(regex, callback) per-match callback, so it re-runs for every match. Non-idempotent macros are {{random}}, {{random:a:b}}, {{roll:NdM}}, {{random::a::b}}, {{date}}/{{time}} (macro-engine.ts lines 907/919/926). Confirmed: applyRegexReplacement("a a a", /a/g, "{{x}}", resolver) calls the resolver 3 times.

What's happening — Each match independently re-evaluates the Replace string. For random/dice/time macros that produces a different value each time; for deterministic macros it's wasted re-evaluation. Either way the applied text can disagree with a single-resolution preview.

Suggested fix — Resolve the macros in the Replace string once, before entering the .replace callback, then expand only the capture-token grammar per match. (This pairs naturally with the Bug 2 fix.)


AI-investigated against v2.0.6; verify the reproduction before fixing.

Originally created by @kolacheee on GitHub (Jun 28, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2931 Originally assigned to: @SpicyMarinara on GitHub. Regex scripts let you put macros like `{{user}}` or `{{char}}` inside the **Find** box and the **Replace** box. At save time these macros are blanked out before the safety check, but at run time the real name/value is dropped in literally — with no escaping. So as soon as a persona name, character name, or macro value contains a character that means something special to a regex (parentheses, `+`, `*`, braces, `$`, backslash), the script silently misbehaves: it does nothing, throws an error that's swallowed, matches the wrong text, or mangles the output. None of this surfaces to the user. All four problems below were reproduced against v2.0.6 by running the actual shared regex modules. --- ### Bug 1 — A macro in the Find box silently stops working when the name has special characters **How to reproduce (try it yourself)** 1. Create a prompt-side regex script: Find = `\b{{user}}\b`, Replace = `REDACTED`, placement AI output / user input, enabled. It saves fine. 2. With persona name `Bob`, send/preview "Hi I am Bob here." → "Bob" is redacted. (control: works) 3. Rename the persona to `A(B` (or `Mr. [Smith]`, `Alex (DM)`). 4. Send/preview the same message. **You'll see:** the script does nothing — no redaction, no error message. **Expected:** it redacts the name, or at least warns that the script can't run. **Where it is** — `packages/server/src/services/regex/regex-application.ts`, `applyRegexScriptsToPromptText`: line 110 resolves `{{user}}` into the Find pattern with no escaping, line 114 skips the script if `isPatternSafe` returns false, line 118 compiles it, line 125 swallows any compile error. The display path in `packages/client/src/hooks/use-apply-regex.ts` lines 104-106 has the same flaw and doesn't even call `isPatternSafe`. **What's happening** — The name is injected verbatim, so `\b{{user}}\b` becomes `\bA(B\b`. That has an unbalanced paren. `isPatternSafe("\bA(B\b")` returns false (confirmed) → silent skip. A name like `A**B` passes the safety check but then `new RegExp` throws "Nothing to repeat" (confirmed), which the catch on line 125 swallows. A name like `A+B` compiles but `A+` is now "one or more A", so it matches the wrong text instead of the literal name. **Suggested fix** — Regex-escape resolved macro values before they're spliced into the Find pattern (a `\Q…\E`-style literal escape on the substituted text), so a name is always matched literally. At minimum, surface a visible warning when a script is skipped because its resolved pattern failed the safety/compile gate, instead of silently doing nothing. --- ### Bug 2 — Macro values in the Replace box get mangled (Windows paths, `$`, LaTeX) **How to reproduce (try it yourself)** 1. Create a regex script whose Replace box contains a macro that resolves to a Windows path, e.g. Replace = `{{user}}` where the persona name / value is `C:\Users\bob`. 2. Make the Find pattern match somewhere in the text. **You'll see:** the output is `C:SERS\BOB` instead of `C:\Users\bob`. **Expected:** the literal value `C:\Users\bob`. Same class of problem: a `$&` inside the resolved value comes out as the whole matched substring; `$1`, `` $` ``, `$'`, `$<name>` are also re-interpreted. **Where it is** — `packages/shared/src/utils/regex-replacement.ts`: line 145 resolves the macro **first** and then feeds the resulting literal string into `expandRegexReplacement`. Lines 83-115 treat `\U \L \E \u \l` as case-change commands; line 118 treats `$` as the start of a capture token. **What's happening** — `\U` (the `\U` in `C:\Users`) is read as "uppercase from here on", which eats the backslash+`U` and uppercases the rest → `C:SERS\BOB` (confirmed). The replacement grammar is applied to the resolved macro value, but it should only be applied to the script author's literal Replace string — not to data that a macro produced. **Suggested fix** — Expand the `\U`/`$1`/etc. replacement tokens against the author's *raw* Replace string, and substitute macro values in as inert literals (escaped so `$` and `\U` in a value are emitted verbatim). Resolve the token grammar before macro values are injected, not after. --- ### Bug 3 — A script that saved fine is silently dropped at send time, but still runs in the displayed text **How to reproduce (try it yourself)** 1. Save a script with Find = `{{user}}` (it validates, because the save-time check replaces `{{user}}` with `x`). 2. Set the persona name to `D {Brave}`. 3. Send a message that contains that name. **You'll see:** in the prompt actually sent to the model the script is skipped (name not transformed), but in the on-screen displayed message it still applies. What you see and what the model sees diverge. **Expected:** consistent behavior, or a visible warning — not a silent split. **Where it is** — `packages/shared/src/schemas/regex.schema.ts` line 19 runs `isPatternSafe` on the macro-stripped placeholder (`{{...}}` → `x`); `packages/server/src/services/regex/regex-application.ts` lines 110-114 run `isPatternSafe` on the macro-**resolved** string and `continue` (skip) on failure. The client display path (`use-apply-regex.ts`) has no `isPatternSafe` gate at all, so it never skips. **What's happening** — `isPatternSafe("x")` is true (so it saves) but `isPatternSafe("D {Brave}")` is false, even though `new RegExp("D {Brave}","gi")` compiles fine (all confirmed). The safety heuristic reads the ` {Brave}` brace as a malformed `{n,m}` quantifier. The server skips; the client doesn't — hence the divergence. **Suggested fix** — Run the same resolution-then-validation on both paths, and don't reject a resolved pattern that actually compiles. Escaping resolved macro values (Bug 1's fix) also removes the brace problem here. If a script truly can't run, skip it consistently on **both** prompt and display sides and warn. --- ### Bug 4 — A random macro in the Replace box rolls a fresh value for every match **How to reproduce (try it yourself)** 1. Create a global script: Find = `\bHP\b` (with the `g` flag), Replace = `{{roll:1d6}}`. 2. Apply it to a message that contains "HP ... HP ... HP". **You'll see:** three different roll results, one per "HP". **Expected:** a single rolled value stamped in all three places (and matching a single-resolution preview). **Where it is** — `packages/shared/src/utils/regex-replacement.ts` line 145: the macro resolver is called **inside** the `text.replace(regex, callback)` per-match callback, so it re-runs for every match. Non-idempotent macros are `{{random}}`, `{{random:a:b}}`, `{{roll:NdM}}`, `{{random::a::b}}`, `{{date}}`/`{{time}}` (`macro-engine.ts` lines 907/919/926). Confirmed: `applyRegexReplacement("a a a", /a/g, "{{x}}", resolver)` calls the resolver 3 times. **What's happening** — Each match independently re-evaluates the Replace string. For random/dice/time macros that produces a different value each time; for deterministic macros it's wasted re-evaluation. Either way the applied text can disagree with a single-resolution preview. **Suggested fix** — Resolve the macros in the Replace string once, before entering the `.replace` callback, then expand only the capture-token grammar per match. (This pairs naturally with the Bug 2 fix.) --- AI-investigated against v2.0.6; verify the reproduction before fixing.
Author
Owner

@kolacheee commented on GitHub (Jun 28, 2026):

Re-verified this against v2.0.6 (read the code + reproduced each part) and rewrote the description in plain language with concrete, try-it-yourself reproduction steps. Any original claims I could not actually reproduce were dropped (and called out at the end where relevant). Should be much easier to follow and confirm now — sorry the first version was so dense.

<!-- gh-comment-id:4827556709 --> @kolacheee commented on GitHub (Jun 28, 2026): Re-verified this against v2.0.6 (read the code + reproduced each part) and rewrote the description in plain language with concrete, try-it-yourself reproduction steps. Any original claims I could not actually reproduce were dropped (and called out at the end where relevant). Should be much easier to follow and confirm now — sorry the first version was so dense.
Author
Owner

@SpicyMarinara commented on GitHub (Jun 28, 2026):

Fixed on staging: regex Find macro values are now escaped as literal text, Replace macro values are substituted as inert literals, and Replace macros resolve once per regex application instead of once per match. Added prompt regression coverage for special-character names, literal Windows-path replacement values, and repeated random replacements. Validation: pnpm regression:prompt; pnpm check.

<!-- gh-comment-id:4827607966 --> @SpicyMarinara commented on GitHub (Jun 28, 2026): Fixed on staging: regex Find macro values are now escaped as literal text, Replace macro values are substituted as inert literals, and Replace macros resolve once per regex application instead of once per match. Added prompt regression coverage for special-character names, literal Windows-path replacement values, and repeated random replacements. Validation: pnpm regression:prompt; pnpm check.
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#1508
No description provided.