[GH-ISSUE #2693] [Issue]: Lorebook activation gates fire wrong — probability re-rolled on recursion, cooldown ticks during sticky, deterministic group selection, gt/lt NaN passes #1338

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

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

Originally assigned to: @SpicyMarinara on GitHub.

Summary

Four lorebook activation gates fire entries incorrectly: (a) the probability gate is re-rolled fresh on every recursion pass, inflating activation for <100% entries; (b) cooldown counts down during the sticky window, so cooldown expires earlier than configured; (c) inclusion-group selection is deterministic max-weight (not SillyTavern's weighted-random), so low-weight group members can never fire; (d) numeric gt/lt activation conditions pass when the game-state field is missing/non-numeric (a NaN comparison never returns false).

Expected behavior

Probability should be rolled once per generation; cooldown should block for exactly its configured count regardless of sticky; group members should be selectable by weight (not permanently excluded); and a numeric gt/lt condition against a missing/non-numeric field should fail (not pass).

Actual behavior

  • (a) Probability re-rolled on recursion. recursiveScan calls scanForActivatedEntries fresh on each depth, and the per-entry probabilityDecisions cache is local to each call. So a <100% entry that failed its roll on the primary pass gets new dice on each recursion pass — extra chances to fire.
  • (b) Cooldown decremented during sticky. In updateTimingStatesForScan, when an entry is not freshly activated, cooldownRemaining and stickyCount are both decremented in the same branch. While a sticky entry is held active (re-activated via the sticky path), its cooldown still ticks down, so cooldown expires earlier than the configured count when sticky+cooldown are both set.
  • (c) Group selection deterministic. applyGroupSelection sorts each group by groupWeight desc then order and keeps only the top entry, discarding the rest. ST inclusion groups pick by weighted probability, so a high-weight member always wins here and low-weight members can never fire.
  • (d) gt/lt NaN. evaluateConditions does parseFloat(fieldValue) <= parseFloat(condition.value) for gt (and the inverse for lt). When the game-state field is missing/non-numeric, parseFloat yields NaN, and NaN <= x is false, so the return false is skipped and the condition passes — the entry fires when its numeric condition can't be evaluated.

How it breaks the pipeline

Code trace (staging @ b826f8f4) — packages/server/src/services/lorebook/keyword-scanner.ts:

  • (a) recursiveScan :537-572 (fresh scanForActivatedEntries per depth); probabilityDecisions is local in scanForActivatedEntries (:417-424); gate passesProbabilityGate :197-202.
  • (b) updateTimingStatesForScan :248-258 (non-activation branch decrements cooldownRemaining and stickyCount together); sticky re-activation at :429-439.
  • (c) applyGroupSelection :318-351 (keeps groupEntries[0] only).
  • (d) evaluateConditions :105-110 (gt/lt parseFloat comparisons; NaN never false).

Steps to reproduce

  • (a) Entry probability=30 with recursion enabled and an activated entry whose content matches it on recursion → it gets multiple 30% rolls across depths, so its effective activation rate exceeds 30%.
  • (b) Entry with sticky=3, cooldown=5; observe the cooldown reaching 0 before 5 messages because it ticked during the 3 sticky messages.
  • (c) Group lore with members A(weight 100) and B(weight 1); A activates every time and B never does, even though ST would pick B ~1% of the time.
  • (d) Entry with activation condition field=hp, operator=gt, value=50 on a chat with no hp in game state → parseFloat("")=NaN, NaN<=50 is false, so the condition passes and the entry fires.

Suggested fix

  • (a) Roll probability once per generation: thread the probabilityDecisions map (or pre-rolled results) through recursiveScan so each entry is decided once across all passes.
  • (b) Do not decrement cooldownRemaining while the entry is held by sticky (only tick cooldown once the sticky window ends), or track them on independent clocks.
  • (c) Implement weighted-random group selection (pick by groupWeight proportionally), matching ST inclusion-group behavior; keep deterministic only as an opt-in.
  • (d) In evaluateConditions, return false for gt/lt when either side is NaN (e.g. if (!Number.isFinite(a) || !Number.isFinite(b)) return false).

Environment

  • Marinara Engine version: 2.0.0 (staging @ b826f8f4)
  • Install type: source
  • OS + version: All (code-level defect, platform-independent)
  • Browser or app shell: All

Additional context

Found via a systematic multi-agent audit of conditional prompt insertion. (a), (b), (d) make entries fire when they shouldn't; (c) prevents low-weight entries from ever firing. All four live in the lorebook scanner. Part of a set of lorebook-triggering issues filed together.

Template check

Please uncheck (untick) the box below before submitting so we know you read the template. It is intentionally pre-checked:

  • I DID NOT read this template and provide the requested details.
Originally created by @kolacheee on GitHub (Jun 21, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2693 Originally assigned to: @SpicyMarinara on GitHub. ## Summary Four lorebook activation gates fire entries incorrectly: **(a)** the probability gate is re-rolled fresh on every recursion pass, inflating activation for `<100%` entries; **(b)** cooldown counts down during the sticky window, so cooldown expires earlier than configured; **(c)** inclusion-group selection is deterministic max-weight (not SillyTavern's weighted-random), so low-weight group members can never fire; **(d)** numeric `gt`/`lt` activation conditions pass when the game-state field is missing/non-numeric (a NaN comparison never returns false). ## Expected behavior Probability should be rolled once per generation; cooldown should block for exactly its configured count regardless of sticky; group members should be selectable by weight (not permanently excluded); and a numeric `gt`/`lt` condition against a missing/non-numeric field should fail (not pass). ## Actual behavior - **(a) Probability re-rolled on recursion.** `recursiveScan` calls `scanForActivatedEntries` fresh on each depth, and the per-entry `probabilityDecisions` cache is local to each call. So a `<100%` entry that failed its roll on the primary pass gets new dice on each recursion pass — extra chances to fire. - **(b) Cooldown decremented during sticky.** In `updateTimingStatesForScan`, when an entry is *not* freshly activated, `cooldownRemaining` and `stickyCount` are both decremented in the same branch. While a sticky entry is held active (re-activated via the sticky path), its cooldown still ticks down, so cooldown expires earlier than the configured count when sticky+cooldown are both set. - **(c) Group selection deterministic.** `applyGroupSelection` sorts each group by `groupWeight` desc then `order` and keeps **only the top entry**, discarding the rest. ST inclusion groups pick by weighted probability, so a high-weight member always wins here and low-weight members can never fire. - **(d) gt/lt NaN.** `evaluateConditions` does `parseFloat(fieldValue) <= parseFloat(condition.value)` for `gt` (and the inverse for `lt`). When the game-state field is missing/non-numeric, `parseFloat` yields `NaN`, and `NaN <= x` is `false`, so the `return false` is skipped and the condition **passes** — the entry fires when its numeric condition can't be evaluated. ## How it breaks the pipeline Code trace (staging @ `b826f8f4`) — `packages/server/src/services/lorebook/keyword-scanner.ts`: - (a) `recursiveScan` `:537-572` (fresh `scanForActivatedEntries` per depth); `probabilityDecisions` is local in `scanForActivatedEntries` (`:417-424`); gate `passesProbabilityGate` `:197-202`. - (b) `updateTimingStatesForScan` `:248-258` (non-activation branch decrements `cooldownRemaining` and `stickyCount` together); sticky re-activation at `:429-439`. - (c) `applyGroupSelection` `:318-351` (keeps `groupEntries[0]` only). - (d) `evaluateConditions` `:105-110` (`gt`/`lt` `parseFloat` comparisons; NaN never `false`). ## Steps to reproduce - (a) Entry `probability=30` with recursion enabled and an activated entry whose content matches it on recursion → it gets multiple 30% rolls across depths, so its effective activation rate exceeds 30%. - (b) Entry with `sticky=3, cooldown=5`; observe the cooldown reaching 0 before 5 messages because it ticked during the 3 sticky messages. - (c) Group `lore` with members `A(weight 100)` and `B(weight 1)`; `A` activates every time and `B` never does, even though ST would pick `B` ~1% of the time. - (d) Entry with activation condition `field=hp, operator=gt, value=50` on a chat with no `hp` in game state → `parseFloat("")=NaN`, `NaN<=50` is false, so the condition passes and the entry fires. ## Suggested fix - (a) Roll probability once per generation: thread the `probabilityDecisions` map (or pre-rolled results) through `recursiveScan` so each entry is decided once across all passes. - (b) Do not decrement `cooldownRemaining` while the entry is held by sticky (only tick cooldown once the sticky window ends), or track them on independent clocks. - (c) Implement weighted-random group selection (pick by `groupWeight` proportionally), matching ST inclusion-group behavior; keep deterministic only as an opt-in. - (d) In `evaluateConditions`, return `false` for `gt`/`lt` when either side is `NaN` (e.g. `if (!Number.isFinite(a) || !Number.isFinite(b)) return false`). ## Environment - Marinara Engine version: 2.0.0 (staging @ `b826f8f4`) - Install type: source - OS + version: All (code-level defect, platform-independent) - Browser or app shell: All ## Additional context Found via a systematic multi-agent audit of conditional prompt insertion. (a), (b), (d) make entries fire when they shouldn't; (c) prevents low-weight entries from ever firing. All four live in the lorebook scanner. Part of a set of lorebook-triggering issues filed together. ## Template check Please **uncheck (untick)** the box below before submitting so we know you read the template. It is intentionally pre-checked: - [ ] I DID NOT read this template and provide the requested details.
Author
Owner

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

Veracity self-review — correction / clarification
Automated post-filing review of this issue against the current working tree. The reported bug remains valid; the notes below refine its scope, accuracy, or suggested fix for whoever implements it.

Correction on sub-claim (a): the cited locus is dead code. recursiveScan (keyword-scanner.ts:537-572) has ZERO callers anywhere in the repo — a repo-wide search finds only its definition; every other "recursiveScan" hit is the unrelated recursiveScanning config flag. It is not in the live pipeline, so threading probabilityDecisions through it (as the suggested fix says) would change nothing observable.

The probability-re-roll defect is real and shipped, but it lives in the production recursion path: resolveBudgetAndRecursivelyActivateLorebookEntriesWithDiagnostics in packages/server/src/services/lorebook/index.ts (called from processLorebooks at index.ts:914 when recursion is enabled). That function calls scanForActivatedEntries fresh on the initial scan (index.ts:705) and on every recursion depth (index.ts:740); each call builds its own local probabilityDecisions map (keyword-scanner.ts:417). An entry that fails its probability roll is dropped inside the scan (continue at keyword-scanner.ts:446/492/514) and is never returned in frontier, so it is never added to processedIds (index.ts:712-714, which only iterates the candidates taken from frontier) and remains in remaining (index.ts:737) — getting a brand-new probability roll on the next depth at index.ts:740.

So (a) is a genuine bug, but the fix must be applied in index.ts, not to recursiveScan. Concretely: thread a shared probabilityDecisions Map (or pre-rolled per-entry results) into each scanForActivatedEntries call across depths via ScanOptions, or pre-roll all entry probabilities once before the recursion loop. random is already injectable via ScanOptions (keyword-scanner.ts:377), so adding a shared decision cache there is straightforward. Recommend also deleting the unused recursiveScan to prevent future confusion.

Sub-claims (b), (c), (d) are accurate and their line citations (105-110, 248-258 + 429-439, 318-351) all match the current tree exactly. Two minor refinements: (b) is slightly understated — when cooldown <= sticky the cooldown fully expires inside the sticky window (effectively zero post-sticky cooldown), not just "earlier". (c) note: ST's opt-in deterministic mode tiebreaks on highest Order ("Prioritize Inclusion"); Marinara has no equivalent field today (only groupWeight), so any deterministic opt-in should tiebreak on Order to match ST rather than on weight.

<!-- gh-comment-id:4761102259 --> @kolacheee commented on GitHub (Jun 21, 2026): > **Veracity self-review — correction / clarification** > _Automated post-filing review of this issue against the current working tree. The reported bug remains valid; the notes below refine its scope, accuracy, or suggested fix for whoever implements it._ Correction on sub-claim (a): the cited locus is dead code. `recursiveScan` (keyword-scanner.ts:537-572) has ZERO callers anywhere in the repo — a repo-wide search finds only its definition; every other "recursiveScan" hit is the unrelated `recursiveScanning` config flag. It is not in the live pipeline, so threading `probabilityDecisions` through it (as the suggested fix says) would change nothing observable. The probability-re-roll defect is real and shipped, but it lives in the production recursion path: `resolveBudgetAndRecursivelyActivateLorebookEntriesWithDiagnostics` in packages/server/src/services/lorebook/index.ts (called from `processLorebooks` at index.ts:914 when recursion is enabled). That function calls `scanForActivatedEntries` fresh on the initial scan (index.ts:705) and on every recursion depth (index.ts:740); each call builds its own local `probabilityDecisions` map (keyword-scanner.ts:417). An entry that fails its probability roll is dropped inside the scan (`continue` at keyword-scanner.ts:446/492/514) and is never returned in `frontier`, so it is never added to `processedIds` (index.ts:712-714, which only iterates the `candidates` taken from `frontier`) and remains in `remaining` (index.ts:737) — getting a brand-new probability roll on the next depth at index.ts:740. So (a) is a genuine bug, but the fix must be applied in index.ts, not to `recursiveScan`. Concretely: thread a shared `probabilityDecisions` Map (or pre-rolled per-entry results) into each `scanForActivatedEntries` call across depths via ScanOptions, or pre-roll all entry probabilities once before the recursion loop. `random` is already injectable via ScanOptions (keyword-scanner.ts:377), so adding a shared decision cache there is straightforward. Recommend also deleting the unused `recursiveScan` to prevent future confusion. Sub-claims (b), (c), (d) are accurate and their line citations (105-110, 248-258 + 429-439, 318-351) all match the current tree exactly. Two minor refinements: (b) is slightly understated — when cooldown <= sticky the cooldown fully expires inside the sticky window (effectively zero post-sticky cooldown), not just "earlier". (c) note: ST's opt-in deterministic mode tiebreaks on highest Order ("Prioritize Inclusion"); Marinara has no equivalent field today (only `groupWeight`), so any deterministic opt-in should tiebreak on Order to match ST rather than on weight.
Author
Owner

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

Fixed in branch codex/spicy-issue-sweep-2026-06-21.

What changed:

  • Threads a shared probability decision map through the live recursive lorebook budget path so each entry rolls at most once per generation.
  • Stops cooldown from ticking down while a sticky activation is holding the entry active.
  • Replaces deterministic max-weight group selection with weighted random selection using the existing injectable RNG.
  • Makes numeric gt/lt activation conditions fail when either side is missing or non-numeric.
  • Also made the unused recursiveScan helper honor the same probability-decision cache so it does not preserve the old pattern.

Final repo checks will run after the full issue sweep.

<!-- gh-comment-id:4761535998 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Fixed in branch `codex/spicy-issue-sweep-2026-06-21`. What changed: - Threads a shared probability decision map through the live recursive lorebook budget path so each entry rolls at most once per generation. - Stops cooldown from ticking down while a sticky activation is holding the entry active. - Replaces deterministic max-weight group selection with weighted random selection using the existing injectable RNG. - Makes numeric `gt`/`lt` activation conditions fail when either side is missing or non-numeric. - Also made the unused `recursiveScan` helper honor the same probability-decision cache so it does not preserve the old pattern. Final repo checks will run after the full issue sweep.
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#1338
No description provided.