M5: genre-neutral authoritative narrative state, with review corrections

Replaces AI-DnD's RPG relative-delta world state with the genre-neutral typed
narrative state of ADR 010: explicit, absolute, allowlisted events proposed by
the model, validated by the application, applied to one authoritative document,
and snapshotted per position so restore stays a row read.

This commit includes the corrective pass that followed the independent review
in planning/reports/M5-IMPLEMENTATION-REPORT.md. The invariant it exists to
hold is:

    visible active transcript position == stored head == authoritative state

Narrator editing (D10, STORY-BRANCH-SEMANTICS §§14-15)

  A narrator edit no longer rewrites a row. It returns to the state before the
  turn, takes the reader's exact text as the accepted narration, re-derives the
  state that text implies, and becomes a new active continuation — while the
  original narration keeps its words, its live flag and its whole future as
  retained history. At the tip the correction is another take; with story below
  it, it forks. No new history machinery: this is the existing fork/take/head
  path with the reader's text in place of a generated reply. The §14A refusal
  is therefore gone for narrator turns, and remains only for player input.

Pre-M5 positions

  Migration 88 backfills the empty narrative document onto every action written
  before M5, and a missing snapshot now restores the empty document instead of
  leaving the previous position's state standing. Restoring to an old Save
  Point no longer leaves a later position's entities and facts on screen.

Narrator context

  Replayed history carries prose only; the machine-readable block is no longer
  reconstructed into past turns, where it contradicted the authoritative state
  in the same prompt. A fact withdrawn by a manual correction is now named as
  no longer true, with the reader's reason, rather than silently dropped.

Also

  - state_changes joins the action-list bulk read, removing one query per row.
  - Extraction takes only the application's own protocol payload: an ordinary
    ```json or ```python block in a story survives, and a mangled proposal
    still does not reach the reader.

Planning: ADR 013 records the authoritative document shape; §§14-15/14A, D10,
C04 and BUILD-MILESTONES are updated to describe what exists. Debt is recorded
against M8 (scenario editor UX) and M9 (export of the audit trail).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PWU4gTfLYY6Qq9U7aa9Qw2
This commit is contained in:
JesseMarkowitz
2026-09-05 07:01:50 -04:00
co-authored by Claude Opus 5
parent 62a997f364
commit b7005e6fdd
57 changed files with 7257 additions and 474 deletions
+28
View File
@@ -60,6 +60,7 @@ from sqlalchemy.orm import Session, undefer
from . import attempts, models, schemas
from .context import cursors, lineage
from .narrative import model as narrative_model
FORMAT = "ai-dnd-adventure-v2"
LEGACY_FORMAT = "ai-dnd-adventure-v1"
@@ -121,6 +122,14 @@ def export(db: Session, adventure: models.Adventure) -> dict:
"desc": adventure.persona_desc,
},
"worldState": adventure.world_state,
# M5. The authoritative narrative state, and the campaign's own rules.
# Both are decisions rather than derivations — the state is what the
# campaign established, and canon is what its owner wrote — so both go
# in the file by the rule at the top of this module. A bundle written
# before M5 has neither key and imports with an empty state, which is
# what such a campaign had.
"narrativeState": adventure.narrative_state,
"campaignCanon": adventure.campaign_canon,
"autoSummarize": adventure.auto_summarize,
"memoryBankEnabled": adventure.memory_bank_enabled,
# Write a root entry even for an adventure whose branch row was never
@@ -207,6 +216,14 @@ def _exported_node(action: models.Action, local: dict[int, int]) -> dict:
node["stateAfter"] = action.state_after
if action.world_state_after is not None:
node["worldStateAfter"] = action.world_state_after
# M5. Without this a restored campaign could be read but not moved around
# inside: every Undo, Redo and Save Point restore reads the destination
# node's snapshot, so a bundle carrying the turns and not the snapshots
# imports a story whose history cannot be walked.
if action.narrative_state_after is not None:
node["narrativeStateAfter"] = action.narrative_state_after
if action.state_changes:
node["stateChanges"] = action.state_changes
if action.world_delta:
node["worldDelta"] = action.world_delta
return node
@@ -495,6 +512,8 @@ def _planned_nodes(bundle: dict, branches: int) -> list[dict]:
"branch": branch,
"depth": depth,
"live": bool(entry.get("live", True)),
"narrativeStateAfter": _as_dict(entry.get("narrativeStateAfter")),
"stateChanges": _as_dict(entry.get("stateChanges")),
"type": str(entry.get("type") or "story")[:TYPE_MAX],
"text": str(entry.get("text") or ""),
"reasoning": _as_text(entry.get("reasoning")),
@@ -718,6 +737,8 @@ def _write_nodes(
state_after=spec["stateAfter"],
world_state_after=spec["worldStateAfter"],
world_delta=spec["worldDelta"],
narrative_state_after=spec.get("narrativeStateAfter"),
state_changes=spec.get("stateChanges"),
)
if spec["createdAt"] is not None:
action.created_at = spec["createdAt"]
@@ -871,6 +892,13 @@ def materialize(
ai_instructions=str(payload.get("aiInstructions") or ""),
story_summary=str(payload.get("storySummary") or ""),
world_state=payload.get("worldState") or {},
# M5. Normalised on the way in, so a hand-edited or truncated state
# section costs the section rather than the campaign — the story is the
# valuable thing, and a malformed document should not refuse an import.
narrative_state=narrative_model.normalize(payload.get("narrativeState"))
if isinstance(payload.get("narrativeState"), dict) else None,
campaign_canon=payload.get("campaignCanon")
if isinstance(payload.get("campaignCanon"), dict) else None,
auto_summarize=bool(payload.get("autoSummarize", False)),
memory_bank_enabled=bool(payload.get("memoryBankEnabled", False)),
**_imported_persona(payload.get("persona")),