[GH-ISSUE #2724] [Issue]: Tracker merge silently drops or mis-applies agent output (absent-vs-empty no-ops, empty-array clobber, tool-loop trap, combat clobbers world-state) #1369

Closed
opened 2026-10-21 05:32:32 +07:00 by bsakaguchi · 1 comment
Owner

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

Originally assigned to: @SpicyMarinara on GitHub.

Summary

The tracker merge layer mishandles legitimate structured agent output in several distinct ways. (1) The combat agent shares the game_state_update result type with world-state and re-runs the world-state create() path off a stale baseline, reverting the scene every combat turn. (2) Empty-array / empty-string outputs are treated as "no update" at the patch-construction guards, so trackers can never empty an inventory, clear a status, empty the persona bar list, or wipe custom fields — yet an empty presentCharacters array DOES clobber existing characters client-side. (3) The update_game_state tool is advertised as trackers' default tool, which routes them through a tool loop that only echoes and loses the JSON snapshot. (4) quest_update is missing from the custom-agent capability map, so custom quest agents persist nothing. The shared theme: the merge cannot distinguish "field absent" from "field present but empty," and result-type routing is overloaded/inconsistent.


Bug 1 — Combat agent reverts world-state scene advancement (high)

How it breaks the pipeline: combat maps to result.type==='game_state_update', the same type as world-state. Both pass the world-state handler gate (no agentType discriminator; combat is built-in). Both compute prevSnap from the same stale baseGameStateSnapshot and both call gameStateStore.create(), which deletes the existing (messageId, swipeIndex) row first. World-state runs first and advances date/time/location; combat runs second, emits no scene fields, falls back to the OLD baseline, and its create() deletes world-state's row — reverting the scene every combat turn.

Steps to replicate: Game mode with World State + Combat agents enabled; during an active encounter, take a turn that advances time/location. The HUD reverts date/time/location to the previous turn.

Code trace: agent-executor.ts:1822 combat: 'game_state_update'; gate generate.routes.ts:7511-7517 (no agentType exclusion); baseGameStateSnapshot const :3967; world-state prevSnap :7525-7527; combat schema emits no scene fields (agent-prompts.ts:203-228) -> coerceGameStateTextValue(undefined) -> falls back to old base; create() delete-then-insert game-state.storage.ts:237-243; RESULT_ORDER :7193; post_processing (world-state) ordered before parallel (combat) :7048-7056. (Requires manual-trackers off so world-state runs in-pipeline, :4643-4645.)

Bug 2 — Persona-stats can never empty inventory or clear status (medium)

How it breaks the pipeline: buildLockedPersonaTrackerPatch adds inventory/status to the patch only when non-empty, so an emitted inventory:[] (last item consumed) or status:'' is dropped before locks/diff and the previous value persists forever.

Steps to replicate: Consume the last inventory item so the persona agent emits inventory:[]. The item stays in the tracker indefinitely.

Code trace: generate-route-utils.ts:139 if(status)..., :140 if(inventory.length>0)...; field never added -> :160 Array.isArray(lockedPlayerStatsPatch.inventory) false -> existing kept; changed stays false -> no persist/SSE. Same in retry path retry-agents-route.ts:2209-2237. Prompt defines full-snapshot semantics (agent-prompts.ts:281-300).

Bug 3 — personaStats bar array can never be emptied (medium)

How it breaks the pipeline: Same root defect at a distinct line: if (stats.length > 0) rawPatch.personaStats = stats; drops an emitted empty bar list, so obsolete bars (e.g. a combat-only Stamina bar) linger forever.

Code trace: generate-route-utils.ts:136; personaStatsChanged requires Array.isArray(patch.personaStats) (:149-150) which is false -> never written. Both callers gate on non-empty updates (generate.routes.ts:7954, retry-agents-route.ts:2224).

Bug 4 — Custom-tracker agent can never clear all custom fields (low)

How it breaks the pipeline: The entire custom-field write is gated on rawFields.length > 0, so an explicit fields:[] (full wipe) is silently treated as no-op, even though buildLockedPlayerStatsArrayPatch would clear correctly if called.

Code trace: generate.routes.ts:7998-7999 const rawFields=(ctData.fields as any[])??[]; if(rawFields.length>0){...}; helper diff generate-route-utils.ts:86-109 computes changed correctly via isDeepStrictEqual([], existing). Same guard duplicated retry-agents-route.ts:2352-2353. Empty-as-delete is documented intent (agent-prompts.ts:306).

Bug 5 — Empty/partial presentCharacters array clobbers existing unlocked characters (high)

How it breaks the pipeline: Inversely to Bugs 2-4, the client merge applyGameStatePatchToStore special-cases empty arrays ONLY for activeQuests; an emitted presentCharacters:[] replaces existing characters wholesale (lock layer only preserves locked rows), and the server character-tracker path emits presentCharacters unconditionally even when empty.

Steps to replicate: Character-tracker returns valid JSON of {} or {presentCharacters:[]}. All unlocked present characters vanish from the HUD/panel.

Code trace: Client use-generate.ts:830-845 (only activeQuests empty-guard at :836-842); server emits unconditionally generate.routes.ts:7661,7886-7887 and retry-agents-route.ts:2171,2203. Maintainers' own comment generate.routes.ts:7602-7604 names this clobber vector for world-state but did not harden the character path. (inventory/personaStats are NOT emitted empty by the server, so only presentCharacters is the live clobber.)

Bug 6 — update_game_state default tool routes trackers through a lossy tool loop (medium)

How it breaks the pipeline: Tracker manifests advertise defaultTools:['update_game_state']; enabling it attaches a toolContext so the tracker runs via executeAgentWithTools. The tool impl only echoes ({applied:true,...}) and never writes the snapshot; the merge reads result.data, so if the model 'calls the tool' and returns prose/partial JSON, the snapshot is empty or established characters get wiped.

Steps to replicate: On a tracker agent, confirm update_game_state is toggled on (it is by default), run a turn with a model that calls the tool. Tracker stops updating or presentCharacters wipes to [].

Code trace: character-tracker/manifest.ts:12 (and persona/world/custom/quest :12); seeding agent.ts:598-600, agents.routes.ts:131,308; UI exposure AgentEditor.tsx:1234-1242; tool-context attach tool-resolution-runtime.ts:671-766; routing agent-pipeline.ts:152-181; echo-only impl tool-executor.ts:413-426; merge ignores tool calls generate.routes.ts:7651-7682.

Bug 7 — Custom quest_update agents persist nothing (medium)

How it breaks the pipeline: quest_update is the only tracker result type missing from CUSTOM_AGENT_RESULT_CAPABILITY, so a custom agent with resultType='quest_update' is never auto-granted edit_trackers; emit is allowed (default:true) but the persist gate (customAgentCanApplyResult(...,'edit_trackers')) returns false, so nothing is saved.

Code trace: agent.ts:483-493 (omits quest_update); normalizeCustomAgentCapabilities:517-520; emit gate generate.routes.ts:394-421 (no quest_update case -> default true); persist gate :8033-8038. Reachable via the agent create/update API / import (agent.schema.ts:14 accepts quest_update) even though the editor UI excludes it.


Suggested Fix

  • Gate the world-state create() handler on result.agentType (route combat through its own handler that never calls create()), OR make create() merge-update the existing (messageId, swipeIndex) row instead of delete-and-rebuild, OR have later game_state_update emitters re-read the just-written snapshot as prevSnap. (Bug 1.)
  • Distinguish 'field absent' from 'field present but empty': only skip when the agent did not emit the key at all; apply []/'' when the key is present. Apply to status/inventory/personaStats (generate-route-utils.ts:136,139,140) and custom fields (generate.routes.ts:7998, retry-agents-route.ts:2352). (Bugs 2-4.)
  • Client-side, treat an empty array as no-op for ALL tracker array sections (mirror activeQuests), OR have the character-tracker path skip emitting empty presentCharacters like world-state/persona-stats do. (Bug 5.)
  • Remove update_game_state from tracker manifests' defaultTools (trackers are pure-JSON snapshot agents), or hide/disable it in the editor for snapshot trackers, or make the tracker handlers consume update_game_state tool-call args. (Bug 6.)
  • Add quest_update:'edit_trackers' to CUSTOM_AGENT_RESULT_CAPABILITY and a case 'quest_update': arm to customAgentCanEmitResult so emit and apply are gated identically. (Bug 7.)

Template checklist

  • pnpm check passes (TypeScript + ESLint)
  • pnpm db:push run if storage/schema touched
  • Manually verify a combat turn with World State enabled does not revert date/time/location
  • Manually verify consuming the last inventory item empties the inventory in the tracker
  • Manually verify clearing a persona status / emptying the persona bar list persists
  • Manually verify a custom-tracker fields:[] wipes all custom fields
  • Manually verify a character-tracker returning empty does not delete existing present characters
  • Manually verify trackers produce snapshots with update_game_state disabled (or that enabling it no longer loses the snapshot)
  • Manually verify a custom agent configured with quest_update actually persists quest changes

Affected files

  • packages/server/src/routes/generate.routes.ts
  • packages/server/src/routes/generate/generate-route-utils.ts
  • packages/server/src/routes/generate/retry-agents-route.ts
  • packages/server/src/services/storage/game-state.storage.ts
  • packages/shared/src/types/agent.ts
  • packages/shared/src/features/agents/character-tracker/manifest.ts
  • packages/client/src/hooks/use-generate.ts

Audit provenance

Found by a multi-agent static audit of the trackers/widgets subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified). Severity: HIGH. Line numbers are against the staging working tree.

Note: this issue was AI-drafted from a static read of the code; the validation/test-plan boxes are intentionally left UNCHECKED for a human to verify before close.

Originally created by @kolacheee on GitHub (Jun 21, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2724 Originally assigned to: @SpicyMarinara on GitHub. ## Summary The tracker merge layer mishandles legitimate structured agent output in several distinct ways. (1) The combat agent shares the `game_state_update` result type with world-state and re-runs the world-state `create()` path off a stale baseline, reverting the scene every combat turn. (2) Empty-array / empty-string outputs are treated as "no update" at the patch-construction guards, so trackers can never empty an inventory, clear a status, empty the persona bar list, or wipe custom fields — yet an empty `presentCharacters` array DOES clobber existing characters client-side. (3) The `update_game_state` tool is advertised as trackers' default tool, which routes them through a tool loop that only echoes and loses the JSON snapshot. (4) `quest_update` is missing from the custom-agent capability map, so custom quest agents persist nothing. The shared theme: the merge cannot distinguish "field absent" from "field present but empty," and result-type routing is overloaded/inconsistent. --- ### Bug 1 — Combat agent reverts world-state scene advancement (high) **How it breaks the pipeline:** `combat` maps to `result.type==='game_state_update'`, the same type as world-state. Both pass the world-state handler gate (no `agentType` discriminator; combat is built-in). Both compute `prevSnap` from the same stale `baseGameStateSnapshot` and both call `gameStateStore.create()`, which deletes the existing (messageId, swipeIndex) row first. World-state runs first and advances date/time/location; combat runs second, emits no scene fields, falls back to the OLD baseline, and its `create()` deletes world-state's row — reverting the scene every combat turn. **Steps to replicate:** Game mode with World State + Combat agents enabled; during an active encounter, take a turn that advances time/location. The HUD reverts date/time/location to the previous turn. **Code trace:** `agent-executor.ts:1822` `combat: 'game_state_update'`; gate `generate.routes.ts:7511-7517` (no agentType exclusion); `baseGameStateSnapshot` const `:3967`; world-state `prevSnap` `:7525-7527`; combat schema emits no scene fields (`agent-prompts.ts:203-228`) -> `coerceGameStateTextValue(undefined)` -> falls back to old base; `create()` delete-then-insert `game-state.storage.ts:237-243`; `RESULT_ORDER` `:7193`; post_processing (world-state) ordered before parallel (combat) `:7048-7056`. (Requires manual-trackers off so world-state runs in-pipeline, `:4643-4645`.) ### Bug 2 — Persona-stats can never empty inventory or clear status (medium) **How it breaks the pipeline:** `buildLockedPersonaTrackerPatch` adds inventory/status to the patch only when non-empty, so an emitted `inventory:[]` (last item consumed) or `status:''` is dropped before locks/diff and the previous value persists forever. **Steps to replicate:** Consume the last inventory item so the persona agent emits `inventory:[]`. The item stays in the tracker indefinitely. **Code trace:** `generate-route-utils.ts:139` `if(status)...`, `:140` `if(inventory.length>0)...`; field never added -> `:160` `Array.isArray(lockedPlayerStatsPatch.inventory)` false -> existing kept; `changed` stays false -> no persist/SSE. Same in retry path `retry-agents-route.ts:2209-2237`. Prompt defines full-snapshot semantics (`agent-prompts.ts:281-300`). ### Bug 3 — personaStats bar array can never be emptied (medium) **How it breaks the pipeline:** Same root defect at a distinct line: `if (stats.length > 0) rawPatch.personaStats = stats;` drops an emitted empty bar list, so obsolete bars (e.g. a combat-only Stamina bar) linger forever. **Code trace:** `generate-route-utils.ts:136`; `personaStatsChanged` requires `Array.isArray(patch.personaStats)` (`:149-150`) which is false -> never written. Both callers gate on non-empty `updates` (`generate.routes.ts:7954`, `retry-agents-route.ts:2224`). ### Bug 4 — Custom-tracker agent can never clear all custom fields (low) **How it breaks the pipeline:** The entire custom-field write is gated on `rawFields.length > 0`, so an explicit `fields:[]` (full wipe) is silently treated as no-op, even though `buildLockedPlayerStatsArrayPatch` would clear correctly if called. **Code trace:** `generate.routes.ts:7998-7999` `const rawFields=(ctData.fields as any[])??[]; if(rawFields.length>0){...}`; helper diff `generate-route-utils.ts:86-109` computes `changed` correctly via `isDeepStrictEqual([], existing)`. Same guard duplicated `retry-agents-route.ts:2352-2353`. Empty-as-delete is documented intent (`agent-prompts.ts:306`). ### Bug 5 — Empty/partial presentCharacters array clobbers existing unlocked characters (high) **How it breaks the pipeline:** Inversely to Bugs 2-4, the client merge `applyGameStatePatchToStore` special-cases empty arrays ONLY for `activeQuests`; an emitted `presentCharacters:[]` replaces existing characters wholesale (lock layer only preserves locked rows), and the server character-tracker path emits `presentCharacters` unconditionally even when empty. **Steps to replicate:** Character-tracker returns valid JSON of `{}` or `{presentCharacters:[]}`. All unlocked present characters vanish from the HUD/panel. **Code trace:** Client `use-generate.ts:830-845` (only `activeQuests` empty-guard at `:836-842`); server emits unconditionally `generate.routes.ts:7661,7886-7887` and `retry-agents-route.ts:2171,2203`. Maintainers' own comment `generate.routes.ts:7602-7604` names this clobber vector for world-state but did not harden the character path. (inventory/personaStats are NOT emitted empty by the server, so only presentCharacters is the live clobber.) ### Bug 6 — update_game_state default tool routes trackers through a lossy tool loop (medium) **How it breaks the pipeline:** Tracker manifests advertise `defaultTools:['update_game_state']`; enabling it attaches a `toolContext` so the tracker runs via `executeAgentWithTools`. The tool impl only echoes (`{applied:true,...}`) and never writes the snapshot; the merge reads `result.data`, so if the model 'calls the tool' and returns prose/partial JSON, the snapshot is empty or established characters get wiped. **Steps to replicate:** On a tracker agent, confirm `update_game_state` is toggled on (it is by default), run a turn with a model that calls the tool. Tracker stops updating or presentCharacters wipes to `[]`. **Code trace:** `character-tracker/manifest.ts:12` (and persona/world/custom/quest `:12`); seeding `agent.ts:598-600`, `agents.routes.ts:131,308`; UI exposure `AgentEditor.tsx:1234-1242`; tool-context attach `tool-resolution-runtime.ts:671-766`; routing `agent-pipeline.ts:152-181`; echo-only impl `tool-executor.ts:413-426`; merge ignores tool calls `generate.routes.ts:7651-7682`. ### Bug 7 — Custom quest_update agents persist nothing (medium) **How it breaks the pipeline:** `quest_update` is the only tracker result type missing from `CUSTOM_AGENT_RESULT_CAPABILITY`, so a custom agent with `resultType='quest_update'` is never auto-granted `edit_trackers`; emit is allowed (default:true) but the persist gate (`customAgentCanApplyResult(...,'edit_trackers')`) returns false, so nothing is saved. **Code trace:** `agent.ts:483-493` (omits quest_update); `normalizeCustomAgentCapabilities:517-520`; emit gate `generate.routes.ts:394-421` (no quest_update case -> default true); persist gate `:8033-8038`. Reachable via the agent create/update API / import (`agent.schema.ts:14` accepts quest_update) even though the editor UI excludes it. --- ## Suggested Fix - Gate the world-state `create()` handler on `result.agentType` (route combat through its own handler that never calls `create()`), OR make `create()` merge-update the existing (messageId, swipeIndex) row instead of delete-and-rebuild, OR have later `game_state_update` emitters re-read the just-written snapshot as `prevSnap`. (Bug 1.) - Distinguish 'field absent' from 'field present but empty': only skip when the agent did not emit the key at all; apply `[]`/`''` when the key is present. Apply to status/inventory/personaStats (`generate-route-utils.ts:136,139,140`) and custom fields (`generate.routes.ts:7998`, `retry-agents-route.ts:2352`). (Bugs 2-4.) - Client-side, treat an empty array as no-op for ALL tracker array sections (mirror `activeQuests`), OR have the character-tracker path skip emitting empty `presentCharacters` like world-state/persona-stats do. (Bug 5.) - Remove `update_game_state` from tracker manifests' `defaultTools` (trackers are pure-JSON snapshot agents), or hide/disable it in the editor for snapshot trackers, or make the tracker handlers consume `update_game_state` tool-call args. (Bug 6.) - Add `quest_update:'edit_trackers'` to `CUSTOM_AGENT_RESULT_CAPABILITY` and a `case 'quest_update':` arm to `customAgentCanEmitResult` so emit and apply are gated identically. (Bug 7.) --- ## Template checklist - [ ] `pnpm check` passes (TypeScript + ESLint) - [ ] `pnpm db:push` run if storage/schema touched - [ ] Manually verify a combat turn with World State enabled does not revert date/time/location - [ ] Manually verify consuming the last inventory item empties the inventory in the tracker - [ ] Manually verify clearing a persona status / emptying the persona bar list persists - [ ] Manually verify a custom-tracker `fields:[]` wipes all custom fields - [ ] Manually verify a character-tracker returning empty does not delete existing present characters - [ ] Manually verify trackers produce snapshots with `update_game_state` disabled (or that enabling it no longer loses the snapshot) - [ ] Manually verify a custom agent configured with `quest_update` actually persists quest changes --- ### Affected files - `packages/server/src/routes/generate.routes.ts` - `packages/server/src/routes/generate/generate-route-utils.ts` - `packages/server/src/routes/generate/retry-agents-route.ts` - `packages/server/src/services/storage/game-state.storage.ts` - `packages/shared/src/types/agent.ts` - `packages/shared/src/features/agents/character-tracker/manifest.ts` - `packages/client/src/hooks/use-generate.ts` ### Audit provenance Found by a multi-agent static audit of the trackers/widgets subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified). Severity: **HIGH**. Line numbers are against the `staging` working tree. > Note: this issue was AI-drafted from a static read of the code; the validation/test-plan boxes are intentionally left UNCHECKED for a human to verify before close.
Author
Owner

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

Fixed in eb403162. Combat game_state_update results no longer run through the world-state snapshot path, persona/custom tracker outputs now distinguish absent fields from intentional empty values, empty/missing character tracker presence is treated as no-op instead of clobbering snapshots, tracker built-ins no longer default-enable update_game_state, and quest_update is gated through edit_trackers for custom agents.

<!-- gh-comment-id:4761791387 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Fixed in eb403162. Combat game_state_update results no longer run through the world-state snapshot path, persona/custom tracker outputs now distinguish absent fields from intentional empty values, empty/missing character tracker presence is treated as no-op instead of clobbering snapshots, tracker built-ins no longer default-enable update_game_state, and quest_update is gated through edit_trackers for custom agents.
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#1369
No description provided.