A campaign could already be exported and imported. What could not survive the trip was everything that explains it: the state events behind the authoritative document, the prompt each turn was actually given, the passages it was shown, the summaries that carry long-story continuity, and which take belonged to which turn. An imported campaign could be read and could no longer say why it was what it was — and a manual correction, the one state change no narration explains, was indistinguishable from something the story had established. The bundle is now `ai-dnd-adventure-v3`, and the version is the design rather than a side effect. Everything added here could have been another optional key, the way persona, Save Points, narrative state and imported knowledge each were. That mechanism stops working at exactly this addition: a v2 file with no prompt provenance is ambiguous between "written before M9" and "written by M9 from a campaign that has none", and those are different facts about a campaign. A version number is how a recovery file states what it was capable of recording. v1 and v2 still import, and every seam from pre-active-head onward is tested for the rule that an older file is never reinterpreted under a newer assumption. Two categories became three. "Chosen travels, derived is recomputed" was enough until stored prompts had to be decided: they are derived, and they must travel anyway. The test that separates evidence from cache is not "could this be recomputed" but "would a recomputation answer the same question" — a rebuilt search index answers the same question, a rebuilt prompt says what the turn would be told *now*, which is the opposite of what the inspector is for. Also here: a real SQLite backup, through the online backup API rather than a file copy, taken while the application is running and verified before it is kept; story cards settled as compatibility-only legacy data and taken out of the narrator's prompt, because they were the untracked path around knowledge authority that IMPORTED-KNOWLEDGE-DESIGN §73 already forbade; and no schema change at all, proved against a database M8's own code wrote. Three defects, found by running the milestone's own tests rather than by reading them. Deleting a campaign leaked its FTS index rows, and SQLite then handed the freed ids to the next source imported into any campaign, which failed with an integrity error that Reindex could not repair — both ends are closed, and a database already carrying the damage now repairs itself. An imported node with no state snapshot was being stamped with the campaign's head state, so an Undo to turn 2 showed what the story knew at turn 20. And the snapshot relink did not persist at all, because it mutated a dict in place on a column SQLAlchemy tracks by assignment: it looked correct in memory and wrote the wrong ids to disk. Carrying per-turn prompts looked like it would halve the length of campaign that can be restored. Measured — and after compressing them inside the file — everything M9 added costs 12% of it: the import ceiling moves from about 318 turns to about 279, against a 100-turn certification target. The dominant cost is not M9's at all. The per-position narrative state document is 74% of a bundle, and v2 already carried it. Backend 1,102 passed / 14 skipped / 0 failed. Frontend 145 passed. Lint, production build and Docker build clean. Verified across two server processes with two data directories, and in a real browser against a real narrator. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Qyn3oRd4D6pi72nKBG725B
95 lines
3.9 KiB
Python
95 lines
3.9 KiB
Python
"""Gives every new guest a short adventure that is already played.
|
|
|
|
A guest arriving on an empty account has nothing to look at, and the demo turns
|
|
are limited, so learning what the app does used to cost one of them. This copies
|
|
a small pre-played adventure into the new account instead. It opens on a story
|
|
with real turns in it, and the turn summaries show what the world-state engine
|
|
records: the changes it applied, and the changes it refused.
|
|
|
|
The file in `starter_data/` is an ordinary export bundle, produced by
|
|
`GET /api/adventures/{id}/export` and trimmed to its first two exchanges. To
|
|
replace it, play a new adventure, export it, and overwrite the file. Nothing
|
|
else here knows what the story contains.
|
|
|
|
The copy is the guest's own from the first moment: they can edit it, branch it,
|
|
delete it, or export it, and nothing links it back to the file. A returning
|
|
guest is not given a second one, because this runs only where a guest row is
|
|
created.
|
|
"""
|
|
|
|
import json
|
|
import logging
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from . import bundle, models, seed
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
STARTER_FILE = Path(__file__).resolve().parent / "starter_data" / "pokemon-league.json"
|
|
|
|
|
|
def _load() -> dict | None:
|
|
"""Returns the starter bundle, or None when the file is missing or invalid.
|
|
|
|
The file ships with the server, so a failure here is a packaging mistake
|
|
rather than bad input. It is still tolerated: a guest with no starter
|
|
adventure can play, and a guest who cannot be created cannot.
|
|
"""
|
|
try:
|
|
return json.loads(STARTER_FILE.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
logger.exception("Starter adventure is missing or unreadable; skipping it.")
|
|
return None
|
|
|
|
|
|
def give(db: Session, user: models.User) -> models.Adventure | None:
|
|
"""Copies the starter adventure into `user`, and returns it.
|
|
|
|
The caller commits. This writes rows and does not commit them, so a guest
|
|
and their first adventure land in one transaction: an account is never left
|
|
half-populated.
|
|
|
|
Failures are logged and swallowed. The starter is a convenience, and losing
|
|
it must not cost the visitor their session.
|
|
"""
|
|
payload = _load()
|
|
if payload is None:
|
|
return None
|
|
try:
|
|
# A savepoint, so a failure halfway through writing the tree discards
|
|
# only the starter's rows. Without it the caller's next commit would
|
|
# flush whatever part of the adventure the session still held.
|
|
with db.begin_nested():
|
|
story = bundle.plan(payload, bundle.check_format(payload))
|
|
# The starter ships with no imported knowledge, so the derived
|
|
# report is always empty here and nothing reads it.
|
|
adventure, _ = bundle.materialize(db, payload, story, user.id)
|
|
_link_scenario(db, adventure, payload)
|
|
return adventure
|
|
except Exception:
|
|
logger.exception("Could not give user %s the starter adventure.", user.id)
|
|
return None
|
|
|
|
|
|
def _link_scenario(db: Session, adventure: models.Adventure, payload: dict) -> None:
|
|
"""Points the copy at the demo scenario it came from, when that seed exists.
|
|
|
|
A bundle does not carry a scenario id, because the id is local to one
|
|
database and an export outlives it. The link matters anyway: an adventure
|
|
has no cover art of its own, and inherits the scenario's. Without it the
|
|
starter shows a monogram tile while the demo it came from shows its own
|
|
artwork.
|
|
|
|
The name is read from `scenarioTitle` in the file. If no seeded scenario
|
|
answers to it, the adventure keeps a NULL `scenario_id`, which is the same
|
|
state an imported bundle is in and costs only the artwork.
|
|
"""
|
|
title = str(payload.get("scenarioTitle") or "").strip()
|
|
if not title:
|
|
return
|
|
scenario = seed.find_seeded(db, title)
|
|
if scenario is not None:
|
|
adventure.scenario_id = scenario.id
|