[GH-ISSUE #2711] [Issue]: Malformed game-state JSON silently freezes world-state updates; Lorebook Keeper output can't reach the repair modal #1357

Closed
opened 2026-10-21 05:32:10 +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/2711

Originally assigned to: @SpicyMarinara on GitHub.

Summary

When a prior game-state JSON blob is malformed, the world-state agent's persistence block silently aborts the entire state update (no error surfaced) — so the HUD trackers freeze and stop advancing — and the only Lorebook-Keeper recovery path can't reach the repair modal, so truncated keeper output can only be re-rolled, never repaired. Both present as "the agent isn't running / the game forgot things" with no error.

Expected behavior

A single malformed/corrupt state field should degrade to a fallback (not abort the whole update), and structured agent output that fails to parse should be repairable (or surface a clear, actionable error) — not silently no-op.

Actual behavior

  1. World-state silently drops the update. In the world-state persistence block, prevSnap.presentCharacters / personaStats / playerStats are parsed with bare JSON.parse, all inside one broad try whose catch is an empty "non-critical" swallow. If any prior blob is malformed (the #2682 corruption surface, most exercised in game mode), the parse throws and the catch aborts the whole block: gameStateStore.create is skipped, no game_state_patch SSE is emitted, the gameMap sync is skipped, and the location-change journal entry is skipped. The HUD date/time/location/weather silently stops advancing turn after turn, with only a swallowed log. (Distinct from the #2682 crash — here the parse is caught and silently no-ops, which is why it's hard to attribute.)
  2. Keeper recovery can't repair. /session/regenerate-lorebook (the only manual keeper retry) calls the same function with the unguarded parse and, on failure, bare throws — it never calls sendJsonRepairError. Unlike session conclusions (which have a /session/conclude/apply-json repair endpoint), the keeper has no apply-json endpoint, so a deterministically-bad keeper generation can only be re-rolled (re-running the same failure-prone generation), never hand-repaired — the session's lore stays permanently empty.

How it breaks the pipeline

Code trace (staging @ b826f8f4):

  • (1) packages/server/src/routes/generate.routes.ts:7549,7554,7559 (bare JSON.parse), :7518-7648 (one broad try), :7646-7648 (empty "non-critical" catch); :7613 (the skipped game_state_patch SSE). Same pattern in the character-tracker block at :7669.
  • (2) packages/server/src/routes/game.routes.ts:4432-4467 (/session/regenerate-lorebook), :4455-4463 (calls keeper w/ unguarded parse at :2353), :4465-4466 (bare throw); contrast the conclude apply-json endpoint at :4313-4430.

Steps to reproduce

  1. Have an earlier turn store a malformed playerStats/personaStats/presentCharacters blob → run a game turn with the world-state agent enabled → no game_state_patch event, frozen HUD/world tracker, only a swallowed log.
  2. After a keeper run fails, click "Regenerate Lorebook"; if the model again returns invalid JSON it 500s with no repair modal, and repeating yields the same failure.

Suggested fix

  • Parse each game-state blob through a tolerant parseMaybeJson-style helper that returns null on failure (so one corrupt field degrades to a fallback instead of aborting the whole persistence block); apply to the character-tracker block too.
  • Have the keeper return its raw response on parse failure and respond with sendJsonRepairError(kind:'lorebook_keeper', applyEndpoint:'/game/session/lorebook-keeper/apply-json') instead of a bare throw, plus an apply-json endpoint that runs createGameLorebookKeeperEntries on the repaired JSON.

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 Game Mode. The "frozen trackers / forgot last session" weirdness with no surfaced error. Related to the #2682 unguarded-parse crash (same blob class), but these are the silent-degrade and unrepairable-keeper manifestations. Part of a set of game-mode 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/2711 Originally assigned to: @SpicyMarinara on GitHub. ## Summary When a prior game-state JSON blob is malformed, the world-state agent's persistence block silently aborts the **entire** state update (no error surfaced) — so the HUD trackers freeze and stop advancing — and the only Lorebook-Keeper recovery path can't reach the repair modal, so truncated keeper output can only be re-rolled, never repaired. Both present as "the agent isn't running / the game forgot things" with no error. ## Expected behavior A single malformed/corrupt state field should degrade to a fallback (not abort the whole update), and structured agent output that fails to parse should be repairable (or surface a clear, actionable error) — not silently no-op. ## Actual behavior 1. **World-state silently drops the update.** In the world-state persistence block, `prevSnap.presentCharacters` / `personaStats` / `playerStats` are parsed with bare `JSON.parse`, all inside one broad `try` whose `catch` is an empty "non-critical" swallow. If any prior blob is malformed (the #2682 corruption surface, most exercised in game mode), the parse throws and the catch aborts the whole block: `gameStateStore.create` is skipped, **no `game_state_patch` SSE** is emitted, the `gameMap` sync is skipped, and the location-change journal entry is skipped. The HUD date/time/location/weather silently stops advancing turn after turn, with only a swallowed log. (Distinct from the #2682 *crash* — here the parse is caught and silently no-ops, which is why it's hard to attribute.) 2. **Keeper recovery can't repair.** `/session/regenerate-lorebook` (the only manual keeper retry) calls the same function with the unguarded parse and, on failure, **bare `throw`s** — it never calls `sendJsonRepairError`. Unlike session conclusions (which have a `/session/conclude/apply-json` repair endpoint), the keeper has no apply-json endpoint, so a deterministically-bad keeper generation can only be re-rolled (re-running the same failure-prone generation), never hand-repaired — the session's lore stays permanently empty. ## How it breaks the pipeline Code trace (staging @ `b826f8f4`): - (1) `packages/server/src/routes/generate.routes.ts:7549,7554,7559` (bare `JSON.parse`), `:7518-7648` (one broad try), `:7646-7648` (empty "non-critical" catch); `:7613` (the skipped `game_state_patch` SSE). Same pattern in the character-tracker block at `:7669`. - (2) `packages/server/src/routes/game.routes.ts:4432-4467` (`/session/regenerate-lorebook`), `:4455-4463` (calls keeper w/ unguarded parse at `:2353`), `:4465-4466` (bare throw); contrast the conclude apply-json endpoint at `:4313-4430`. ## Steps to reproduce 1. Have an earlier turn store a malformed `playerStats`/`personaStats`/`presentCharacters` blob → run a game turn with the world-state agent enabled → no `game_state_patch` event, frozen HUD/world tracker, only a swallowed log. 2. After a keeper run fails, click "Regenerate Lorebook"; if the model again returns invalid JSON it 500s with no repair modal, and repeating yields the same failure. ## Suggested fix - Parse each game-state blob through a tolerant `parseMaybeJson`-style helper that returns null on failure (so one corrupt field degrades to a fallback instead of aborting the whole persistence block); apply to the character-tracker block too. - Have the keeper return its raw response on parse failure and respond with `sendJsonRepairError(kind:'lorebook_keeper', applyEndpoint:'/game/session/lorebook-keeper/apply-json')` instead of a bare throw, plus an apply-json endpoint that runs `createGameLorebookKeeperEntries` on the repaired JSON. ## 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 Game Mode. The "frozen trackers / forgot last session" weirdness with no surfaced error. Related to the #2682 unguarded-parse crash (same blob class), but these are the silent-degrade and unrepairable-keeper manifestations. Part of a set of game-mode 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.

Two clarifications for the fixer (verified against the working tree):

  1. Fix-completeness on claim (1): hardening only the three standalone JSON.parse calls (generate.routes.ts:7549/7554/7559) is NOT sufficient. The same broad try also calls parseGameStateRow(prevSnap) at generate.routes.ts:7563, and parseGameStateRow (packages/server/src/routes/generate/generate-route-utils.ts:998-1022) itself does bare JSON.parse on manualOverrides (:1001), presentCharacters (:1014), recentEvents (:1015), playerStats (:1016), and personaStats (:1017). A corrupt prevSnap blob will still throw there and abort the block even after the standalone parses are made tolerant. The fix must also make parseGameStateRow tolerant (or guard its call). The character-tracker block has the same dependency at generate.routes.ts:7674.

  2. Description nit: the character-tracker block is NOT silent — its catch at generate.routes.ts:7918-7920 logs via logger.error("[generate] character-tracker persistence error"). Only the world-state catch (:7646-7648, "// Non-critical") is truly silent. The CT abort is real, just attributable via the log.

  3. Keeper parse wording: the parse at game.routes.ts:2353 is parseJSON → parseGameJsonish (tolerant multi-attempt, not a bare JSON.parse), but its final fallback at services/game/jsonish.ts:168 (JSON.parse(candidate)) is unguarded and does throw on bad output — so the conclusion (status:'failed' at :2393 → bare throw at :4465-4467, no repair path) still holds.

  4. Fix prerequisites for the keeper repair path: (a) the regenerate-lorebook handler at game.routes.ts:4433 is async (req) => with no reply param and must add one to call sendJsonRepairError (which requires FastifyReply); (b) runGameLorebookKeeperAfterConclusion (game.routes.ts:2381-2394) currently catches the parse error internally and returns only an error string — it discards the raw model content, so it must be refactored to surface the raw response before a repair payload can be built; (c) add 'lorebook_keeper' to the JsonRepairKind union (game.routes.ts:2405). The conclude/apply-json endpoint at game.routes.ts:4313-4361 is the pattern to mirror, and the helpers normalizeGameLorebookKeeperEntries (:1915) and createGameLorebookKeeperEntries (:2188) already exist. The client GameJsonRepairModal posts to request.applyEndpoint generically (GameJsonRepairModal.tsx:66), so the bulk of the work is server-side.

<!-- gh-comment-id:4761102658 --> @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._ Two clarifications for the fixer (verified against the working tree): 1) Fix-completeness on claim (1): hardening only the three standalone JSON.parse calls (generate.routes.ts:7549/7554/7559) is NOT sufficient. The same broad try also calls parseGameStateRow(prevSnap) at generate.routes.ts:7563, and parseGameStateRow (packages/server/src/routes/generate/generate-route-utils.ts:998-1022) itself does bare JSON.parse on manualOverrides (:1001), presentCharacters (:1014), recentEvents (:1015), playerStats (:1016), and personaStats (:1017). A corrupt prevSnap blob will still throw there and abort the block even after the standalone parses are made tolerant. The fix must also make parseGameStateRow tolerant (or guard its call). The character-tracker block has the same dependency at generate.routes.ts:7674. 2) Description nit: the character-tracker block is NOT silent — its catch at generate.routes.ts:7918-7920 logs via logger.error("[generate] character-tracker persistence error"). Only the world-state catch (:7646-7648, "// Non-critical") is truly silent. The CT abort is real, just attributable via the log. 3) Keeper parse wording: the parse at game.routes.ts:2353 is parseJSON → parseGameJsonish (tolerant multi-attempt, not a bare JSON.parse), but its final fallback at services/game/jsonish.ts:168 (JSON.parse(candidate)) is unguarded and does throw on bad output — so the conclusion (status:'failed' at :2393 → bare throw at :4465-4467, no repair path) still holds. 4) Fix prerequisites for the keeper repair path: (a) the regenerate-lorebook handler at game.routes.ts:4433 is `async (req) =>` with no reply param and must add one to call sendJsonRepairError (which requires FastifyReply); (b) runGameLorebookKeeperAfterConclusion (game.routes.ts:2381-2394) currently catches the parse error internally and returns only an error string — it discards the raw model content, so it must be refactored to surface the raw response before a repair payload can be built; (c) add 'lorebook_keeper' to the JsonRepairKind union (game.routes.ts:2405). The conclude/apply-json endpoint at game.routes.ts:4313-4361 is the pattern to mirror, and the helpers normalizeGameLorebookKeeperEntries (:1915) and createGameLorebookKeeperEntries (:2188) already exist. The client GameJsonRepairModal posts to request.applyEndpoint generically (GameJsonRepairModal.tsx:66), so the bulk of the work is server-side.
Author
Owner

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

Fixed in c5ef429e. Game-state row parsing and the world/character tracker carry-forward paths now tolerate malformed JSON fields with safe fallbacks, so one corrupt blob no longer aborts the whole state update. Lorebook Keeper retries now preserve raw invalid output, return a lorebook_keeper repair payload, and include a repair apply endpoint that writes corrected entries through the existing Keeper entry path; the client now recognizes that repair kind and opens the generic repair modal.

<!-- gh-comment-id:4761647968 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Fixed in c5ef429e. Game-state row parsing and the world/character tracker carry-forward paths now tolerate malformed JSON fields with safe fallbacks, so one corrupt blob no longer aborts the whole state update. Lorebook Keeper retries now preserve raw invalid output, return a lorebook_keeper repair payload, and include a repair apply endpoint that writes corrected entries through the existing Keeper entry path; the client now recognizes that repair kind and opens the generic repair modal.
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#1357
No description provided.