Files
JesseMarkowitzandClaude Opus 5 44edece67e M9: a campaign you can actually get back
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
2026-09-07 01:55:45 -04:00

76 lines
3.2 KiB
Python

"""M9: taking a verified copy of the whole database, from the browser.
Two endpoints and no third. `app/backup.py` owns the procedure and every
guarantee it makes; these only decide who may ask.
## Why there is no restore endpoint, and no download
**Restore** means replacing the database file the running process has open.
Doing that from inside that process is how someone loses both copies at once:
the connection pool still holds handles on the old file, the WAL belongs to the
old file, and a half-swapped database is not something a running application can
notice. The supported procedure is in `DEVELOPMENT.md` — stop the application,
move the file into place, start it — and it is a procedure precisely because
each step needs the application not to be running. Campaign-level recovery, the
common case and the only one that crosses machines, is the export bundle.
**Download** is not offered either. The file is a copy of every campaign on the
machine, and streaming it through the browser would put it in the download
directory, in the browser's own cache, and in whatever the reader does with it
next — for a local single-user application whose whole premise is that the story
does not leave the machine, that is a worse default than a path the reader can
copy. So the response names the directory and the reader takes it from there.
## Where the file goes
Nowhere a request can name. The destination is derived from the database the
application is already using, and the filename is generated from the clock. No
part of either comes from the caller, so there is no traversal to attempt (H08),
and the endpoints below accept no body at all.
"""
import logging
from fastapi import APIRouter, Depends, HTTPException
from .. import auth, backup, models
router = APIRouter(prefix="/api/backups", tags=["backups"])
log = logging.getLogger(__name__)
@router.get("")
def list_backups(_user: models.User = Depends(auth.get_current_user)):
"""The backups already on disk, newest first, and where they are.
The directory is reported once here rather than on every row, because it is
the same for all of them and it is what the reader needs in order to find
the files at all.
"""
return {
"directory": str(backup.directory()),
"backups": backup.existing(),
}
@router.post("", status_code=201)
def create_backup(_user: models.User = Depends(auth.get_current_user)):
"""Takes one verified backup, and reports what it wrote.
Synchronous. A backup of a local single-user database is a page copy that
finishes in well under a second, and a reader who pressed the button is
entitled to be told whether it worked rather than to be told it started.
A failure is a 500 carrying the reason. There is nothing for the caller to
fix by retrying differently — the request has no parameters — so the useful
thing is the message, and `backup.create` guarantees that the source database
is untouched and no partial file is left behind.
"""
try:
result = backup.create()
except backup.BackupError as exc:
log.error("Backup failed: %s", exc)
raise HTTPException(500, str(exc)) from exc
return {"directory": str(result.path.parent), **result.as_dict()}