Roll back script_state on undo/retry; fix retry double-apply

The shared per-adventure script_state ("scoreboard" scripts write to) was
never reverted by undo, and retry re-ran the output hook on top of the already-
mutated state, double-applying its changes (e.g. "+10 gold" became +20).

Each action now snapshots script_state as it was immediately before its own
hooks ran (new Action.state_before column, migration 25):
- undo restores the turn's first-action snapshot, prunes memories that
  summarized the removed actions, and takes the turn lock against races.
- retry restores the AI action's snapshot before regenerating.

Story-card mutations are not reverted (documented limit). Adds the project's
first test suite: unit + full HTTP integration through the real scripting
engine (14 tests). See plan/11-state-revert-and-retry-fix.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
parththakkar106
2026-07-21 02:58:38 +05:30
co-authored by Claude Opus 4.8
parent 92044a53c4
commit dab1807118
7 changed files with 491 additions and 12 deletions
+15
View File
@@ -84,6 +84,21 @@ def story_actions(adventure: models.Adventure) -> list[models.Action]:
return [a for a in adventure.actions if a.text.strip()]
def prune_dangling_memories(adventure: models.Adventure, db: Session) -> int:
"""Delete memories that summarized actions which no longer exist (e.g. after
undo). source_start/source_end are Action.index values; a memory is dangling
if any covered action is past the current end of the story. Returns the count
removed. Cursors are self-healing in run_post_turn, so this is cleanup only."""
max_index = max((a.index for a in adventure.actions), default=-1)
dangling = [
m for m in adventure.memories
if m.source_end is not None and m.source_end > max_index
]
for m in dangling:
db.delete(m)
return len(dangling)
# ---------- Retrieval (runs inside the turn, before build_context) ----------
async def retrieve_memories(