[GH-ISSUE #2682] [Issue]: Unguarded JSON.parse in agent_data/world-state marker expansion crashes the entire main-prompt assembly #1326

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

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

Originally assigned to: @SpicyMarinara on GitHub.

Summary

expandAgentData() and expandWorldStateAgent() call JSON.parse on stored agent results / world-state snapshots without a try/catch, and the assembler's section-resolution loop does not guard resolveSection. So a single malformed or partial stored agent value throws synchronously during prompt assembly and aborts the entire main generation — not just the one agent section. A single bad stored row takes down every subsequent generation for that chat until the row is cleared.

Expected behavior

A corrupt/partial stored agent result or snapshot should degrade gracefully (the affected marker expands to empty), never crash the whole prompt build / generation.

Actual behavior

expandAgentData() does JSON.parse(run.resultData) and expandWorldStateAgent() does JSON.parse on presentCharacters/personaStats/playerStats — all unguarded. resolveSection → expandMarker → these expanders is called inside the assembler's section loop, which has no surrounding try/catch (the only nearby try/catch guards a separate chat_summary detection parse). A throw propagates out of the assembler and fails the generation request.

How it breaks the pipeline

Code trace (staging @ b826f8f4):

  • packages/server/src/services/prompt/marker-expander.ts:489 — const resultData = JSON.parse(run.resultData) (unguarded); also :538, :560, :568 (presentCharacters / personaStats / playerStats).
  • packages/server/src/services/prompt/assembler.ts:569 — resolveSection → expandMarker → expandAgentData; the section-resolution loop at assembler.ts:316-344 has no try/catch around resolveSection (the try/catch at :329-335 only guards chat_summary detection).
  • A malformed agent_runs.resultData (truncated agent write, schema change, corrupted snapshot from an aborted run) → JSON.parse throws → exception propagates out of assemblePrompt → the whole generation fails.

Steps to reproduce

  1. Leave/insert an agent_runs row for an active agent type with resultData = '{"text": "oops' (invalid JSON), or a game_state_snapshots row with presentCharacters = '[{"name"'.
  2. On the next generation with a preset containing that agent_data marker (or world-state active), expandAgentData/expandWorldStateAgent throws and the whole prompt build aborts — the chat can no longer generate until the row is cleared.

Suggested fix

Wrap each JSON.parse in expandAgentData and expandWorldStateAgent in try/catch returning { content: "" } (or skipping the field), and/or wrap the resolveSection call in the assembler loop so a single marker failure degrades to empty instead of aborting the prompt build.

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 the agent subsystem for 2.0.0 stability. This is the only agent-subsystem bug in the audit that breaks the main generation (not just an agent); recommended as a release blocker given the fix is a small try/catch. Part of a set of agent-pipeline 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 20, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2682 Originally assigned to: @SpicyMarinara on GitHub. ## Summary `expandAgentData()` and `expandWorldStateAgent()` call `JSON.parse` on stored agent results / world-state snapshots **without a try/catch**, and the assembler's section-resolution loop does not guard `resolveSection`. So a single malformed or partial stored agent value throws synchronously during prompt assembly and **aborts the entire main generation** — not just the one agent section. A single bad stored row takes down *every* subsequent generation for that chat until the row is cleared. ## Expected behavior A corrupt/partial stored agent result or snapshot should degrade gracefully (the affected marker expands to empty), never crash the whole prompt build / generation. ## Actual behavior `expandAgentData()` does `JSON.parse(run.resultData)` and `expandWorldStateAgent()` does `JSON.parse` on `presentCharacters`/`personaStats`/`playerStats` — all unguarded. `resolveSection` → `expandMarker` → these expanders is called inside the assembler's section loop, which has no surrounding try/catch (the only nearby try/catch guards a separate chat_summary detection parse). A throw propagates out of the assembler and fails the generation request. ## How it breaks the pipeline Code trace (staging @ `b826f8f4`): - `packages/server/src/services/prompt/marker-expander.ts:489` — `const resultData = JSON.parse(run.resultData)` (unguarded); also `:538`, `:560`, `:568` (`presentCharacters` / `personaStats` / `playerStats`). - `packages/server/src/services/prompt/assembler.ts:569` — `resolveSection` → `expandMarker` → `expandAgentData`; the section-resolution loop at `assembler.ts:316-344` has **no** try/catch around `resolveSection` (the try/catch at `:329-335` only guards chat_summary detection). - A malformed `agent_runs.resultData` (truncated agent write, schema change, corrupted snapshot from an aborted run) → `JSON.parse` throws → exception propagates out of `assemblePrompt` → the whole generation fails. ## Steps to reproduce 1. Leave/insert an `agent_runs` row for an active agent type with `resultData = '{"text": "oops'` (invalid JSON), or a `game_state_snapshots` row with `presentCharacters = '[{"name"'`. 2. On the next generation with a preset containing that agent_data marker (or world-state active), `expandAgentData`/`expandWorldStateAgent` throws and the whole prompt build aborts — the chat can no longer generate until the row is cleared. ## Suggested fix Wrap each `JSON.parse` in `expandAgentData` and `expandWorldStateAgent` in try/catch returning `{ content: "" }` (or skipping the field), and/or wrap the `resolveSection` call in the assembler loop so a single marker failure degrades to empty instead of aborting the prompt build. ## 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 the agent subsystem for 2.0.0 stability. This is the only agent-subsystem bug in the audit that breaks the **main** generation (not just an agent); recommended as a release blocker given the fix is a small try/catch. Part of a set of agent-pipeline 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 after reading the cited code in the current tree (and matching the issue's commit b826f8f4): only the agent_data half of this issue is a live crash. The world-state citations (marker-expander.ts:538/560/568 in expandWorldStateAgent) are DEAD CODE. In expandAgentData, world-state is in AUTO_INJECTED_TRACKERS and the function returns {content:""} at marker-expander.ts:455, before the if (agentType === "world-state") branch at :464 that is the only caller of expandWorldStateAgent (:468). That function has no other callers anywhere in the repo, so those three JSON.parse calls can never execute during prompt assembly. The live world-state/tracker injection is injectCommittedTrackerContext (packages/server/src/services/generation/committed-tracker-context.ts, called from generate.routes.ts:4528), and it already guards every parse via parseMaybeJson (lines 23-30, returns null on failure). So the world-state parses cannot crash the prompt build — please drop them from the crash claim, or re-scope them as "delete unreachable dead code," not a release-blocking crash.

The agent_data path IS confirmed real and reachable. marker-expander.ts:489 JSON.parse(run.resultData) is unguarded. When there is no runtime agent data (the stored-result case), assembler.ts:569 calls expandMarker, which has no try/catch (marker-expander.ts:106-127) and dispatches agent_data to expandAgentData. The assembler section loop (assembler.ts:316-353) has no try/catch around resolveSection — the try/catch at :329-335 only guards chat_summary marker detection. A throw exits assemblePrompt and is caught only by the route-level catch at generate.routes.ts:10328, which emits an SSE error and fails that generation; a persisted bad agent_runs row then fails every subsequent generation with that agent active until cleared. That alone justifies the release-blocker severity.

Fix refinement: the repo already has the safe pattern — parseRunData (agents.storage.ts:59-65, JSON.parse in try/catch falling back to the raw string) and parseMaybeJson (committed-tracker-context.ts:23-30). The minimal fix is to make expandAgentData use a guarded parse at marker-expander.ts:489; formatAgentResult (marker-expander.ts:601-624) already returns a string as-is and null as "", so degrading to the raw string or "" is safe. (Note parseRunData is module-private/not exported, so inline the same try/catch rather than importing it.) The optional defense-in-depth wrap of the resolveSection/expandMarker call in the assembler loop is worth doing because it also covers the genuinely LIVE adjacent unguarded parses — expandCharacter at marker-expander.ts:139 (JSON.parse on character card data) and resolveSection at assembler.ts:550 (JSON.parse on preset markerConfig) — but it should NOT be sold as hardening the world-state parses, which are unreachable.

<!-- gh-comment-id:4761102170 --> @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 after reading the cited code in the current tree (and matching the issue's commit b826f8f4): only the agent_data half of this issue is a live crash. The world-state citations (marker-expander.ts:538/560/568 in expandWorldStateAgent) are DEAD CODE. In expandAgentData, `world-state` is in AUTO_INJECTED_TRACKERS and the function returns {content:""} at marker-expander.ts:455, before the `if (agentType === "world-state")` branch at :464 that is the only caller of expandWorldStateAgent (:468). That function has no other callers anywhere in the repo, so those three JSON.parse calls can never execute during prompt assembly. The live world-state/tracker injection is injectCommittedTrackerContext (packages/server/src/services/generation/committed-tracker-context.ts, called from generate.routes.ts:4528), and it already guards every parse via parseMaybeJson (lines 23-30, returns null on failure). So the world-state parses cannot crash the prompt build — please drop them from the crash claim, or re-scope them as "delete unreachable dead code," not a release-blocking crash. The agent_data path IS confirmed real and reachable. marker-expander.ts:489 `JSON.parse(run.resultData)` is unguarded. When there is no runtime agent data (the stored-result case), assembler.ts:569 calls expandMarker, which has no try/catch (marker-expander.ts:106-127) and dispatches agent_data to expandAgentData. The assembler section loop (assembler.ts:316-353) has no try/catch around resolveSection — the try/catch at :329-335 only guards chat_summary marker detection. A throw exits assemblePrompt and is caught only by the route-level catch at generate.routes.ts:10328, which emits an SSE error and fails that generation; a persisted bad agent_runs row then fails every subsequent generation with that agent active until cleared. That alone justifies the release-blocker severity. Fix refinement: the repo already has the safe pattern — parseRunData (agents.storage.ts:59-65, JSON.parse in try/catch falling back to the raw string) and parseMaybeJson (committed-tracker-context.ts:23-30). The minimal fix is to make expandAgentData use a guarded parse at marker-expander.ts:489; formatAgentResult (marker-expander.ts:601-624) already returns a string as-is and null as "", so degrading to the raw string or "" is safe. (Note parseRunData is module-private/not exported, so inline the same try/catch rather than importing it.) The optional defense-in-depth wrap of the resolveSection/expandMarker call in the assembler loop is worth doing because it also covers the genuinely LIVE adjacent unguarded parses — expandCharacter at marker-expander.ts:139 (JSON.parse on character card data) and resolveSection at assembler.ts:550 (JSON.parse on preset markerConfig) — but it should NOT be sold as hardening the world-state parses, which are unreachable.
Author
Owner

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

Addressed on the issue-sweep branch. Verified the correction in the issue comment: the world-state parse path is unreachable in marker expansion, so I did not edit it. The live stored agent_data path now catches malformed JSON and expands that marker to empty with a warning, and the assembler now skips a section whose marker expansion throws instead of aborting the whole prompt build. Final repo checks will run after the sweep.

<!-- gh-comment-id:4761451658 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Addressed on the issue-sweep branch. Verified the correction in the issue comment: the world-state parse path is unreachable in marker expansion, so I did not edit it. The live stored agent_data path now catches malformed JSON and expands that marker to empty with a warning, and the assembler now skips a section whose marker expansion throws instead of aborting the whole prompt build. Final repo checks will run after the 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#1326
No description provided.