[GH-ISSUE #2937] [Issue]: Regex scripts: no controllable run order for new/imported scripts, import order lost, cross-scope reorder can flip order, invalid depth/placement silently disable a script #1514

Closed
opened 2026-10-21 05:37:44 +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/2937

Originally assigned to: @SpicyMarinara on GitHub.

Several related problems in the regex script engine around execution order and silent self-disabling. Each is independently reproducible. Verified against v2.0.6.

Regex scripts run in ascending order, but new scripts all default to order = 0, so there is no way to control the run order of multiple scripts except by manually drag-reordering them. A few code paths make this worse (import loses file order, a global reorder can shift scoped scripts' relative position), and two settings can be saved in states that make a script never run with no warning.


Bug 1 — New and imported scripts all get order 0, so chained scripts have no controllable run order

How to reproduce (try it yourself):

  1. In the Presets panel, create two GLOBAL regex scripts using the editor, leaving the "order" field untouched (both save with order = 0):
    • Script A: find foo → replace BAR, placement AI output
    • Script B: find BAR → replace baz, placement AI output
  2. Send/display a message containing foo.

You'll see: the output is either BAR (B ran first, so its BAR→baz saw nothing) or baz (A ran first, then B), depending purely on creation tie-order. You cannot choose which without manually drag-reordering the two scripts.
Expected: a way to set run order at creation, or a deterministic, documented tiebreaker (e.g. creation time), so a dependent chain is controllable without drag-and-drop.

Where it is: packages/server/src/services/storage/regex-scripts.storage.ts:13 (list() orders by asc(order) only — no secondary tiebreaker) and :35 (order: input.order ?? 0 on create). New scripts in the editor default to 0 at packages/client/src/components/agents/RegexScriptEditor.tsx:219 (setLocalOrder(0)).

What's happening: Every newly created script gets order = 0. With all orders tied, the only ordering signal is whatever the store returns for equal-order rows; the user has no field to influence it at creation time. Drag-reorder is the only escape hatch.

Suggested fix: On create, assign order = max(existing order) + step like prompts and lorebooks already do (packages/server/src/services/storage/prompts.storage.ts:400/:412 use maxOrder + 100), and/or add a stable secondary sort (e.g. createdAt) in list().


Bug 2 — Bulk regex-file import assigns every entry order 0, losing file order

How to reproduce (try it yourself):

  1. Create a JSON file:
    {"regexScripts":[
      {"name":"A","findRegex":"foo","replaceString":"BAR","placement":["ai_output"]},
      {"name":"B","findRegex":"BAR","replaceString":"baz","placement":["ai_output"]}
    ]}
    
    (no order keys)
  2. Import it via the Presets panel regex import (also reproducible via the character Advanced-tab regex import).

You'll see: both scripts land with order = 0, so their relative run order is uncontrollable — the file's authoring order is discarded.
Expected: imported scripts keep their file/array order (A before B).

Where it is: The import normalizer defaults order to 0 when the entry has none — packages/client/src/components/panels/PresetsPanel.tsx:188 and the same in packages/client/src/components/characters/CharacterRegexSection.tsx:106 (order: typeof entry.order === "number" ? entry.order : 0). The import loop creates each entry one by one (PresetsPanel.tsx:408-413) and the server create does not assign a max-order (regex-scripts.storage.ts:35).

What's happening: Files exported without explicit order keys (and the in-app exporter does not write them) all default to 0 on import, collapsing the file order. Note the server ST-card importer does NOT have this problem — it preserves order via order: index (packages/server/src/services/import/st-character.importer.ts:158). Only the client regex-file import paths drop it.

Suggested fix: In the import loop, assign incrementing orders (baseMaxOrder + index) instead of defaulting to 0, mirroring st-character.importer.ts:158.


Bug 3 — Reordering global scripts can flip their position relative to a character-scoped script

How to reproduce (try it yourself):

  1. Set up: global script A (order 10), a character-scoped script S (order 5, targeting the active character), global script B (order 20).
  2. In the Presets regex list (which shows global scripts only), drag B above A.

You'll see: the reorder reindexes only the global scripts it can see — B becomes order 0, A becomes order 1 — while S stays at order 5. Now for that character the engine runs B, A (orders 0, 1) before S (order 5). Previously S (5) ran before A (10) and B (20).
Expected: reordering global scripts should not silently change where a scoped script falls in the combined run order, or the reorder should renumber within a consistent global+scoped sequence.

Where it is: The Presets list filters to global scripts (packages/client/src/components/panels/PresetsPanel.tsx:285-291) and the reorder handler sends only those global ids (:482-493). reorder() then sets each passed script's order to its array index (packages/server/src/services/storage/regex-scripts.storage.ts:64-72). At apply time there is a single ascending-order pass over the combined list with scoped scripts gated by targetCharacterId but interleaved by order (packages/server/src/services/regex/regex-application.ts:93-103; call site generate.routes.ts:2043-2046).

What's happening: Because the global-only reorder renumbers globals starting from 0 without considering scoped scripts that share the same global order space, a global script can be pushed numerically below a scoped script it used to run after. Separately, reorder() uses Promise.all with no transaction (regex-scripts.storage.ts:66), so a partial failure could leave a half-renumbered set (other storages use db.transaction, e.g. chat-folders.storage.ts). This is low-probability — it needs a mixed global+scoped set and the user noticing the scoped script moved.

Suggested fix: Renumber against the full ordered set (global + scoped) so relative positions are preserved, and wrap the per-row updates in a single db.transaction.


Bug 4 — Setting Depth Range Min > Max saves silently and makes the script never run

How to reproduce (try it yourself):

  1. In the regex script editor set Depth Range Min = 5, Max = 2 and save (it's accepted, no error).
  2. Use the script on any message.

You'll see: the script never applies to any message, with no warning.
Expected: the editor should reject or warn on Min > Max, or treat it as a no-op range explicitly.

Where it is: packages/shared/src/schemas/regex.schema.ts:29-30 defines minDepth/maxDepth as independent nullable ints with no cross-field check. Apply logic skips when depth < minDepth OR depth > maxDepth (packages/server/src/services/regex/regex-application.ts:107-108; display side packages/client/src/hooks/use-apply-regex.ts:99-100). The editor sets the two fields independently with no comparison (packages/client/src/components/agents/RegexScriptEditor.tsx:776-798).

What's happening: With Min=5/Max=2, every possible depth fails one of the two checks (depths 0–4 are < 5, depths 3+ are > 2), so the loop continues for all depths. The script is effectively disabled, but it still shows as enabled.

Suggested fix: Add a superRefine to the schema rejecting minDepth > maxDepth, and/or validate it in the editor before save.


Bug 5 — A regex script with empty placement is silently skipped for every message, and backup restore can create one

How to reproduce (try it yourself):

  1. Take a profile backup, edit the snapshot so a regex_scripts row has placement = '' (or '[]') while enabled = 'true' and promptOnly = 'false', and restore it.
  2. The script shows as enabled in the UI.

You'll see: the script never applies to any message (prompt or display side), with no log or warning.
Expected: restore should validate rows (reject/normalize empty placement) the same way the in-app create API does.

Where it is: parsePlacement('') returns [] (packages/server/src/services/regex/regex-application.ts:42-53), and :96 skips the script because [].includes(placement) is always false. Backup restore inserts each row verbatim, only blanking apiKeyEncrypted, with no Zod validation (packages/server/src/routes/backup.routes.ts:694-703), and regex_scripts is a file-backed table that goes through this path (packages/server/src/db/file-backed-store.ts:178). The API create path's placement.min(1) (regex.schema.ts:24) is bypassed on restore.

What's happening: The create API enforces at least one placement, but the backup restore path does not run that validation, so a hand-edited or corrupted snapshot can introduce an enabled-but-inert script. Hard to hit without editing a backup or a direct DB write; the normal in-app path and ST importer both reject/skip empty placement.

Suggested fix: Validate restored regex_scripts rows against the regex schema (or at least require a non-empty placement) during backup restore.


Bug 6 — Importing a regex file with non-1/2 ST placement numbers silently becomes AI output

How to reproduce (try it yourself):

  1. Create a JSON file:
    {"regexScripts":[{"scriptName":"WI script","findRegex":"/foo/g","replaceString":"bar","placement":[5]}]}
    
    (5 = SillyTavern WORLD_INFO; also 0 = markdown display, 3 = slash command)
  2. Import it via the Presets panel regex import (not as a full character card).

You'll see: the [5] placement maps to nothing, gets filtered out, and falls back to ['ai_output'] — producing an enabled, content-affecting AI-output script, with no warning. Any markdownOnly/runOnEdit-style fields are silently dropped.
Expected: unmapped placements should skip the script or warn, not coerce it into an AI-output transform.

Where it is: The client import normalizer maps only 1→user_input and 2→ai_output, filters out anything else, then defaults to ['ai_output'] when nothing survives — packages/client/src/components/panels/PresetsPanel.tsx:170-184 (and the same in packages/client/src/components/characters/CharacterRegexSection.tsx:89-103). The placement schema only supports ai_output/user_input (regex.schema.ts:7).

What's happening: A placement the engine can't represent (display-only, slash-command, world-info) gets coerced into a real AI-output transform that mutates message content. Note the server ST-character-card importer is NOT affected — convertStPlacements returns null for unknown-only placement arrays and the importer skips those scripts (packages/server/src/services/import/st-character.importer.ts:105-113, :144). This issue applies only to the client regex-file import path.

Suggested fix: On the client import paths, skip (or surface a warning for) entries whose placements don't map to a supported value instead of falling back to ['ai_output'].


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/2937 Originally assigned to: @SpicyMarinara on GitHub. Several related problems in the regex script engine around **execution order** and **silent self-disabling**. Each is independently reproducible. Verified against v2.0.6. Regex scripts run in ascending `order`, but new scripts all default to `order = 0`, so there is no way to control the run order of multiple scripts except by manually drag-reordering them. A few code paths make this worse (import loses file order, a global reorder can shift scoped scripts' relative position), and two settings can be saved in states that make a script never run with no warning. --- ### Bug 1 — New and imported scripts all get order 0, so chained scripts have no controllable run order **How to reproduce (try it yourself):** 1. In the Presets panel, create two GLOBAL regex scripts using the editor, leaving the "order" field untouched (both save with order = 0): - Script A: find `foo` → replace `BAR`, placement AI output - Script B: find `BAR` → replace `baz`, placement AI output 2. Send/display a message containing `foo`. You'll see: the output is either `BAR` (B ran first, so its `BAR→baz` saw nothing) or `baz` (A ran first, then B), depending purely on creation tie-order. You cannot choose which without manually drag-reordering the two scripts. Expected: a way to set run order at creation, or a deterministic, documented tiebreaker (e.g. creation time), so a dependent chain is controllable without drag-and-drop. **Where it is:** `packages/server/src/services/storage/regex-scripts.storage.ts:13` (`list()` orders by `asc(order)` only — no secondary tiebreaker) and `:35` (`order: input.order ?? 0` on create). New scripts in the editor default to 0 at `packages/client/src/components/agents/RegexScriptEditor.tsx:219` (`setLocalOrder(0)`). **What's happening:** Every newly created script gets `order = 0`. With all orders tied, the only ordering signal is whatever the store returns for equal-order rows; the user has no field to influence it at creation time. Drag-reorder is the only escape hatch. **Suggested fix:** On create, assign `order = max(existing order) + step` like prompts and lorebooks already do (`packages/server/src/services/storage/prompts.storage.ts:400`/`:412` use `maxOrder + 100`), and/or add a stable secondary sort (e.g. `createdAt`) in `list()`. --- ### Bug 2 — Bulk regex-file import assigns every entry order 0, losing file order **How to reproduce (try it yourself):** 1. Create a JSON file: ```json {"regexScripts":[ {"name":"A","findRegex":"foo","replaceString":"BAR","placement":["ai_output"]}, {"name":"B","findRegex":"BAR","replaceString":"baz","placement":["ai_output"]} ]} ``` (no `order` keys) 2. Import it via the Presets panel regex import (also reproducible via the character Advanced-tab regex import). You'll see: both scripts land with `order = 0`, so their relative run order is uncontrollable — the file's authoring order is discarded. Expected: imported scripts keep their file/array order (A before B). **Where it is:** The import normalizer defaults order to 0 when the entry has none — `packages/client/src/components/panels/PresetsPanel.tsx:188` and the same in `packages/client/src/components/characters/CharacterRegexSection.tsx:106` (`order: typeof entry.order === "number" ? entry.order : 0`). The import loop creates each entry one by one (`PresetsPanel.tsx:408-413`) and the server create does not assign a max-order (`regex-scripts.storage.ts:35`). **What's happening:** Files exported without explicit `order` keys (and the in-app exporter does not write them) all default to 0 on import, collapsing the file order. Note the server ST-card importer does NOT have this problem — it preserves order via `order: index` (`packages/server/src/services/import/st-character.importer.ts:158`). Only the client regex-file import paths drop it. **Suggested fix:** In the import loop, assign incrementing orders (`baseMaxOrder + index`) instead of defaulting to 0, mirroring `st-character.importer.ts:158`. --- ### Bug 3 — Reordering global scripts can flip their position relative to a character-scoped script **How to reproduce (try it yourself):** 1. Set up: global script A (order 10), a character-scoped script S (order 5, targeting the active character), global script B (order 20). 2. In the Presets regex list (which shows global scripts only), drag B above A. You'll see: the reorder reindexes only the global scripts it can see — B becomes order 0, A becomes order 1 — while S stays at order 5. Now for that character the engine runs B, A (orders 0, 1) **before** S (order 5). Previously S (5) ran before A (10) and B (20). Expected: reordering global scripts should not silently change where a scoped script falls in the combined run order, or the reorder should renumber within a consistent global+scoped sequence. **Where it is:** The Presets list filters to global scripts (`packages/client/src/components/panels/PresetsPanel.tsx:285-291`) and the reorder handler sends only those global ids (`:482-493`). `reorder()` then sets each passed script's `order` to its array index (`packages/server/src/services/storage/regex-scripts.storage.ts:64-72`). At apply time there is a single ascending-order pass over the combined list with scoped scripts gated by `targetCharacterId` but interleaved by order (`packages/server/src/services/regex/regex-application.ts:93-103`; call site `generate.routes.ts:2043-2046`). **What's happening:** Because the global-only reorder renumbers globals starting from 0 without considering scoped scripts that share the same global order space, a global script can be pushed numerically below a scoped script it used to run after. Separately, `reorder()` uses `Promise.all` with no transaction (`regex-scripts.storage.ts:66`), so a partial failure could leave a half-renumbered set (other storages use `db.transaction`, e.g. `chat-folders.storage.ts`). This is low-probability — it needs a mixed global+scoped set and the user noticing the scoped script moved. **Suggested fix:** Renumber against the full ordered set (global + scoped) so relative positions are preserved, and wrap the per-row updates in a single `db.transaction`. --- ### Bug 4 — Setting Depth Range Min > Max saves silently and makes the script never run **How to reproduce (try it yourself):** 1. In the regex script editor set Depth Range **Min = 5, Max = 2** and save (it's accepted, no error). 2. Use the script on any message. You'll see: the script never applies to any message, with no warning. Expected: the editor should reject or warn on Min > Max, or treat it as a no-op range explicitly. **Where it is:** `packages/shared/src/schemas/regex.schema.ts:29-30` defines `minDepth`/`maxDepth` as independent nullable ints with no cross-field check. Apply logic skips when `depth < minDepth` OR `depth > maxDepth` (`packages/server/src/services/regex/regex-application.ts:107-108`; display side `packages/client/src/hooks/use-apply-regex.ts:99-100`). The editor sets the two fields independently with no comparison (`packages/client/src/components/agents/RegexScriptEditor.tsx:776-798`). **What's happening:** With Min=5/Max=2, every possible depth fails one of the two checks (depths 0–4 are `< 5`, depths 3+ are `> 2`), so the loop `continue`s for all depths. The script is effectively disabled, but it still shows as enabled. **Suggested fix:** Add a `superRefine` to the schema rejecting `minDepth > maxDepth`, and/or validate it in the editor before save. --- ### Bug 5 — A regex script with empty placement is silently skipped for every message, and backup restore can create one **How to reproduce (try it yourself):** 1. Take a profile backup, edit the snapshot so a `regex_scripts` row has `placement = ''` (or `'[]'`) while `enabled = 'true'` and `promptOnly = 'false'`, and restore it. 2. The script shows as enabled in the UI. You'll see: the script never applies to any message (prompt or display side), with no log or warning. Expected: restore should validate rows (reject/normalize empty placement) the same way the in-app create API does. **Where it is:** `parsePlacement('')` returns `[]` (`packages/server/src/services/regex/regex-application.ts:42-53`), and `:96` skips the script because `[].includes(placement)` is always false. Backup restore inserts each row verbatim, only blanking `apiKeyEncrypted`, with no Zod validation (`packages/server/src/routes/backup.routes.ts:694-703`), and `regex_scripts` is a file-backed table that goes through this path (`packages/server/src/db/file-backed-store.ts:178`). The API create path's `placement.min(1)` (`regex.schema.ts:24`) is bypassed on restore. **What's happening:** The create API enforces at least one placement, but the backup restore path does not run that validation, so a hand-edited or corrupted snapshot can introduce an enabled-but-inert script. Hard to hit without editing a backup or a direct DB write; the normal in-app path and ST importer both reject/skip empty placement. **Suggested fix:** Validate restored `regex_scripts` rows against the regex schema (or at least require a non-empty placement) during backup restore. --- ### Bug 6 — Importing a regex file with non-1/2 ST placement numbers silently becomes AI output **How to reproduce (try it yourself):** 1. Create a JSON file: ```json {"regexScripts":[{"scriptName":"WI script","findRegex":"/foo/g","replaceString":"bar","placement":[5]}]} ``` (5 = SillyTavern WORLD_INFO; also 0 = markdown display, 3 = slash command) 2. Import it via the Presets panel regex import (not as a full character card). You'll see: the `[5]` placement maps to nothing, gets filtered out, and falls back to `['ai_output']` — producing an enabled, content-affecting AI-output script, with no warning. Any `markdownOnly`/`runOnEdit`-style fields are silently dropped. Expected: unmapped placements should skip the script or warn, not coerce it into an AI-output transform. **Where it is:** The client import normalizer maps only `1→user_input` and `2→ai_output`, filters out anything else, then defaults to `['ai_output']` when nothing survives — `packages/client/src/components/panels/PresetsPanel.tsx:170-184` (and the same in `packages/client/src/components/characters/CharacterRegexSection.tsx:89-103`). The placement schema only supports `ai_output`/`user_input` (`regex.schema.ts:7`). **What's happening:** A placement the engine can't represent (display-only, slash-command, world-info) gets coerced into a real AI-output transform that mutates message content. Note the server ST-character-card importer is NOT affected — `convertStPlacements` returns `null` for unknown-only placement arrays and the importer skips those scripts (`packages/server/src/services/import/st-character.importer.ts:105-113, :144`). This issue applies only to the client regex-**file** import path. **Suggested fix:** On the client import paths, skip (or surface a warning for) entries whose placements don't map to a supported value instead of falling back to `['ai_output']`. --- AI-investigated against v2.0.6; verify the reproduction before fixing.
Author
Owner

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

Addressed in the staging fixes: regex script listing now has stable tie-breakers, new orderless scripts auto-append after the current max order, imports preserve file sequence past existing scripts, global reorder is transactional and renumbers the full ordered set without scrambling scoped rows, minDepth > maxDepth is rejected, invalid restored placements are logged, and unsupported SillyTavern placements are skipped with a visible import reason.

<!-- gh-comment-id:4827507749 --> @SpicyMarinara commented on GitHub (Jun 28, 2026): Addressed in the staging fixes: regex script listing now has stable tie-breakers, new orderless scripts auto-append after the current max order, imports preserve file sequence past existing scripts, global reorder is transactional and renumbers the full ordered set without scrambling scoped rows, minDepth > maxDepth is rejected, invalid restored placements are logged, and unsupported SillyTavern placements are skipped with a visible import reason.
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:4827556945 --> @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.
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#1514
No description provided.