[PR #5106] [MERGED] feat(game): host-owned experience-state routes over game_engine_state #6630

Closed
opened 2026-10-23 04:12:14 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/5106
Author: @kolacheee
Created: 8/15/2026
Status: ✅ Merged
Merged: 8/16/2026
Merged by: @kolacheee

Base: staging ← Head: feat/5102-experience-state


📝 Commits (8)

  • 2e61291 feat(game): host-owned experience-state routes over game_engine_state (#5102)
  • 1e56056 fix(game): harden experience-state per adversarial review (#5102)
  • 4fdcc6c Merge branch 'staging' into feat/5102-experience-state
  • 89a43db Merge remote-tracking branch 'origin/staging' into feat/5102-experience-state
  • 32ea749 Merge remote-tracking branch 'origin/staging' into feat/5102-experience-state
  • 2a05b81 fix(game): address CodeRabbit review on the experience-state PR
  • e350c3c Merge remote-tracking branch 'origin/staging' into feat/5102-experience-state
  • c783b7c Merge remote-tracking branch 'origin/staging' into feat/5102-experience-state

📊 Changes

11 files changed (+800 additions, -65 deletions)

View changed files

📝 CHANGELOG.md (+2 -0)
📝 package.json (+2 -1)
📝 packages/server/src/db/file-backed-store.ts (+11 -4)
📝 packages/server/src/db/file-query.ts (+5 -1)
📝 packages/server/src/db/schema/checkpoints.ts (+5 -0)
📝 packages/server/src/routes/chats.routes.ts (+8 -4)
📝 packages/server/src/routes/game.routes.ts (+236 -23)
📝 packages/server/src/services/game/checkpoint.service.ts (+20 -0)
📝 packages/server/src/services/storage/game-engine-state.storage.ts (+117 -27)
📝 packages/server/src/services/turn-games/turn-game-runner.service.ts (+14 -5)
➕ scripts/regressions/experience-state.regression.ts (+380 -0)

📄 Description

Closes #5102

Why

A game-surface Experience (a capability package that owns an entire Game Mode world, e.g. the pixel-RPG Experience) has nowhere correct to keep its world state. The engine's game_engine_state table rides every lifecycle seam a game state needs — swipe delete/re-index, message and chat prunes, branch re-anchoring, checkpoint restore — but only the turn-game runner can reach it, and the package route registrar is privileged-only (admin secret off loopback, unusable from Android over LAN). So Experience saves live in chat metadata: a whole-blob store that no engine seam rewinds. Swipes don't rewind the world, branches copy stale state under dead anchors, and checkpoint restores skip it entirely.

What changed

Host-owned routes on the game router over createGameEngineStateStorage:

  • GET /api/game/:chatId/experience-state — the row for the chat's currently-visible anchor (via resolveVisibleGameStateAnchor, the same resolver game mode and turn-games use, including its checkpoint_restore rule), falling back to the latest committed save; the response's anchorMatched flag says whether the state belongs to the visible anchor or is a fallback (fresh swipe, pruned anchor), so a package can refuse a mismatched world instead of silently continuing it.
  • PUT /api/game/:chatId/experience-state — a bounded save (262,144 serialized chars; route-level bodyLimit rejects oversize payloads at the socket) anchored to the visible message ("" live anchor before the first one). Saves default to committed: true, are serialized per chat through a write lock (create is delete-then-insert across an await), and prune to the newest 100 anchors per chat.

Scoping and safety:

  • Rows use gameType: "experience:<gameExperienceId>". The stamp is honored only on game-mode chats and re-validated against the setup schema's id shape on every read — the metadata PATCH route merges arbitrary keys, and a malformed (e.g. newline-bearing) id must never reach the namespace. Both verbs refuse unstamped/malformed chats with 409, missing chats with 404.
  • Isolation is enforced in both directions: experience reads are scoped to their own namespace, and the turn-game runner's reads and its start/resign wipes exclude the experience: prefix (new notLike file-query operator) — so a newer experience save can neither shadow an active turn-game nor be destroyed by one. matchesLike is also newline-safe now (SQL-LIKE parity), which independently fixes multi-line substring-search misses.
  • create()'s per-anchor dedupe is scoped to the writer's own gameType, and chat branching copies every engine row at an anchor rather than limit(1).

Checkpoint capture, by value. The pre-existing restore re-lookup (newest row with createdAt ≤ the checkpoint's) is invalid for any writer that delete-recreates a single anchor — every experience save inside one narration turn, and in-place turn games like Tic-Tac-Toe — where it reproducibly restored nothing or a stale world on the auto-checkpoint path. Checkpoints now capture the newest engine-state blob per gameType into a new nullable engineStateData column at create time (mirroring the existing snapshotData copies; no storage-format bump — additive nullable columns follow repo precedent since format 4) and restore clones those blobs. The legacy lookup remains only for checkpoints created before the field existed. This also closes the documented in-place-turn-game caveat for all new checkpoints.

Review process

Round 1 (adversarial review, 2 empirically-reproduced blockers/majors + minors) reshaped the first cut: capture-by-value, both-direction namespace isolation, the mode gate. Round 2 (two-lens verification: an empirical probe suite re-running every pre-fix failure with discrimination controls, plus a fresh adversarial read of the fix layer) confirmed all round-1 failures fixed and surfaced the newline-stamp bypass, the body-limit gap, and the branch-copy limit(1) hole — all fixed and regression-pinned. Checkpoint blob accumulation (pre-existing for snapshotData) is deliberately out of scope: #5110.

New tracked lane regression:experience-state (in regression:issues), 14 cases: anchored round-trip (+anchorMatched), unstamped/malformed-stamp/mode-gate refusals with no row written, 404, namespace isolation in both directions at a shared anchor, anchor rewind, live-anchor saves, oversized-state 422, same-anchor replacement + legacy re-lookup + pruning, turn-game visibility under newer experience rows, resign survival, and checkpoint restore after a same-anchor rewrite (the ordering that broke the old heuristic).

Follow-up (Marinara-Agents side): migrate the Pixelforge package's saves off chat metadata onto these routes once this ships.

Validation

  • pnpm check
  • pnpm regression:experience-state (new, 14 cases)
  • Neighbor lanes: game-checkpoint-engine-state (now exercises the capture path), chat-branch-lineage, conversation-game-slash, game-metadata-race, card-library-search (covers the matchesLike change)
  • Manually verify in browser: in a Game Mode chat with an Experience, save state, swipe the last GM message and swipe back (world rewinds on the anchored swipe), load a checkpoint taken mid-session (world follows it), and resign nothing — then in a Conversation chat, confirm turn-games behave unchanged.

Summary by CodeRabbit

  • New Features

    • Added persistent Experience state storage for Game Mode chats, with retrieval, committed saves, validation, and size limits.
    • Checkpoints now capture and restore engine state across Experiences and turn-based games.
    • Branching preserves relevant engine snapshots across game types.
  • Bug Fixes

    • Improved isolation between Experience state and turn-game actions.
    • Enhanced checkpoint restoration after updates, rewinds, and branching.
    • Improved multiline and negated pattern matching.
    • Added cleanup for older Experience state anchors.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/5106 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/15/2026 **Status:** ✅ Merged **Merged:** 8/16/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `feat/5102-experience-state` --- ### 📝 Commits (8) - [`2e61291`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2e6129175cbe48c4f291da6d852b1926f88838db) feat(game): host-owned experience-state routes over game_engine_state (#5102) - [`1e56056`](https://github.com/Pasta-Devs/Marinara-Engine/commit/1e56056bc33b60302f81130ab6f19430ce8a38e3) fix(game): harden experience-state per adversarial review (#5102) - [`4fdcc6c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/4fdcc6c0ae4f1cac930f12df1f4f2d39ef5f568c) Merge branch 'staging' into feat/5102-experience-state - [`89a43db`](https://github.com/Pasta-Devs/Marinara-Engine/commit/89a43dbe4f3c90e73f8ee42ae1f7ae2c7069f309) Merge remote-tracking branch 'origin/staging' into feat/5102-experience-state - [`32ea749`](https://github.com/Pasta-Devs/Marinara-Engine/commit/32ea7491b03a3b924af7aef88b528feada80938b) Merge remote-tracking branch 'origin/staging' into feat/5102-experience-state - [`2a05b81`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2a05b81be714e8f67589c316384fca248118afc1) fix(game): address CodeRabbit review on the experience-state PR - [`e350c3c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e350c3c3c3f04301c0b23fee0ce1e3af093b0de3) Merge remote-tracking branch 'origin/staging' into feat/5102-experience-state - [`c783b7c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/c783b7c808d2c7313aefbe25de9452fc61302b9b) Merge remote-tracking branch 'origin/staging' into feat/5102-experience-state ### 📊 Changes **11 files changed** (+800 additions, -65 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+2 -0) 📝 `package.json` (+2 -1) 📝 `packages/server/src/db/file-backed-store.ts` (+11 -4) 📝 `packages/server/src/db/file-query.ts` (+5 -1) 📝 `packages/server/src/db/schema/checkpoints.ts` (+5 -0) 📝 `packages/server/src/routes/chats.routes.ts` (+8 -4) 📝 `packages/server/src/routes/game.routes.ts` (+236 -23) 📝 `packages/server/src/services/game/checkpoint.service.ts` (+20 -0) 📝 `packages/server/src/services/storage/game-engine-state.storage.ts` (+117 -27) 📝 `packages/server/src/services/turn-games/turn-game-runner.service.ts` (+14 -5) ➕ `scripts/regressions/experience-state.regression.ts` (+380 -0) </details> ### 📄 Description Closes #5102 ## Why A game-surface Experience (a capability package that owns an entire Game Mode world, e.g. the pixel-RPG Experience) has nowhere correct to keep its world state. The engine's `game_engine_state` table rides every lifecycle seam a game state needs — swipe delete/re-index, message and chat prunes, branch re-anchoring, checkpoint restore — but only the turn-game runner can reach it, and the package route registrar is privileged-only (admin secret off loopback, unusable from Android over LAN). So Experience saves live in chat metadata: a whole-blob store that no engine seam rewinds. Swipes don't rewind the world, branches copy stale state under dead anchors, and checkpoint restores skip it entirely. ## What changed Host-owned routes on the game router over `createGameEngineStateStorage`: - **`GET /api/game/:chatId/experience-state`** — the row for the chat's currently-visible anchor (via `resolveVisibleGameStateAnchor`, the same resolver game mode and turn-games use, including its `checkpoint_restore` rule), falling back to the latest committed save; the response's `anchorMatched` flag says whether the state belongs to the visible anchor or is a fallback (fresh swipe, pruned anchor), so a package can refuse a mismatched world instead of silently continuing it. - **`PUT /api/game/:chatId/experience-state`** — a bounded save (262,144 serialized chars; route-level `bodyLimit` rejects oversize payloads at the socket) anchored to the visible message (`""` live anchor before the first one). Saves default to `committed: true`, are serialized per chat through a write lock (create is delete-then-insert across an await), and prune to the newest 100 anchors per chat. Scoping and safety: - Rows use `gameType: "experience:<gameExperienceId>"`. The stamp is honored only on **game-mode** chats and **re-validated against the setup schema's id shape on every read** — the metadata PATCH route merges arbitrary keys, and a malformed (e.g. newline-bearing) id must never reach the namespace. Both verbs refuse unstamped/malformed chats with 409, missing chats with 404. - Isolation is enforced in **both directions**: experience reads are scoped to their own namespace, and the turn-game runner's reads and its start/resign **wipes** exclude the `experience:` prefix (new `notLike` file-query operator) — so a newer experience save can neither shadow an active turn-game nor be destroyed by one. `matchesLike` is also newline-safe now (SQL-LIKE parity), which independently fixes multi-line substring-search misses. - `create()`'s per-anchor dedupe is scoped to the writer's own `gameType`, and chat **branching copies every engine row at an anchor** rather than `limit(1)`. **Checkpoint capture, by value.** The pre-existing restore re-lookup (newest row with `createdAt ≤` the checkpoint's) is invalid for any writer that delete-recreates a single anchor — every experience save inside one narration turn, and in-place turn games like Tic-Tac-Toe — where it reproducibly restored nothing or a stale world on the auto-checkpoint path. Checkpoints now capture the newest engine-state blob per `gameType` into a new nullable `engineStateData` column at create time (mirroring the existing `snapshotData` copies; no storage-format bump — additive nullable columns follow repo precedent since format 4) and restore clones those blobs. The legacy lookup remains only for checkpoints created before the field existed. This also closes the documented in-place-turn-game caveat for all new checkpoints. ## Review process Round 1 (adversarial review, 2 empirically-reproduced blockers/majors + minors) reshaped the first cut: capture-by-value, both-direction namespace isolation, the mode gate. Round 2 (two-lens verification: an empirical probe suite re-running every pre-fix failure with discrimination controls, plus a fresh adversarial read of the fix layer) confirmed all round-1 failures fixed and surfaced the newline-stamp bypass, the body-limit gap, and the branch-copy `limit(1)` hole — all fixed and regression-pinned. Checkpoint blob accumulation (pre-existing for `snapshotData`) is deliberately out of scope: #5110. **New tracked lane** `regression:experience-state` (in `regression:issues`), 14 cases: anchored round-trip (+`anchorMatched`), unstamped/malformed-stamp/mode-gate refusals with no row written, 404, namespace isolation in both directions at a shared anchor, anchor rewind, live-anchor saves, oversized-state 422, same-anchor replacement + legacy re-lookup + pruning, turn-game visibility under newer experience rows, resign survival, and checkpoint restore after a same-anchor rewrite (the ordering that broke the old heuristic). Follow-up (Marinara-Agents side): migrate the Pixelforge package's saves off chat metadata onto these routes once this ships. ## Validation - [x] `pnpm check` - [x] `pnpm regression:experience-state` (new, 14 cases) - [x] Neighbor lanes: `game-checkpoint-engine-state` (now exercises the capture path), `chat-branch-lineage`, `conversation-game-slash`, `game-metadata-race`, `card-library-search` (covers the `matchesLike` change) - [x] Manually verify in browser: in a Game Mode chat with an Experience, save state, swipe the last GM message and swipe back (world rewinds on the anchored swipe), load a checkpoint taken mid-session (world follows it), and resign nothing — then in a Conversation chat, confirm turn-games behave unchanged. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added persistent Experience state storage for Game Mode chats, with retrieval, committed saves, validation, and size limits. - Checkpoints now capture and restore engine state across Experiences and turn-based games. - Branching preserves relevant engine snapshots across game types. - **Bug Fixes** - Improved isolation between Experience state and turn-game actions. - Enhanced checkpoint restoration after updates, rewinds, and branching. - Improved multiline and negated pattern matching. - Added cleanup for older Experience state anchors. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:12:14 +07:00
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#6630
No description provided.