M4: add durable named Save Points
A Save Point is a name for a story position, and restoring one is head movement. That is the whole architecture, and it is what ADR 012 and BUILD-MILESTONES' note on M4 asked for: M3 made the head a stored (branch, depth) and made arriving at one a row lookup plus a state restore, so a Save Point needs no restore machinery of its own. What the user gets: - Name the moment they are reading, keep playing, restart the app, and come back to it. Restoring moves the story back and deletes nothing: the later turns stay, Redo still walks forward into them, and writing something different is what starts a new line while the old one is kept. - Rename, delete, and a list, in a Save Points panel beside the branch panel, with a Save Point button next to Undo and Redo. Both confirmations say what is *not* destroyed, because that is the part the screen cannot show. - Save Points survive export and import. What was deliberately not built: - No second restore path. `head.move_to_node` is the only new movement: its depth half is M3's `head.move_to` unchanged, and its branch half is the single assignment `switch_branch` already makes. No head field is written in the checkpoint router, nothing reconstructs state, nothing prunes a memory, nothing copies or deletes a turn, and restore never forks — the first write below the restored head does, through `fork_if_behind_head`. - No automatic cleanup. A Save Point behind the head, or naming a line the story left, is doing its job (STORY-BRANCH-SEMANTICS §19). The one removal is a cascade: deleting a branch takes its Save Points, as it takes its memories, because the story they named went with it. - No new ADR. ADR 012 already decides the architecture, and a table is not a decision. The one call the planning package did not already make: restore moves the branch half of the head only when the coordinate is off the path being read. Doing it unconditionally would quietly hand back an abandoned continuation whenever a Save Point in a shared prefix was restored; never doing it would make a Save Point on a departed line unrestorable, which contradicts §19. TECHNICAL-DESIGN §8.8 records it. Schema: a `checkpoints` table holding a name, an optional note and a (branch, depth) coordinate — no copy of any story. `create_all` builds it as it did `memories` and `branches`; migration 80 adds the index. No backfill, because nobody had named a position before M4. The coordinate is deliberately not an action id: one coordinate holds every attempt at a turn and exactly one is live, so a coordinate follows a retry where a row id would pin a take the story no longer tells. Tests: 680 pass (638 before). 42 new in tests/test_save_points.py covering D11-D14, I04, L03, E-series lineage and memory isolation after restore and divergence, the edge cases, and an M3-database migration. One pre-existing fixture in test_tree_migration.py needed `checkpoints` added to its drop list — SQLite refuses to drop a table another table references. Not verified: the browser. No session has had a usable one, so the Save Point panel's DOM behaviour is unobserved — as M3's Redo control still is. The twenty-step sequence was driven over HTTP against a live server with a real process restart instead, and all seventeen checks pass. M4 is implemented, not accepted: no review has been written. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PWU4gTfLYY6Qq9U7aa9Qw2
This commit is contained in:
co-authored by
Claude Opus 5
parent
3c8e91f644
commit
e08d49c3eb
@@ -134,6 +134,16 @@ def export(db: Session, adventure: models.Adventure) -> dict:
|
||||
"memoryCursor": _exported_anchor(adventure, cursors.MEMORY, local),
|
||||
"summaryCursor": _exported_anchor(adventure, cursors.SUMMARY, local),
|
||||
"memories": [_exported_memory(m, local) for m in adventure.memories],
|
||||
# M4. A Save Point is a decision — someone chose this position and gave
|
||||
# it a name — so it goes in the file by the rule at the top of this
|
||||
# module. Nothing here is derived: the coordinate is the one stored, not
|
||||
# one recomputed from the rows, because the whole point of the pointer
|
||||
# is that no amount of reading the turns can tell you which one somebody
|
||||
# named. A bundle written before M4 has no key here and imports with no
|
||||
# Save Points, which is what such a campaign had.
|
||||
"checkpoints": [
|
||||
_exported_checkpoint(c, local) for c in _checkpoints_of(db, adventure)
|
||||
],
|
||||
"storyCards": [
|
||||
{"type": c.type, "name": c.name, "keys": c.keys,
|
||||
"entry": c.entry, "notes": c.notes}
|
||||
@@ -215,6 +225,35 @@ def _exported_memory(memory: models.Memory, local: dict[int, int]) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _checkpoints_of(db: Session, adventure: models.Adventure) -> list[models.Checkpoint]:
|
||||
"""Returns the campaign's Save Points in creation order.
|
||||
|
||||
Read with a query rather than through a relationship, for the reason
|
||||
`models.Branch` declares none: a relationship on `Adventure` would be loaded
|
||||
by anything that touches an adventure, and the export is the only thing in
|
||||
the application that wants every Save Point at once.
|
||||
"""
|
||||
return (
|
||||
db.query(models.Checkpoint)
|
||||
.filter(models.Checkpoint.adventure_id == adventure.id)
|
||||
.order_by(models.Checkpoint.id)
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def _exported_checkpoint(checkpoint: models.Checkpoint, local: dict[int, int]) -> dict:
|
||||
return {
|
||||
"name": checkpoint.name,
|
||||
"note": checkpoint.note,
|
||||
# The branch as a position in this file's list, like every other branch
|
||||
# reference in the bundle. The depth is a coordinate along it and needs
|
||||
# no translation.
|
||||
"branch": _local(checkpoint.branch_id, local),
|
||||
"depth": checkpoint.depth,
|
||||
"createdAt": checkpoint.created_at.isoformat() if checkpoint.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _imported_persona(persona) -> dict:
|
||||
"""Reads a bundle's `persona` block into `Adventure` keyword arguments.
|
||||
|
||||
@@ -280,6 +319,13 @@ def plan(bundle: dict, version: str) -> dict:
|
||||
"branches": branches,
|
||||
"nodes": nodes,
|
||||
"memories": _planned_memories(bundle, len(branches)),
|
||||
# M4. Empty for a version 1 bundle and for any version 2 bundle written
|
||||
# before Save Points existed, which is the same answer: no one had named
|
||||
# a position in those campaigns.
|
||||
"checkpoints": (
|
||||
_planned_checkpoints(bundle, len(branches), nodes)
|
||||
if version == FORMAT else []
|
||||
),
|
||||
"head": head,
|
||||
# None means the file does not say, which is every version 1 bundle and
|
||||
# every version 2 bundle written before M3. `_point_the_head` derives it
|
||||
@@ -525,6 +571,57 @@ def _planned_memories(bundle: dict, branches: int) -> list[dict]:
|
||||
return out
|
||||
|
||||
|
||||
def _planned_checkpoints(
|
||||
bundle: dict, branches: int, nodes: list[dict]
|
||||
) -> list[dict]:
|
||||
"""Returns the file's Save Points, checked against the tree it also carries.
|
||||
|
||||
A Save Point whose coordinate names no turn in the file is dropped rather
|
||||
than imported, and dropped rather than raising. The two halves of that are
|
||||
each deliberate:
|
||||
|
||||
* Dropped, because an imported pointer to a position the imported story does
|
||||
not contain is a Save Point that can only ever refuse to restore. It would
|
||||
be a row that exists to disappoint.
|
||||
* Not a 400, unlike the head depth. The head is a position the campaign is
|
||||
read at, so a file that misplaces it opens the story in the wrong place
|
||||
and every read is affected. A Save Point is a bookmark, and a bad one
|
||||
spoils nothing else in the file — refusing to import a whole campaign
|
||||
because one bookmark is wrong would lose the story to save the bookmark.
|
||||
|
||||
A name that is blank once trimmed is dropped for the same reason the create
|
||||
endpoint refuses one: an unnamed Save Point is not identifiable in a list.
|
||||
"""
|
||||
# Every coordinate the file writes, not only the ones it marks live.
|
||||
# `_write_nodes` makes exactly one attempt at each coordinate live whatever
|
||||
# the file says, so a coordinate that exists is a coordinate that will
|
||||
# resolve — and reading the flags here would drop a Save Point over a
|
||||
# question the writer has already settled.
|
||||
written = {(n["branch"], n["depth"]) for n in nodes}
|
||||
raw = bundle.get("checkpoints")
|
||||
out: list[dict] = []
|
||||
for entry in raw if isinstance(raw, list) else []:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
name = str(entry.get("name") or "").strip()[:schemas.CHECKPOINT_NAME_MAX]
|
||||
if not name:
|
||||
continue
|
||||
depth = entry.get("depth")
|
||||
if not _is_int(depth):
|
||||
continue
|
||||
branch = _as_index(entry.get("branch"), branches, default=None)
|
||||
if branch is None or (branch, depth) not in written:
|
||||
continue
|
||||
out.append({
|
||||
"name": name,
|
||||
"note": str(entry.get("note") or ""),
|
||||
"branch": branch,
|
||||
"depth": depth,
|
||||
"createdAt": _as_time(entry.get("createdAt")),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _planned_anchors(bundle: dict, branches: int) -> dict:
|
||||
anchors = {}
|
||||
for name in ("memory", "summary"):
|
||||
@@ -550,6 +647,7 @@ def write(db: Session, adventure: models.Adventure, story: dict) -> None:
|
||||
_write_nodes(db, adventure, story["nodes"], ids)
|
||||
_write_memories(db, adventure, story["memories"], ids)
|
||||
_point_the_head(adventure, story, ids)
|
||||
_write_checkpoints(db, adventure, story["checkpoints"], ids)
|
||||
_write_anchors(adventure, story, ids)
|
||||
|
||||
|
||||
@@ -665,6 +763,32 @@ def _write_memories(
|
||||
db.add(memory)
|
||||
|
||||
|
||||
def _write_checkpoints(
|
||||
db: Session, adventure: models.Adventure, specs: list[dict], ids: list[int]
|
||||
) -> None:
|
||||
"""Writes the Save Points, and moves nothing.
|
||||
|
||||
Note what this function does not touch. The head is pointed by
|
||||
`_point_the_head` from the file's own `headBranch`/`headDepth`, and importing
|
||||
a Save Point must not disturb it — a campaign exported at turn 30 with a
|
||||
Save Point at turn 12 opens at turn 30. The bundle records where the story
|
||||
was being read and, separately, which positions someone named; restoring one
|
||||
of them is a thing the user does afterwards, not a thing an import does for
|
||||
them.
|
||||
"""
|
||||
for spec in specs:
|
||||
checkpoint = models.Checkpoint(
|
||||
adventure_id=adventure.id,
|
||||
name=spec["name"],
|
||||
note=spec["note"],
|
||||
branch_id=ids[spec["branch"]],
|
||||
depth=spec["depth"],
|
||||
)
|
||||
if spec["createdAt"] is not None:
|
||||
checkpoint.created_at = spec["createdAt"]
|
||||
db.add(checkpoint)
|
||||
|
||||
|
||||
def _point_the_head(
|
||||
adventure: models.Adventure, story: dict, ids: list[int]
|
||||
) -> None:
|
||||
|
||||
@@ -314,6 +314,40 @@ def move_to(db: Session, adventure: models.Adventure, depth: int) -> None:
|
||||
attempts.restore_state(adventure, node_at(db, adventure, depth))
|
||||
|
||||
|
||||
def move_to_node(db: Session, adventure: models.Adventure, node: models.Action) -> bool:
|
||||
"""Moves the head onto `node`, changing line only if it is not on this one.
|
||||
|
||||
M4 restores a Save Point through this, and it adds no restoring of its own:
|
||||
the depth half is `move_to` unchanged, so the state, the transcript, the
|
||||
assembled context and memory eligibility all arrive exactly as they do for
|
||||
Undo and Redo. Returns whether the line had to change as well as the depth,
|
||||
which is the one thing about a restore a caller cannot work out afterwards.
|
||||
|
||||
The head is two values, and the two halves move for different reasons. A
|
||||
Save Point almost always names a position on the story being read — its own
|
||||
line, or the shared prefix that line inherits — and then only the depth
|
||||
moves. Leaving the branch alone is what makes the restored position keep the
|
||||
continuation it has: after a divergence, restoring to the shared prefix must
|
||||
put the reader back on the *new* line, where Redo walks into the turns they
|
||||
are still writing, not into the future they left. Reaching for the Save
|
||||
Point's own branch there would quietly hand back the abandoned story.
|
||||
|
||||
The other case is real and has to work. A Save Point survives divergence
|
||||
(`STORY-BRANCH-SEMANTICS.md` §19), so one can name a position on a line the
|
||||
story has since left, and no amount of depth movement reaches a branch this
|
||||
path does not contain. The line then moves as well — one assignment, the
|
||||
same one `switch_branch` makes — and the depth still moves through
|
||||
`move_to`. Nothing is created: a restore never forks, whichever case it
|
||||
takes. The first write below the restored head does, through
|
||||
`fork_if_behind_head`, like every other write.
|
||||
"""
|
||||
switched = not lineage.path_of(db, adventure).uncapped().contains(node)
|
||||
if switched:
|
||||
adventure.head_branch_id = node.branch_id
|
||||
move_to(db, adventure, node.depth)
|
||||
return switched
|
||||
|
||||
|
||||
def fork_if_behind_head(db: Session, adventure: models.Adventure) -> bool:
|
||||
"""Gives the story a new branch when a write would displace a retained future.
|
||||
|
||||
|
||||
@@ -350,6 +350,17 @@ MIGRATIONS: list[tuple[int, str | dict[str, str]]] = [
|
||||
# No backfill.
|
||||
(78, "ALTER TABLE branches ADD COLUMN superseded_at TIMESTAMP"),
|
||||
(79, "ALTER TABLE branches ADD COLUMN superseded_depth INTEGER"),
|
||||
# M4: Save Points. `create_all` creates the `checkpoints` table itself, on
|
||||
# existing databases as well as fresh ones, exactly as it did for
|
||||
# `memories` at version 2 and `branches` at version 46. What it does not
|
||||
# create is the index every list and every cascade reads, so that is what
|
||||
# this version is.
|
||||
#
|
||||
# No backfill. A Save Point records a decision someone made, and nobody has
|
||||
# made one yet: an M3 database has no position a user chose to name, and
|
||||
# inventing one would be inventing the decision.
|
||||
(80, "CREATE INDEX IF NOT EXISTS ix_checkpoints_adventure "
|
||||
"ON checkpoints (adventure_id)"),
|
||||
]
|
||||
|
||||
LATEST_VERSION = max((v for v, _ in MIGRATIONS), default=1)
|
||||
|
||||
@@ -241,6 +241,60 @@ class Branch(Base):
|
||||
superseded_depth: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
|
||||
|
||||
class Checkpoint(Base):
|
||||
"""M4: a Save Point — a durable named pointer to a story position.
|
||||
|
||||
"Save Point" is what the user reads; `checkpoint` is what the code calls it
|
||||
(`BROWSER-UX-SPEC.md` §23).
|
||||
|
||||
The row holds a name and a coordinate, and no story. `DATA-MODEL.md` §8
|
||||
describes the pointer as naming a turn; the coordinate here is
|
||||
`(branch_id, depth)`, which is what M3 made the head and what
|
||||
`head.node_at` resolves. Restoring one is therefore head movement with a
|
||||
bounds check rather than a restore system of its own — see ADR 012 and
|
||||
`head.move_to_node`.
|
||||
|
||||
A coordinate rather than an action id, deliberately. One coordinate can
|
||||
hold several attempts at a turn and exactly one of them is live, so a
|
||||
retry replaces the row a Save Point would have pinned. "Turn 42 of this
|
||||
line" survives a retry; "action 918" would point at a take the story no
|
||||
longer tells.
|
||||
|
||||
`branch_id` is the branch the node itself sits on, not the branch that was
|
||||
being read when the Save Point was made. Those differ whenever the head is
|
||||
resting in a shared prefix, and the node's own branch is the one that still
|
||||
names the position after the reader has moved elsewhere.
|
||||
|
||||
Deleting a branch deletes its Save Points, by the same cascade that takes
|
||||
its memories: the story the pointer names is gone with it. Nothing else
|
||||
removes one. They are not cleaned up for going stale, for being behind the
|
||||
head, or for pointing into a future the story has left
|
||||
(`STORY-BRANCH-SEMANTICS.md` §19).
|
||||
"""
|
||||
|
||||
__tablename__ = "checkpoints"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
adventure_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("adventures.id", ondelete="CASCADE")
|
||||
)
|
||||
name: Mapped[str] = mapped_column(String(120), default="")
|
||||
# `DATA-MODEL.md` §8's optional notes, and `BROWSER-UX-SPEC.md` §24's
|
||||
# optional second field. Empty is the ordinary case.
|
||||
note: Mapped[str] = mapped_column(Text, default="")
|
||||
branch_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("branches.id", ondelete="CASCADE")
|
||||
)
|
||||
depth: Mapped[int] = mapped_column(Integer)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=utcnow)
|
||||
# Bumped by a rename, which is the only edit a Save Point allows. The
|
||||
# coordinate is never rewritten: `STORY-BRANCH-SEMANTICS.md` §24 keeps a
|
||||
# Save Point's meaning auditable by making "move it" delete-and-recreate.
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=utcnow, onupdate=utcnow
|
||||
)
|
||||
|
||||
|
||||
class Memory(Base):
|
||||
"""Phase 6: an auto-summarized (or hand-written) fact about the adventure.
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ Read the modules in this order to follow a turn from end to end:
|
||||
turns playing a turn, and the lock that allows only one at a time
|
||||
takes retries and the attempts that collect at one coordinate
|
||||
branches where a story splits
|
||||
checkpoints Save Points: durable names for positions the head can return to
|
||||
|
||||
What this package re-exports, and what it deliberately does not:
|
||||
|
||||
@@ -31,6 +32,7 @@ from . import ( # noqa: F401
|
||||
turns,
|
||||
takes,
|
||||
branches,
|
||||
checkpoints,
|
||||
bundle_io,
|
||||
refresh,
|
||||
insights,
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
"""M4: Save Points — create, list, rename, delete, and restore.
|
||||
|
||||
A Save Point is a durable named pointer to a story position and nothing else.
|
||||
It stores a coordinate, never a copy of any story, and restoring one moves the
|
||||
active head to that coordinate. That is the whole design, and it is what
|
||||
`BUILD-MILESTONES.md`'s note on M4 and ADR 012 ask for: M3 made the head a
|
||||
stored `(branch, depth)` and made arriving at one a row lookup plus a state
|
||||
restore, so a Save Point needs no restore machinery of its own.
|
||||
|
||||
What is deliberately absent from this module, because a second copy of any of it
|
||||
would be the failure M4 is warned about:
|
||||
|
||||
* no head fields are assigned here — `head.move_to_node` moves the head, and
|
||||
`head.move_to` under it restores the state, exactly as Undo and Redo do;
|
||||
* nothing reconstructs state, prunes a memory, copies a turn, or deletes one;
|
||||
* nothing forks. Restore is not a decision to abandon anything, so it creates no
|
||||
branch. The first write below the restored head forks, through the same
|
||||
`fork_if_behind_head` every other write goes through, and the displaced future
|
||||
stays retained (`STORY-BRANCH-SEMANTICS.md` §20).
|
||||
|
||||
The user-facing word is "Save Point" and the internal one is `checkpoint`
|
||||
(`BROWSER-UX-SPEC.md` §23). Error strings here are read by a player, so they say
|
||||
Save Point.
|
||||
"""
|
||||
|
||||
from fastapi import Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ... import head, models, schemas
|
||||
from ...context import lineage
|
||||
from ...database import get_db
|
||||
|
||||
from . import turns
|
||||
from .deps import current_adventure, router
|
||||
from .paging import current_window
|
||||
|
||||
|
||||
def _node_at(
|
||||
db: Session, adventure: models.Adventure, branch_id: int, depth: int
|
||||
) -> models.Action | None:
|
||||
"""Returns the live turn a Save Point's coordinate names, or None.
|
||||
|
||||
The lookup is by coordinate and is not scoped to any path. That is the
|
||||
point of it: a Save Point outlives the reader moving away, so the question
|
||||
it has to answer is "is this position still in this campaign's retained
|
||||
history", not "is it on the story being read now". Whether it is on the
|
||||
current path is a separate question, and `head.move_to_node` is what acts on
|
||||
the answer.
|
||||
|
||||
`live` is what makes the coordinate follow a retry. One coordinate can hold
|
||||
several attempts at a turn, and a Save Point names the turn rather than the
|
||||
attempt, so it lands on whichever take the story currently tells.
|
||||
"""
|
||||
return (
|
||||
db.query(models.Action)
|
||||
.filter(
|
||||
models.Action.adventure_id == adventure.id,
|
||||
models.Action.branch_id == branch_id,
|
||||
models.Action.depth == depth,
|
||||
models.Action.live.is_(True),
|
||||
)
|
||||
.order_by(models.Action.id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _rendered(
|
||||
db: Session, adventure: models.Adventure, checkpoint: models.Checkpoint
|
||||
) -> schemas.CheckpointOut:
|
||||
"""Reads one Save Point out with the three facts the panel needs about it."""
|
||||
node = _node_at(db, adventure, checkpoint.branch_id, checkpoint.depth)
|
||||
out = schemas.CheckpointOut.model_validate(checkpoint)
|
||||
# The same `depth + 1` the branch list counts with, so "turn 42" means the
|
||||
# same thing in both places.
|
||||
out.turn = checkpoint.depth + 1
|
||||
out.resolved = node is not None
|
||||
out.on_path = node is not None and lineage.path_of(db, adventure).uncapped().contains(node)
|
||||
return out
|
||||
|
||||
|
||||
def _get_or_404(
|
||||
db: Session, adventure: models.Adventure, checkpoint_id: int
|
||||
) -> models.Checkpoint:
|
||||
"""Resolves a Save Point id, refusing one that belongs to another campaign.
|
||||
|
||||
The ownership check is the reason this is a function rather than a `db.get`
|
||||
at each call site. A Save Point names a position in one campaign's history,
|
||||
and a coordinate from another campaign would name a different story's turn —
|
||||
or, worse, resolve against this one by arithmetic coincidence. So the id is
|
||||
matched against this adventure, and a Save Point belonging to another is a
|
||||
404 rather than a restore of the wrong story.
|
||||
"""
|
||||
checkpoint = db.get(models.Checkpoint, checkpoint_id)
|
||||
if checkpoint is None or checkpoint.adventure_id != adventure.id:
|
||||
raise HTTPException(404, "Save Point not found")
|
||||
return checkpoint
|
||||
|
||||
|
||||
def _clean_name(raw: str) -> str:
|
||||
"""Returns the trimmed name, refusing one that is blank once trimmed."""
|
||||
name = (raw or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(400, "A Save Point needs a name.")
|
||||
return name
|
||||
|
||||
|
||||
@router.get("/{adventure_id}/checkpoints", response_model=list[schemas.CheckpointOut])
|
||||
def list_checkpoints(
|
||||
db: Session = Depends(get_db),
|
||||
adventure: models.Adventure = Depends(current_adventure),
|
||||
):
|
||||
"""Returns the campaign's Save Points, newest first.
|
||||
|
||||
Newest first rather than in story order, because story order is not
|
||||
something this list can honestly claim. Depths are positions along a path,
|
||||
and two Save Points on lines that parted company are not comparable by depth
|
||||
at all — ordering by it would draw a sequence that no reading of the story
|
||||
passes through. When they were made is a fact about all of them.
|
||||
"""
|
||||
rows = (
|
||||
db.query(models.Checkpoint)
|
||||
.filter(models.Checkpoint.adventure_id == adventure.id)
|
||||
.order_by(models.Checkpoint.created_at.desc(), models.Checkpoint.id.desc())
|
||||
.all()
|
||||
)
|
||||
return [_rendered(db, adventure, row) for row in rows]
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{adventure_id}/checkpoints",
|
||||
response_model=schemas.CheckpointOut,
|
||||
status_code=201,
|
||||
)
|
||||
def create_checkpoint(
|
||||
payload: schemas.CheckpointCreate,
|
||||
db: Session = Depends(get_db),
|
||||
adventure: models.Adventure = Depends(current_adventure),
|
||||
):
|
||||
"""Names the position the story is currently being read at.
|
||||
|
||||
The active head, not the retained tip. Creating a Save Point after two Undos
|
||||
saves the undone position, because that is where the reader is and the
|
||||
position they are looking at is the one they mean. The distinction only
|
||||
exists at all because M3 stopped Undo from deleting.
|
||||
|
||||
The node at the head is resolved before the row is written, and its own
|
||||
branch is what gets stored — which is not always the branch being read. A
|
||||
head resting in a shared prefix sits on an ancestor's node, and the
|
||||
ancestor is the branch that still names that position after the reader has
|
||||
forked away from it.
|
||||
"""
|
||||
name = _clean_name(payload.name)
|
||||
node = head.node_at(db, adventure, adventure.head_depth)
|
||||
if node is None:
|
||||
raise HTTPException(400, "There is no turn here to save yet.")
|
||||
checkpoint = models.Checkpoint(
|
||||
adventure_id=adventure.id,
|
||||
name=name,
|
||||
note=payload.note or "",
|
||||
branch_id=node.branch_id,
|
||||
depth=node.depth,
|
||||
)
|
||||
db.add(checkpoint)
|
||||
db.commit()
|
||||
db.refresh(checkpoint)
|
||||
return _rendered(db, adventure, checkpoint)
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/{adventure_id}/checkpoints/{checkpoint_id}",
|
||||
response_model=schemas.CheckpointOut,
|
||||
)
|
||||
def rename_checkpoint(
|
||||
checkpoint_id: int,
|
||||
payload: schemas.CheckpointRename,
|
||||
db: Session = Depends(get_db),
|
||||
adventure: models.Adventure = Depends(current_adventure),
|
||||
):
|
||||
"""Changes a Save Point's label. Nothing else about it moves.
|
||||
|
||||
Not the coordinate, not the head, not a row of story. A Save Point that has
|
||||
been renamed restores to exactly the position it did before, which is
|
||||
`STORY-BRANCH-SEMANTICS.md` §23.
|
||||
"""
|
||||
checkpoint = _get_or_404(db, adventure, checkpoint_id)
|
||||
if payload.name is not None:
|
||||
checkpoint.name = _clean_name(payload.name)
|
||||
if payload.note is not None:
|
||||
checkpoint.note = payload.note
|
||||
db.commit()
|
||||
db.refresh(checkpoint)
|
||||
return _rendered(db, adventure, checkpoint)
|
||||
|
||||
|
||||
@router.delete("/{adventure_id}/checkpoints/{checkpoint_id}", status_code=204)
|
||||
def delete_checkpoint(
|
||||
checkpoint_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
adventure: models.Adventure = Depends(current_adventure),
|
||||
):
|
||||
"""Removes the named pointer, and only the pointer.
|
||||
|
||||
The turn it named stays, its branch stays, the future past it stays, and the
|
||||
head does not move. This endpoint deletes one row of the `checkpoints`
|
||||
table. `STORY-BRANCH-SEMANTICS.md` §25.
|
||||
"""
|
||||
checkpoint = _get_or_404(db, adventure, checkpoint_id)
|
||||
db.delete(checkpoint)
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{adventure_id}/checkpoints/{checkpoint_id}/restore",
|
||||
response_model=schemas.ActionPage,
|
||||
)
|
||||
def restore_checkpoint(
|
||||
adventure_id: int,
|
||||
checkpoint_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
adventure: models.Adventure = Depends(current_adventure),
|
||||
):
|
||||
"""Returns the story to a Save Point, deleting nothing.
|
||||
|
||||
Four steps, and the last one is not this module's code: resolve the
|
||||
coordinate, refuse it if it no longer names a live turn, hand it to
|
||||
`head.move_to_node`, and answer with the window the head now caps. The
|
||||
transcript, the world state, the assembled context and which memories can be
|
||||
retrieved all move together, because all four already read through the one
|
||||
path object the head caps — the same reason Undo needed no memory pruning.
|
||||
|
||||
The turns past the restored position are retained, exactly as they are after
|
||||
an Undo, and ordinary Redo can still walk forward into them until the user
|
||||
writes something different. Restore does not fork; the first write below the
|
||||
head does.
|
||||
|
||||
A coordinate that no longer resolves is refused rather than approximated.
|
||||
Moving the head to the nearest surviving turn would be the one outcome worse
|
||||
than doing nothing: a Save Point that silently means somewhere else.
|
||||
"""
|
||||
checkpoint = _get_or_404(db, adventure, checkpoint_id)
|
||||
turns.acquire_turn_lock(adventure_id)
|
||||
try:
|
||||
node = _node_at(db, adventure, checkpoint.branch_id, checkpoint.depth)
|
||||
if node is None:
|
||||
raise HTTPException(
|
||||
409,
|
||||
"That Save Point's position is no longer part of this story.",
|
||||
)
|
||||
head.move_to_node(db, adventure, node)
|
||||
adventure.updated_at = models.utcnow()
|
||||
db.commit()
|
||||
db.refresh(adventure)
|
||||
# A window, not the whole story, for the reason Undo gives: the client
|
||||
# replaces its transcript with this, and the transcript is a window.
|
||||
return current_window(db, adventure)
|
||||
finally:
|
||||
turns._active_turns.discard(adventure_id)
|
||||
@@ -25,6 +25,10 @@ ICON_MAX = 16 # One emoji or glyph. VARCHAR(16).
|
||||
BRANCH_NAME_MAX = 80 # What a player called one line of the story. VARCHAR(80).
|
||||
PERSONA_NAME_MAX = 80 # The protagonist's name. VARCHAR(80).
|
||||
PERSONA_PRONOUNS_MAX = 40 # "they/them" and the like. VARCHAR(40).
|
||||
# M4: what a player called a Save Point. VARCHAR(120). Wider than a branch name
|
||||
# because these are sentences rather than labels — "Before entering the abbey"
|
||||
# is the example the specification uses throughout.
|
||||
CHECKPOINT_NAME_MAX = 120
|
||||
|
||||
Name = Annotated[str, Field(max_length=NAME_MAX)]
|
||||
Tags = Annotated[str, Field(max_length=TAGS_MAX)]
|
||||
@@ -35,6 +39,7 @@ Image = Annotated[str, Field(max_length=IMAGE_MAX)]
|
||||
Icon = Annotated[str, Field(max_length=ICON_MAX)]
|
||||
PersonaName = Annotated[str, Field(max_length=PERSONA_NAME_MAX)]
|
||||
PersonaPronouns = Annotated[str, Field(max_length=PERSONA_PRONOUNS_MAX)]
|
||||
CheckpointName = Annotated[str, Field(max_length=CHECKPOINT_NAME_MAX)]
|
||||
|
||||
|
||||
class ORMModel(BaseModel):
|
||||
@@ -267,6 +272,67 @@ class BranchRename(BaseModel):
|
||||
name: Annotated[str, Field(max_length=BRANCH_NAME_MAX)] | None = None
|
||||
|
||||
|
||||
# ---------- Save Points (M4) ----------
|
||||
#
|
||||
# "Save Point" is the user-facing term and `checkpoint` is the internal one
|
||||
# (`BROWSER-UX-SPEC.md` §23). The wire format uses the internal name, as the
|
||||
# rest of this module does.
|
||||
|
||||
|
||||
class CheckpointOut(ORMModel):
|
||||
"""One Save Point: a name and the position it names.
|
||||
|
||||
The position is reported three ways because the panel needs three different
|
||||
things from it. `turn` is what a reader counts — the same `depth + 1` the
|
||||
branch list shows. `depth` and `branch_id` are the coordinate itself.
|
||||
`on_path` says whether the position lies on the story being read, which is
|
||||
how the panel can tell a Save Point on this line from one naming a line the
|
||||
story has left; restoring either works, but they are not the same offer.
|
||||
|
||||
`resolved` is false when the coordinate no longer names a live turn, which
|
||||
an action deleted out of the middle of a story can do. Restore refuses such
|
||||
a Save Point rather than moving the head somewhere approximate, so the list
|
||||
says so before the button is pressed.
|
||||
"""
|
||||
|
||||
id: int
|
||||
adventure_id: int
|
||||
name: str
|
||||
note: str = ""
|
||||
branch_id: int
|
||||
depth: int
|
||||
turn: int = 0
|
||||
on_path: bool = True
|
||||
resolved: bool = True
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class CheckpointCreate(BaseModel):
|
||||
"""A Save Point at wherever the story is being read.
|
||||
|
||||
The position is not a field. A Save Point is made at the campaign's active
|
||||
head, which the server already knows, and accepting a coordinate from the
|
||||
client would be the second way to name a position — the thing this milestone
|
||||
exists not to build.
|
||||
"""
|
||||
|
||||
name: CheckpointName
|
||||
note: Prose = ""
|
||||
|
||||
|
||||
class CheckpointRename(BaseModel):
|
||||
"""A new label, and nothing else.
|
||||
|
||||
There is deliberately no coordinate here. `STORY-BRANCH-SEMANTICS.md` §24
|
||||
keeps a Save Point's meaning auditable by refusing to move one: rename it,
|
||||
or delete it and make another where you are.
|
||||
"""
|
||||
|
||||
name: CheckpointName | None = None
|
||||
note: Prose | None = None
|
||||
|
||||
|
||||
class ActionUpdate(BaseModel):
|
||||
text: ActionText
|
||||
|
||||
|
||||
Reference in New Issue
Block a user