# Undo/redo & autosave — behavior per surface (P16.3)

Every editing surface in the workbench falls into exactly one of four classes.
The class decides what ⌘Z does there, what survives a killed tab, and why. If
you add a surface, add it to a table below — a surface missing from this
document is a review finding, not a default.

## The rules the classes share

- **Undo depth.** The solo command stack refuses construction below 50 entries
  (`MINIMUM_UNDO_DEPTH`) and defaults to 100; the CRDT undo manager is
  unbounded. Both clear the checklist floor of 50.
- **Shortcut scope.** ⌘Z / ⇧⌘Z / Ctrl-Y are bound per editor region
  (`useUndoRedoShortcuts` returns props the editor spreads on its root), never
  on `window`. The develop ladder mounts over a dozen editors at once; a global
  listener per editor would undo something in every one of them on a single
  keystroke. The editor that responds is the one holding focus; with focus
  outside every editor the keys do nothing, and the history bar's buttons
  remain.
- **Text fields.** A field whose edits are recorded in the command stack carries
  `data-history-managed` and routes ⌘Z to the stack. A field without it (search
  boxes, staging forms) keeps the browser's native undo. Both by design.
- **Drafts mirror unsaved edits, not the buffer.** Autosave (800 ms debounce,
  localStorage, 7-day cap) writes only after a real edit; a session that only
  _looked_ writes nothing, and a completed save discards the draft. A recovered
  draft is **offered with its age, never applied** — restore and discard get
  equal visual weight.
- **The kill test.** The recovery contract is stated as a test: kill the tab
  mid-edit, reopen, the draft is offered. It is exercised in
  `src/lib/use-editor-history.spec.tsx` ("offers a draft after the tab is
  killed…") by ripping the container out with no unmount, no effect cleanup and
  no unload handler, then mounting fresh.

## Class 1 — solo editors: command stack + local drafts

Buffer edited locally until an explicit Save; a killed tab would lose minutes of
composition. Each uses `useEditorHistory` (stack, drafts, region shortcuts) and
renders `EditorHistoryBar` (undo/redo + the recovery prompt).

| Surface               | Component             | Draft key (`surface` · `id`)          |
| --------------------- | --------------------- | ------------------------------------- |
| Quick capture modal   | `QuickCapture`        | `quick-capture` · `global`            |
| Design pillars        | `PillarEditor`        | `pillars` · idea id                   |
| Core loop             | `CoreLoopDesigner`    | `core-loop` · idea id                 |
| Comps & positioning   | `PositioningPanel`    | `positioning` · idea id               |
| Systems sketch        | `SystemsSketchPanel`  | `systems-sketch` · idea id            |
| Blockout brief        | `BlockoutBriefPanel`  | `blockout-brief` · idea id            |
| Kit sheets            | `KitSheetEditor`      | `kit-sheet` · idea id                 |
| Prototype brief       | `PrototypeBriefPanel` | `prototype-brief` · idea id           |
| Scope inputs          | `ScopeEstimatePanel`  | `scope-estimate` · idea id            |
| Format decision       | `FormatDecisionPanel` | `format-decision` · idea id           |
| Series bible          | `SeriesBiblePanel`    | `series-bible` · idea id              |
| Episode grid          | `EpisodeGridPanel`    | `episode-grid` · idea id              |
| Breaking board        | `BreakingBoardPanel`  | `breaking-board` · idea id            |
| Casting sheets        | `CastingSheetPanel`   | `casting-sheets` · idea id            |
| Mood board composer   | `MoodBoardComposer`   | `mood-board` · `composer`             |
| Sonic board composer  | `SonicBoardComposer`  | `sonic-board` · `composer`            |
| Corkboard arrangement | `Corkboard`           | `corkboard` · beat-outline version id |

Canvas operations are first-class commands: a card drag coalesces into one undo
step per gesture (per-gesture coalesce keys, so back-to-back drags never merge),
add/remove are discrete steps, and compound edits (remove a loop node and its
edges; remove a comp and its matrix column) are one command so one undo restores
both halves.

Corkboard notes: the board is keyed by beat-outline version id, and a saved
arrangement creates a _new_ version — so a draft only resurfaces for the exact
version it was made against, and drafts for superseded versions age out without
ever being offered.

The panels' load-from-server effect is guarded by their dirty flag, and a
restored draft marks the editor dirty (`onRestore`); without that, the next
background refetch would reset the buffer and silently destroy the draft the
user just chose to keep.

## Class 2 — collaborative surfaces: CRDT history, no local drafts

| Surface           | Component   |
| ----------------- | ----------- |
| Shared idea board | `IdeaBoard` |

The board is a Yjs document (P7.1), so history is `Y.UndoManager` via
`useCrdtHistory`, tracking only transactions tagged with this client's origin —
undo reverts _your_ change and never a colleague's. Every mutation goes through
`withLocalOrigin`; an untagged change would be silently un-undoable, so there is
deliberately no second write path. Drag gestures close their undo step on
pointer-up (`endStep`), so two quick drags are two undos.

No local drafts here, on purpose: the CRDT document is the store and survives a
killed tab by construction. Layering localStorage drafts on top would create a
second source of truth that disagrees the moment a remote edit lands.

## Class 3 — immediate-commit surfaces: no local stack, by design

Every action is a server write the moment it happens; there is no local buffer
for a killed tab to lose, and "undo" would mean reversing a persisted, sometimes
audited, act — a different feature (versioning / revert) than an editor stack,
and pretending otherwise would revert things colleagues may already have seen.

| Surface                 | Where                       | The transient state at risk                                |
| ----------------------- | --------------------------- | ---------------------------------------------------------- |
| Quests page             | `pages/Quests.tsx`          | a 2-field create form                                      |
| Dialogue trees          | `pages/Dialogues.tsx`       | one node's line before "Save node"                         |
| Story graphs            | `pages/StoryGraphs.tsx`     | walkthrough save-states are domain saves, not editor state |
| Relationship web        | `pages/RelationshipWeb.tsx` | none — edge edits commit per action                        |
| Cultures                | `pages/Cultures.tsx`        | none — trait edits commit per action                       |
| Ideation inbox / triage | `pages/IdeationInbox.tsx`   | none — keep/park/kill are decisions                        |
| Tournament voting       | `pages/Tournament.tsx`      | none — votes are recorded judgments                        |
| Stage gates             | `StageGatePanel`            | a one-line note; the decision is audited                   |
| Product routing         | `ProductRoutingPanel`       | a one-line reason; routing is a decision                   |

The residual loss window is a single short field typed seconds before the act.
Browser-native undo covers typing there; nothing else exists to recover.

## Class 4 — read-only / generated panels: nothing to undo

`OnePagerPanel`, `TableReadPanel`, `NotesDashboardPanel`, `TitleClearancePanel`,
`GeneratorScoreboard`, the attribution panel and the diagnostics read-outs
render server-derived documents. They hold no editable buffer; their inputs (if
any) are filters.

`ScriptEditor` predates this checklist and is a controlled library component —
`value`/`onChange` belong to whoever mounts it, so history belongs to the
mounting surface, and it ships its own `useScriptEditorAutoSave` for the one
consumer that wants it.
