This page follows the data the engine keeps while a game runs, and the way the player goes back through it. It covers the stores on the monogatari object, the rules each one merges by, and the rollback path from the Back button to an action’s revert(). Read Architecture first for where these pieces sit, and Statements and Actions for the forward path this one undoes.

What it’s for

A visual novel needs to answer two questions at any moment: what is on screen, and how did it get there. Monogatari 2.9.0 answers them with separate stores:

  • state(): what the game shows now. The label and step, the scene and background, the characters, images, videos, canvas objects and particles on screen, the music, sounds and voice playing, whether the text box is hidden. A save stores it, and a load rebuilds the screen from it.
  • history(): how the game got there. One array per kind of thing (image, character, music, jump, choice…), with the statements that were applied, in order. Rollback reads it to undo them.
  • storage(): the game’s own variables, declared in js/storage.js and changed by the script ({{player.name}}, points, flags).
  • globals(): the engine’s runtime flags (is the game playing, is a choice waiting, is the type-writer done). Never saved.

Rollback is how the player goes back: the Back button of the quick menu, or the left arrow key. In v2 it doesn’t restore a copy of an earlier moment. It walks backwards through the script one statement at a time and asks each statement’s action to undo itself with its willRevert(), revert() and didRevert() methods, using what the action recorded in history() and state().

Saving and loading sit on top of these stores: a save is state, history and storage written to a slot (Saving and Loading).

The files

File What it does Cypress specs
src/monogatari.ts The stores and their defaults: _state, _history, _storage, _globals, _temp, _$, _functions; the accessors state(), history(), storage(), globals(), global(), temp(), $(), fn(), setting(), preference(); the public rollback(), previous() and revert() that delegate to lifecycle.ts; setup() captures storageStructure every spec in actions/ that rolls back
src/engine/lifecycle.ts rollback(), shouldRollback(), willRollback(), previous() and revert(): the whole rollback path; prepareAction() builds the instance to revert with cycle: 'Revert' actions/next.spec.js, actions/functions.spec.js, actions/reversible_functions.spec.js
src/engine/persistence.ts resetGame() (empties every history, resets step, label and storage, calls every action’s reset()), gameObject() (what a save holds) main_menu_after_load.spec.js, components/load-screen.spec.js
src/lib/Action.ts The revert hooks: willRevert(), revert(), didRevert() on instances; shouldRollback(), willRollback(), beforeRevert(), afterRevert(), reset() as statics none directly
src/lib/Component.ts, src/lib/ShadowComponent.ts The static shouldRollback()/willRollback() that call the same methods on every mounted instance, and onReset() none directly
src/lib/types/index.ts StateMap, HistoryMap, GlobalsMap and the item types each history holds none
src/actions/*.ts What each action records and how it undoes it (the table under Who records what) actions/<name>.spec.js for each
src/components/choice-container/index.ts, text-input/, message-modal/, centered-dialog/ willRollback() on the instance: remove what the waiting statement put on screen actions/choices.spec.js, actions/input.spec.js, actions/dialog.spec.js
src/components/game-screen/index.ts Registers the back listener (left arrow key) when AllowRollback is on at bind time none directly
src/components/quick-menu/index.ts Removes the Back button in init() when AllowRollback is off none directly
src/migrations/*.ts Rewrites old saves’ state and history to the current shapes none
node_modules/deeply/ The deep merge behind state(), storage(), globals(), settings() and preferences() none

How it works

The stores and how each one changes

Every store lives in a static field of the Monogatari class, and every accessor is a static method on it, so monogatari.state() in a game and this.engine.state() in an action reach the same data. They don’t all follow the same rules.

Store Read Write How a write works Saved Reset by resetGame()
state state(), state('key') state({ … }) deep merge into a new copy, with willUpdateState/didUpdateState events yes step and label only; each action’s reset() clears its own keys
history history(), history('key') push into the array you read; history({ key: [] }) replaces the arrays are live and changed in place; history(object) is a shallow Object.assign yes every key set to []
storage storage(), storage('key') storage({ … }) deep merge into a new copy, no events yes replaced with the structure captured at setup
globals globals(), global('key') global('key', value), globals({ … }) global() assigns one key; globals() deep merges no not as a whole; actions reset their own in reset()
temp temp('key') temp('key', value) reading a key deletes it no no
$ (placeholders) $('name') $('name', statement), $({ … }) Object.assign no no
settings setting('Key'), settings() setting('Key', value), settings({ … }) setting() assigns, settings() deep merges no (the game’s code sets them on every load) no
preferences preference('Key'), preferences() preference('Key', value), preferences({ … }, true) written to the storage engine under the Settings key in Settings, not in a slot no

The deep merge is the deeply package (version 3.1.0), bound once at the top of src/monogatari.ts as const merge = deeply.bind({}). Its default export is the immutable variant: merge(target, source) builds a deep copy of the target and merges the source into it. In practice, for state() and storage():

  • Objects merge key by key. storage({ player: { age: 18 } }) keeps player.name. storage({ player: {} }) changes nothing: an empty object has no keys to merge.
  • Arrays are replaced, never concatenated. state({ images: [] }) empties the list; state({ images: [...state('images'), statement] }) adds to it.
  • null replaces the value. undefined sets the key to undefined: the key stays in the object.
  • Every write makes a new object. state() returns a different object after each state({ … }) call, and an array you read with state('images') before a write is not the one in the store after it.

state(object) also fires two events on the <visual-novel> element: willUpdateState with { oldState, newState } before it replaces _state, and didUpdateState with { oldState, newState } after. oldState is a shallow copy taken before the merge. game-screen listens to didUpdateState to set its data-label attribute. Nothing fires for history(), storage() or globals().

global('key') returns this._globals?.[key] ?? undefined, so a global set to null reads back as undefined. global('key', undefined) changes nothing, because the setter only writes when the value isn’t undefined.

history('key') creates an empty array the first time a key is read, which is how actions declare their histories in setup() (this.engine.history('image')). Since resetGame() loops over the keys of _history, a key created this way is emptied on reset like the built-in ones.

What the defaults are

_state starts with step: 0, label: 'Start' and one key per kind of thing on screen; actions re-declare their own keys in setup(). init() sets label to the Label setting before the game starts. _history starts with twenty-seven keys: label, music, sound, voice, mediaChanges, scene, background, sceneElements, sceneState, character, characterLayer, image, hideImage, particle, video, hideVideo, canvas, hideCanvas, nvl, clear, choice, choiceOutcome, jump, conditional, particleState, gallery, textbox. The shapes are under The data.

setup() saves JSON.stringify(this.storage()) in the storageStructure global after the preferences load, before the components and actions are set up. Whatever js/storage.js declared before init() is what a reset goes back to.

Who records what

The built-in actions follow one pattern, unified in commit 8d98ad9d (“Ensure we handle state and history the same across actions”):

  • An action that shows something pushes its statement onto its history and adds it to its state key in didApply(). didApply({ updateHistory, updateState }) takes two flags, so the same action can be applied again during a load or a revert without recording twice.
  • An action that hides something only removes the matching entry from the state. To undo, it searches the history backwards for the last statement that showed the same asset and applies it again with updateHistory: false.
  • The show action’s own revert removes the element, removes its entry from the history (splice of the last match) and filters the state.
Action (id) State key History key What revert() does
Show::Image, Hide::Image images image; hideImage ({ asset, statements }: the show image statements of the copies each hide removed) Show removes the element and its entries; Hide applies again every statement it removed (the last show image for that asset, with a save from before 2.9.0)
Show::Character, Hide::Character characters (one statement per character); characterLayers with experimental features character ({ statement, previous }); characterLayer with experimental features Show removes the sprite and applies previous, the statement it replaced; Hide applies the last show character for that character again
Show::CharacterLayer, Hide::CharacterLayer (experimental) characterLayers characterLayer the same pattern, per layer
Scene scene; clears characters and images scene, sceneElements, sceneState (and background, through the show background it runs) reverts that background, puts back the sprites and images from sceneElements and their state from sceneState, and the text box mode
Show::Background background background (falls back to scene) pops its entry and applies the previous background
Play music, sound, voice ({ statement, paused } items, one per track) music, sound, voice (statements); mediaChanges ({ type, name, replaced } for a track already there, { type, resumed } for a plain play <kind>) removes the player, its history entry and its state item; puts a replaced track back as it was; pauses what a plain play resumed
Stop the media type’s key stopping everything pushes the whole state array onto the type’s history; a named stop pushes { type, name, stopped } onto mediaChanges plays again what it stopped, paused if it was
Pause the paused flag of the media items mediaChanges ({ type, paused }: the tracks it paused) plays again what it paused and clears their flag
Show::Video, Hide::Video videos video; hideVideo (the statement of the video each hide removed, or null) Show removes the element and its entries; Hide applies again the show video it removed, if it removed one
Canvas, HideCanvas canvas canvas; hideCanvas (the show canvas statement each hide in the script removed; a hide a canvas runs from its own code records nothing) Canvas calls the object’s stop, removes the container and its entries (only the entries when its own code already hid it); its static willRollback() does the same for a waiting modal or immersive canvas; HideCanvas applies again the statement it recorded, or the last matching show canvas for a hide from before 2.9.0
Particles, HideParticles particles (one statement) particle, and particleState (what showed before each show or hide particles) both stop the particles and apply again the particleState entry they pushed, if it isn’t empty
Hide::TextBox, Show::TextBox textboxHidden textbox (whether the text box was hidden before each show or hide textbox) sets the text box’s hidden state back to the entry they pushed
Dialog none nvl (the NVL text box HTML, saved when it is cleared) applies the line again (ADV), or removes the last NVL entry or restores the saved NVL HTML (Text and the Type-Writer)
Clear none clear (the text box mode when it ran) flags _should_restore_nvl when it cleared an NVL box
Jump label, step jump ({ source, destination }), label ({ label, step }) puts label and step back to the jump’s source; didRevert() pops both histories
Choice answeredChoice (where the choice is and the option picked, while the line its Do showed is on screen at the choice’s own step) choice (the key of the option picked, pushed by the click handler), choiceOutcome ({ label, step, option } for each choice gone through, option: null when every option was hidden, plus the NVL page the menu was on) reverts the option’s Do without advancing, runs its onRevert, puts back the NVL page, shows the menu again; a choice passed over returns { advance: true, step: true } like next
Conditional none conditional (the branch taken) reverts the statement of that branch
Input none (the game’s Save writes storage) none runs the statement’s Revert and shows the input again
Function none none runs the statement’s Revert
Message none none shows the message again
Gallery none (the gallery screen’s state) gallery (whether the image was unlocked or locked before) puts the image back as the entry says
Next, Wait, Notify, Vibrate, Preload, Unload none none nothing to undo; didRevert() says advance: true so the rollback goes on
End none none can’t be reverted: willRevert() throws
Placeholder the stood-for action’s the stood-for action’s builds the stood-for statement’s action and forwards each revert method to it

Choice, Conditional and Input also keep globals (_CurrentChoice, _ChoiceTimer, _choice_pending_rollback, _choice_just_rolled_back, _conditional_pending_rollback, _conditional_just_rolled_back, _InputTimer, _input_just_rolled_back). Their static afterRevert() reads them to tell whether the revert that ran last was their own, and clean up a timer if it wasn’t.

A worked example

With this script (and TypeAnimation off), here is what the stores hold. The values were read from a running game.

monogatari.script({
  'Start': [
    'One',
    'show image polaroid at left',
    'Two',
    'end',
  ],
});
Moment step state('images') history('image') Text box
The game starts 0 [] [] One
The player clicks: the image shows and advances on its own 2 ['show image polaroid at left'] ['show image polaroid at left'] Two
The player presses Back 0 [] [] One

One Back undid two statements. The next sections explain how.

Rollback, step by step

The Back button runs the back listener, which calls monogatari.rollback(). rollback() in src/engine/lifecycle.ts:

  1. Returns without doing anything when the AllowRollback setting isn’t true.
  2. At step 0, looks in history('jump') for a jump whose destination is the current label at step 0. Without one, this is the beginning of the game: it returns.
  3. Awaits shouldRollback(). It refuses (rejects) when distraction_free or the deprecated block global is set, or when _engine_block is set while _executing_sub_action isn’t. Otherwise it asks every action’s static shouldRollback() and every component’s (which asks each mounted instance): any rejection refuses the rollback.
  4. Sets _engine_block, so a click on the game while the rollback runs is refused by shouldProceed().
  5. Awaits willRollback() on every action and component. This is where the current statement cleans up: the statement on screen is not the one that gets reverted, so whatever it showed and waits on has to go here. choice-container, text-input, message-modal and centered-dialog remove themselves; Choice, Wait, Input, Message and Notify clear their blocking flag; Play stops the voice; Dialog marks the type-writer finished and removes the line’s entry from the dialog log.
  6. Calls previous(), which runs revert() from a setTimeout(…, 0) and clears _engine_block when it settles.

revert(statement = null, shouldAdvance = true, shouldStepBack = true) does the undoing:

  1. Awaits every action’s static beforeRevert({ advance, step }), whether or not it is the action being reverted.
  2. Picks the statement to undo: the statement it was given, or the one before the current step (label[step - 1]), or at step 0 the jump that led here (it moves label and step to the jump’s source first, so the statement is that jump).
  3. With nothing to undo, it runs the current statement again and resolves.
  4. A JavaScript function can’t be undone: revert() rejects.
  5. Builds a new instance with prepareAction(statement, { cycle: 'Revert' }). It is not the instance that applied the statement: anything the revert needs must come from the statement, the history, the state or the globals.
  6. Fires willRevertAction, then awaits willRevert(), revert() and didRevert(), which returns { advance, step }. Fires didRevertAction, then awaits every action’s afterRevert({ advance, step }).
  7. If step is true and the caller allowed it (shouldStepBack), sets step to step - 1.
  8. If advance is true and the caller allowed it (shouldAdvance), schedules another revert() with setTimeout(…, 0), which undoes the statement before that one.
sequenceDiagram actor Player participant Back as back listener participant RB as rollback() participant Prev as previous() participant Rev as revert() participant All as every action and component participant Act as the action to undo Player->>Back: Back button or left arrow Back->>RB: rollback() Note over RB: AllowRollback off, or step 0 with no jump here: stop RB->>All: shouldRollback() All-->>RB: any rejection refuses RB->>RB: _engine_block = true RB->>All: willRollback(): the statement on screen cleans up RB->>Prev: previous() Prev->>Rev: revert() in a setTimeout Rev->>All: beforeRevert({ advance, step }) Rev->>Act: prepareAction(label[step - 1], cycle Revert) Rev->>Act: willRevert(), revert(), didRevert() Act-->>Rev: { advance, step } Rev->>All: afterRevert({ advance, step }) Note over Rev: step true: step - 1 alt advance true Rev->>Rev: revert() again in a setTimeout else Rev-->>Prev: resolved, the game waits end Prev->>Prev: _engine_block = false

In the worked example, the player is on 'Two' at step 2. revert() undoes label[1], the show image: it removes the image and its entries, and its didRevert() returns { advance: true, step: true }. The step goes to 1 and a second revert() undoes label[0], the line 'One': Dialog’s revert() applies the line again (its _cycle is 'Revert', so the dialog log isn’t written twice) and returns { advance: false, step: true }. The step goes to 0 and the game waits on 'One'.

So reverting a line of dialog shows it. The rollback always ends on a statement whose didRevert() says advance: false, and that is the statement on screen.

Which statement gets reverted

flowchart TD start(["revert(statement, shouldAdvance, shouldStepBack)"]) --> given{"statement given?"} given -- yes --> target["Undo that statement"] given -- no --> step{"step >= 1?"} step -- yes --> before["Undo label[step - 1]"] step -- no --> jump{"A jump in history('jump')<br/>to this label at step 0?"} jump -- yes --> source["Move label and step to the jump's source,<br/>undo the jump statement there"] jump -- no --> none["Nothing to undo:<br/>run the current statement again"] target --> kind{"A JavaScript function?"} before --> kind source --> kind kind -- yes --> reject(["Reject: previous() catches it"]) kind -- no --> prepare["prepareAction(..., cycle Revert)"]

Three actions call revert() with a statement of their own, to undo a statement nested in theirs: Choice reverts the option’s Do with shouldAdvance: false; Conditional reverts the statement of the branch it took; Scene reverts the show background it ran with shouldAdvance: false, shouldStepBack: false, so the step moves only once, for the scene.

Going back across a jump

Jump.apply() pushes { source: { label, step }, destination: { label: target, step: 0 } } onto history('jump'), sets label and step, runs the target’s first statement, and pushes { label: target, step: 0 } onto history('label').

When the player presses Back at step 0 of the target label, rollback() finds that entry and lets the rollback start. revert() moves label and step to the jump’s source and undoes the jump statement there: Jump.revert() sets the same source position, and Jump.didRevert() pops both histories and returns { advance: true, step: false }. The step stays on the jump, and the next revert() undoes the statement before it. With ['A0', 'A1', 'jump Other'] in Start and ['B0', 'B1'] in Other, Back on B0 shows A1, at Start step 1, with both histories empty again. Exercise 3 checks every step of it.

When a rollback can’t go back

A rollback that can’t undo a statement leaves the player where they were. There are two ways it fails, handled in two places:

  • willRevert(), revert() or didRevert() throws or rejects. revert() catches it, logs it with console.error (when it is an object or a string), puts label and step back to where they were when it started (going back across a jump had moved them to the jump’s source), runs the statement at the current step again with engine.run(), and resolves. End does this on purpose (willRevert() throws), and so does Choice when the option picked has an onChosen without an onRevert, and Input without a Revert.
  • revert() itself rejects: the statement is a JavaScript function, no action matched it, or a beforeRevert() hook rejected. When going back from the first statement of a label had moved label and step to the jump’s source, revert() puts them back first. previous() catches the rejection, clears _engine_block, moves step back by one and calls proceed(), whose next() moves the step forward again and runs the statement on screen once more. At step 0 there is no step before it, so previous() runs label[0] again in place with engine.run(). Before 2.9.0 the game stayed at the jump’s source instead: going back from the first line of a label that a function statement jumped to ran the function again, and its side effects with it.

Either way, the statement on screen runs again. Dialog’s willRollback() already removed its entry from the dialog log, so running the line again writes it back once.

A statement that failed when it ran is different again: revert() doesn’t call its action at all. run() records the positions whose statement failed, and revert() steps over one of those (it moves step back and reverts the statement before it), since there is nothing to undo (Statements and Actions).

A {'Function': { Apply, Revert }} statement without Revert is different: revert() calls Util.callAsync(undefined, …), which fails inside the Function action’s own revert(). That catch shows the action:function:revert_error dialog and the rollback goes on, past a statement whose effect was not undone.

Resetting

resetGame() in src/engine/persistence.ts runs when end finishes a game and at the start of every load. It turns off auto-play and skip, replaces the storage with storageStructure, sets step to 0 and label to the Label setting, clears the deprecated block global, sets every history key to [], and awaits every action’s reset() and every component’s onReset(). Each action’s reset() removes what it showed and resets its own state keys (images, characters, scene, music…) and globals.

Settings and preferences, in brief

A setting (monogatari.setting('Name')) is the game’s configuration, written in js/options.js: it is code, read again every time the page loads, and never saved. A preference (monogatari.preference('TextSpeed')) belongs to the player: setup() reads the saved ones from the storage engine under the Settings key and merges them over the defaults, and preference(key, value) writes them back. Neither is part of a save slot. The Configuration pages list both.

The data

The types are in src/lib/types/index.ts. Every map has an index signature ([key: string]: unknown), so a game or an action can add keys, and TypeScript users can extend them through declaration merging.

interface MediaStateItem {
  statement: string;
  paused: boolean;
}

interface StateMap {
  step: number;
  label: string;
  music: MediaStateItem[];
  sound: MediaStateItem[];
  voice: MediaStateItem[];
  scene: string;
  background: string;
  characters: string[];
  characterLayers: string[];
  images: string[];
  particles: string;
  videos: string[];
  canvas: string[];
  textboxHidden: boolean;
  [key: string]: unknown;
}

Every value in the state is a statement as the script wrote it ('show image polaroid at left'), except step, label, textboxHidden and the media items. A load runs those statements again to draw the screen.

interface CharacterHistoryItem {
  statement: string;
  previous: string | null;
}

interface CharacterLayerHistoryItem {
  parent: string | null;
  layers: Array<{
    statement: string | null;
    previous: string | null;
  }>;
}

interface SceneStateItem {
  characters: string[];
  images: string[];
  textBoxMode?: string;
}

interface LabelHistoryItem {
  label: string;
  step: number;
}

interface JumpHistoryItem {
  source: { label: string; step: number };
  destination: { label: string; step: number };
}

type MediaHistoryItem = string | MediaStateItem[];

interface HistoryMap {
  label: LabelHistoryItem[];
  music: MediaHistoryItem[];
  sound: MediaHistoryItem[];
  voice: MediaHistoryItem[];
  scene: string[];
  background: string[];
  sceneElements: string[][];
  sceneState: SceneStateItem[];
  character: CharacterHistoryItem[];
  characterLayer: CharacterLayerHistoryItem[];
  image: string[];
  particle: string[];
  video: string[];
  canvas: string[];
  nvl: string[];
  clear: string[];
  choice: string[];
  conditional: string[];
  jump: JumpHistoryItem[];
  particleState: string[];
  gallery: string[];
  textbox: boolean[];
  [key: string]: unknown[];
}

sceneElements holds the outerHTML of every visible sprite and image when a scene replaced them; MediaHistoryItem is a string for a play and a whole state array for a stop that stopped everything.

The revert methods pass this around:

interface ActionRevertResult {
  advance: boolean;
  step: boolean;
}

interface ActionRevertContext {
  advance: boolean;
  step: boolean;
}

didRevert() returns an ActionRevertResult; beforeRevert() receives the caller’s shouldAdvance and shouldStepBack as an ActionRevertContext, and afterRevert() receives the result of didRevert(). The base class’s didRevert() returns { advance: false, step: true }.

The globals rollback depends on, from GlobalsMap:

interface GlobalsMap {
  playing: boolean;
  distraction_free: boolean;
  _restoring_state: boolean;
  _engine_block: boolean;

  /** @deprecated Each action should use its `blocking` attribute */
  block: boolean;

  /** @deprecated Each action should use its `blocking` attribute */
  _executing_sub_action: boolean;

  storageStructure: string;
  _dialog_pending_revert: boolean;
  _should_restore_nvl: boolean;
  _scene_history_cleared_by_background: boolean;
  _choice_pending_rollback: boolean[];
  _choice_just_rolled_back: boolean[];
  _conditional_pending_rollback: boolean[];
  _conditional_just_rolled_back: boolean[];
  _input_just_rolled_back: boolean;

  // …and the others listed in src/lib/types/index.ts
  [key: string]: unknown;
}

What a save holds, from gameObject() in src/engine/persistence.ts and SaveGameData:

interface SaveGameData {
  state: Record<string, unknown>;
  history: Record<string, unknown[]>;
  storage: Record<string, unknown>;
}

Rules and why

  • Back undoes the statement before the one on screen. The statement on screen is never reverted: it is a statement that waits (a line, a choice, an input), and the revert of the statement before it replaces it. So a statement that waits cleans up its own elements in a static willRollback() (or a component’s instance willRollback()), never in revert().
  • didRevert() mirrors didApply(). An action that advanced on its own returns advance: true from didRevert(), so the rollback keeps going until it reaches a statement that waited. One that waited returns advance: false. Get it wrong and Back seems to do nothing (Exercise 1), or skips past a line.
  • Record what you need to undo. The revert runs on a new instance built from the statement. What it must restore (what was there before, which option was picked, which branch was taken) has to be in history(), in state() or recomputable from the statement.
  • Record twice: history to undo, state to rebuild. history answers “what to put back”; state answers “what is on screen”, which a save stores and a load draws. An action that shows something writes both, and takes updateHistory/updateState flags in didApply() so a load or a revert can apply it again without recording it twice.
  • Never keep a reference to something you read from state() or storage(). Every merge replaces the object. Build a new array or object and write it: state({ images: [...state('images'), statement] }).
  • storage({ key: {} }) doesn’t clear a nested object. Pass null or the complete new value.
  • Test a global for “not set” with == null or a truthiness check. global() turns null into undefined, so global('skip') !== null is always true.
  • A plain JavaScript function in the script stops rollback. It can’t be reverted, so the player stays after it. A game that needs to undo code uses {'Function': { Apply, Revert }}. Step 0 of the starting label stops it too: there is nothing before it.
  • AllowRollback: false turns the whole path off: rollback() returns at once, the quick menu loses its Back button in init(), and game-screen doesn’t register the back listener. The last two read the setting once, when the game starts, so changing it later only affects rollback().

How to make the common changes

Make a new action that shows something reversible

Follow Show::Image (src/actions/ShowImage.ts). Declare the history and the state key in setup(), clear the state in reset(), record in didApply(), undo in revert() and didRevert():

static override async setup(): Promise<void> {
  this.engine.history ('stamp');
  this.engine.state({ stamps: [] });
}

static override async reset(): Promise<void> {
  this.engine.element().find ('[data-stamp]').remove();
  this.engine.state({ stamps: [] });
}

override async didApply({ updateHistory = true, updateState = true } = {}): Promise<ActionApplyResult> {
  if (updateHistory === true) {
    (this.engine.history ('stamp') as string[]).push(this._statement as string);
  }

  if (updateState === true) {
    this.engine.state({ stamps: [...(this.engine.state ('stamps') as string[]), this._statement as string] });
  }

  return { advance: true };
}

override async revert(): Promise<void> {
  this.engine.element().find (`[data-stamp="${this.name}"]`).remove();
}

override async didRevert(): Promise<ActionRevertResult> {
  const history = this.engine.history ('stamp') as string[];

  for (let i = history.length - 1; i >= 0; i--) {
    if (history[i] === this._statement) {
      history.splice(i, 1);
      break;
    }
  }

  this.engine.state({ stamps: (this.engine.state ('stamps') as string[]).filter((statement) => statement !== this._statement) });

  return { advance: true, step: true };
}

Add an onLoad() that applies every statement in state('stamps') with didApply({ updateHistory: false, updateState: false }), as Show::Image does, so a load draws them (Saving and Loading). Add StateMap and HistoryMap keys in src/lib/types/index.ts for a built-in.

Undo a “hide” action

Search the history backwards for the last statement that showed the same asset and apply it again, recording state but not history. This is HideImage.revert():

override async revert(): Promise<void> {
  const history = this.engine.history ('image') as string[];

  for (let i = history.length - 1; i >= 0; i--) {
    const [, , asset] = history[i].split (' ');

    if (asset === this.asset) {
      const action = this.engine.prepareAction(history[i], { cycle: 'Application' });

      if (action !== null) {
        await action.willApply();
        await action.apply();
        await action.didApply({ updateHistory: false, updateState: true });
      }

      return;
    }
  }

  throw new Error ('Could not find a previous state to revert to');
}

Throwing when nothing matches makes the rollback refuse instead of going on with the screen out of step.

Clean up a statement that waits

When a new action waits for the player (it returns advance: false and shows something), remove what it shows in a static willRollback(), and clear its blocking flag there:

static override async willRollback(): Promise<void> {
  this.engine.element().find ('[data-gate]').remove();
  Gate.blocking = false;
}

Refuse to go back

Throw from a static shouldRollback() to refuse every rollback while something is true (a minigame in progress): rollback() rejects before anything changes. Throw from an instance’s willRevert() to refuse going back over one statement: the engine runs the statement on screen again.

Undo game code

In a game, a reversible function is the statement to reach for:

{'Function': {
  'Apply': function() {
    this.storage({ points: this.storage ('points') + 10 });
  },
  'Revert': function() {
    this.storage({ points: this.storage ('points') - 10 });
  }
}}

Returning false from Revert stops the rollback on that statement. An Input takes a Revert the same way, and a Choice option takes onRevert next to onChosen. The old name Reverse works too; write Revert in new code.

Pitfalls and history

  • Keys added during a game survived end and a load, before 2.9.0. resetGame() called engine.storage(JSON.parse(storageStructure)), which merges: the declared keys went back to their values, but a key the game added later (storage({ secret: 'found' })), or a nested key added under a declared object, stayed in the next game, and in any save loaded after it. 2.9.0 replaces the storage instead. Exercise 4 has you find and fix it on the v2.8.1 tag.
  • fn() stores functions nobody reads. monogatari.fn(name, { apply, revert }) writes _functions[name], and nothing in the engine reads _functions. Reversible code goes in a Function statement. Until 2.9.0, fn(name) alone also overwrote the stored pair with two functions that return true, because its defaults were applied before the check that something was given.
  • global() hides null. The skip listener in setup() tests this.global('skip') !== null. The global defaults to null, which global() returns as undefined, so the test is always true and the listener always calls skip(false).
  • Back from the line a choice’s Do shows stays on the choice’s step. Clicking an option runs its Do with engine.run() and leaves step on the Choice when the Do is a line of dialog. Until 2.9.0, Back from it undid the statement before the Choice: the player landed before the menu, and the option stayed in history('choice'). Now the click handler sets state('answeredChoice'), revert() in lifecycle.ts reverts the Choice itself when that matches the current position, and Choice.revert() undoes the Do without stepping back. Choice.beforeRun() clears answeredChoice as soon as a statement runs anywhere else.
  • A Function without Revert doesn’t stop the rollback. It shows action:function:revert_error, then goes on to the statement before it, with the function’s effect still in place. Input refuses instead (willRevert() throws without a Revert).
  • Reverse worked only after the statement ran in the same page until 2.9.0. ReversibleFunction.willApply() (@Compatibility [<= v2.0.0-beta.15], ccc55707, 2020) copied Reverse to Revert by writing into the script’s own object, and the revert cycle never calls willApply(), so after loading a save the rollback found no Revert. The constructor picks Revert or Reverse now.
  • A failed rollback used to freeze the game (8a781e42, 2019): previous() resolved without clearing anything. It now clears _engine_block, steps back and proceeds, and since b11ad8a7 (2020) it doesn’t step below 0. Until 2.9.0, at step 0 it proceeded anyway, which moved the game one statement forward; it runs the statement on screen again now.
  • Back on the first statement looped (e191017e, 2020). rollback() now returns at step 0 unless a jump led there.
  • Rollback changed the jump history (2659dd89, 2019). Only Jump.didRevert() pops it now.
  • Clicks during a revert advanced the game mid-rollback, until 8af22546 (2019) set _engine_block around it.
  • shouldStepBack (da2a9160, 2019) exists so Scene can revert its inner background without moving the step twice.
  • Lines were logged twice after a rollback (6169653f, a0cf6f60, 2020). Dialog writes to the log only in the 'Application' cycle, and its willRollback() pops the entry of the line on screen.
  • Character history items gained previous in 2.1.0 (441c699e, 2021), so undoing a show character that replaced another sprite puts the old one back. The migration 20211223-add-previous-statement-to-show-history.ts rewrites old saves. Media state items became { statement, paused } in 2.0.0-beta.15, with the migration 20200310-add-pause-state-to-media-state.ts.
  • block and _executing_sub_action are deprecated (14494a78, 2025) in favor of each action’s static blocking, but shouldRollback() still reads both.
  • interrupt() is declared on Action “for future purposes”; the engine never calls it. 2.9.0 marks it @deprecated.

Exercises

Each check is a Cypress spec. Put it in cypress/e2e/exercises/, run it with bunx cypress run --browser chromium --spec 'cypress/e2e/exercises/<name>.spec.js', and delete it when you are done. The specs use the repository’s own commands from cypress/support/commands.js, so they open dist/index.html like every other spec. How Each Part Works explains the scratch copy to do them in, and Testing how the specs run.

Exercise 1: make a custom action undoable

What to do. Inside a spec, define a stamp <name> action that adds <p data-stamp="name"> to the game screen, records its statement in history('stamp') and in state('stamps'), and advances on its own. Register it, play 'One', 'stamp gold', 'Two', and make one Back from 'Two' show 'One' with the stamp and its records gone.

Hint. Start with only apply() and didApply(), press Back once and look at step and the text box. What does the base class’s didRevert() return, and what does revert() do with it?

Check. After one rollback the text box shows 'One', step is 0, [data-stamp="gold"] is gone and both state('stamps') and history('stamp') are empty. Without revert() and didRevert(), the first Back leaves the game on 'Two' at step 1 with the stamp still there; with revert() but the base didRevert(), the stamp goes but the text box still shows 'Two'. Both fail the check.

Solution

cypress/e2e/exercises/stamp.spec.js:

const defineStamp = (Action) => {
  class Stamp extends Action {
    static id = 'Stamp';

    static matchString([action]) {
      return action === 'stamp';
    }

    constructor([action, name]) {
      super();
      this.name = name;
    }

    async apply() {
      this.engine.element().find ('[data-screen="game"]').append (`<p data-stamp="${this.name}">${this.name}</p>`);
    }

    async didApply() {
      this.engine.history ('stamp').push(this._statement);
      this.engine.state({ stamps: [...(this.engine.state ('stamps') || []), this._statement] });

      return { advance: true };
    }

    async revert() {
      this.engine.element().find (`[data-stamp="${this.name}"]`).remove();
    }

    async didRevert() {
      this.engine.history ('stamp').pop();
      this.engine.state({ stamps: this.engine.state ('stamps').filter((statement) => statement !== this._statement) });

      return { advance: true, step: true };
    }
  }

  return Stamp;
};

context ('Exercise: an undoable stamp', function() {
  beforeEach(() => {
    cy.open();
  });

  it ('removes the stamp and goes back to the line before it', function() {
    this.monogatari.setting ('TypeAnimation', false);

    cy.window().then((win) => {
      this.monogatari.registerAction(defineStamp(win.Monogatari.Action));
    });

    this.monogatari.script({
      'Start': [
        'One',
        'stamp gold',
        'Two',
        'end'
      ]
    });

    cy.start();
    cy.proceed();
    cy.get ('text-box').contains ('Two');
    cy.get ('[data-stamp="gold"]').should ('exist');
    cy.wrap(this.monogatari).invoke ('state', 'stamps').should ('deep.equal', ['stamp gold']);

    cy.rollback();
    cy.get ('text-box').contains ('One');
    cy.get ('[data-stamp="gold"]').should ('not.exist');
    cy.wrap(this.monogatari).invoke ('state', 'step').should ('equal', 0);
    cy.wrap(this.monogatari).invoke ('state', 'stamps').should ('deep.equal', []);
    cy.wrap(this.monogatari).invoke ('history', 'stamp').should ('deep.equal', []);
  });
});

The action is registered after init() (the page has already started the engine when the spec runs), so its setup() would never run: history('stamp') creates the array on first use instead, and state('stamps') || [] covers the missing key.

revert() targets label[1], the stamp. Its { advance: true, step: true } moves the step to 1 and reverts label[0], the line, which shows 'One' and stops. The base class’s { advance: false, step: true } stops after the stamp: the step is 1, but nothing replaced 'Two' on screen.

Exercise 2: points that roll back

What to do. A game gives the player 10 points with a plain function between two lines. Make Back from the second line show the first one and take the points away.

Hint. Look at what revert() does when the statement to undo is a function, and at what the Function action matches.

Check. With storage({ points: 0 }), after one proceed storage('points') is 10 and the text box shows 'After'; after one rollback it shows 'Before', step is 0 and points is 0. With the plain function the check fails: Back leaves the game on 'After' with 10 points.

Solution

cypress/e2e/exercises/points.spec.js:

context('Exercise: points that roll back', () => {
  beforeEach(() => {
    cy.open();
  });

  it('gives the points back when the player goes back', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.storage({ points: 0 });

    this.monogatari.script({
      'Start': [
        'Before',
        {'Function': {
          'Apply': function() {
            this.storage({ points: this.storage('points') + 10 });
          },
          'Revert': function() {
            this.storage({ points: this.storage('points') - 10 });
          },
        }},
        'After',
        'end',
      ],
    });

    cy.start();
    cy.proceed();
    cy.get('text-box').contains('After');
    cy.wrap(this.monogatari).invoke('storage', 'points').should('equal', 10);

    cy.rollback();
    cy.get('text-box').contains('Before');
    cy.wrap(this.monogatari).invoke('state', 'step').should('equal', 0);
    cy.wrap(this.monogatari).invoke('storage', 'points').should('equal', 0);
  });
});

A plain function makes revert() reject; previous() steps back, proceeds, and 'After' runs again. The Function statement matches the Function action (its id is 'Function', its class ReversibleFunction), whose revert() calls Revert with the engine as this. Revert returns undefined, so didRevert() says advance: true and the rollback goes on to 'Before'.

Exercise 3: test going back across a jump

What to do. No spec in the repository covers rolling back across a jump. Write one for Start: ['A0', 'A1', 'jump Other', 'Never shown'] and Other: ['B0', 'B1', 'end']: predict label, step, history('jump') and history('label') after each Back from B1, then assert them. Then break Jump.didRevert() in src/actions/Jump.ts so it returns { advance: false, step: false }, rebuild with bun build.ts --browser, and see your spec fail.

Hint. Read rollback() for what happens at step 0, and the first branch of revert() that reads history('jump'). Which statement does revert() undo after it moves label and step?

Check. The spec passes on the engine as it is: Back from B1 shows B0 (Other, step 0); Back again shows A1 (Start, step 1) with both histories empty. With the broken didRevert(), it fails on A1. Restore with git checkout -- src dist/engine/core.

Solution

cypress/e2e/exercises/jump-rollback.spec.js:

context('Exercise: rolling back across a jump', () => {
  beforeEach(() => {
    cy.open();
  });

  it('goes back to the label the jump came from', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.script({
      'Start': [
        'A0',
        'A1',
        'jump Other',
        'Never shown',
      ],
      'Other': [
        'B0',
        'B1',
        'end',
      ],
    });

    cy.start();
    cy.proceed();
    cy.proceed();
    cy.get('text-box').contains('B0');
    cy.wrap(this.monogatari).invoke('history', 'jump').should('deep.equal', [
      { source: { label: 'Start', step: 2 }, destination: { label: 'Other', step: 0 } },
    ]);

    cy.proceed();
    cy.get('text-box').contains('B1');

    // Back inside the label: an ordinary step back
    cy.rollback();
    cy.get('text-box').contains('B0');
    cy.wrap(this.monogatari).invoke('state').its('label').should('equal', 'Other');
    cy.wrap(this.monogatari).invoke('state').its('step').should('equal', 0);

    // Back at step 0: the jump history takes the game to the jump's source,
    // the Jump action reverts and the line before it shows
    cy.rollback();
    cy.get('text-box').contains('A1');
    cy.wrap(this.monogatari).invoke('state').its('label').should('equal', 'Start');
    cy.wrap(this.monogatari).invoke('state').its('step').should('equal', 1);
    cy.wrap(this.monogatari).invoke('history', 'jump').should('deep.equal', []);
    cy.wrap(this.monogatari).invoke('history', 'label').should('deep.equal', []);
  });
});

The second Back starts at step 0 of Other. rollback() finds the jump whose destination is Other at step 0, so it doesn’t stop. revert() sets label to Start and step to 2 and undoes label[2], the jump. Jump.didRevert() pops both histories and returns { advance: true, step: false }: the step stays at 2 and the next revert() undoes label[1], 'A1', which shows it and moves the step to 1. With advance: false, the rollback stops on the jump with Start/2 in the state and B0 still on screen.

Exercise 4: start every new game with the declared storage

2.9.0 fixed the bug this exercise is about, so do it on the v2.8.1 tag: make the scratch copy with git worktree add --detach ../monogatari-v2.8.1 v2.8.1 instead of HEAD.

What to do. Write a spec that plays a game whose function adds storage({ secret: 'found', player: { name: 'Zed', nickname: 'Z' } }), reaches end, and checks that the storage is back to what dist/js/storage.js declares ({ player: { name: '' } }). It fails on 2.8.1. Fix resetGame() so it passes.

Hint. resetGame() gives storage() the structure captured in setup(). What does storage() do with an object, and which keys can a merge never remove?

Check. On the engine as it is, the spec fails with { player: { name: '', nickname: 'Z' }, secret: 'found' }. After the fix and bun build.ts --browser, it passes. components/save-screen.spec.js, actions/input.spec.js, actions/reversible_functions.spec.js and main_menu_after_load.spec.js still pass with the fix. Restore with git checkout -- src dist/engine/core.

Solution

cypress/e2e/exercises/reset-storage.spec.js:

context('Exercise: a new game starts with the declared storage', () => {
  beforeEach(() => {
    cy.open();
  });

  it('forgets variables the last game added', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.script({
      'Start': [
        'One',
        function() {
          this.storage({
            secret: 'found',
            player: { name: 'Zed', nickname: 'Z' },
          });
        },
        'Two',
        'end',
      ],
    });

    cy.start();
    cy.proceed();
    cy.get('text-box').contains('Two');
    cy.wrap(this.monogatari).invoke('storage', 'secret').should('equal', 'found');

    // 'end' resets the game and shows the main menu
    cy.proceed();
    cy.get('main-screen').should('be.visible');

    cy.wrap(this.monogatari).invoke('storage').should('deep.equal', {
      player: { name: '' },
    });
  });
});

The fix, in resetGame() in src/engine/persistence.ts, replaces the storage instead of merging into it:

 	// Reset Storage
 	const storageStructure = engine.global ('storageStructure');

-	engine.storage (JSON.parse(storageStructure));
+	// Replace the storage instead of merging into it, so variables the last
+	// game added don't survive into the next one
+	engine._storage = JSON.parse (storageStructure);

_storage is the static field behind storage() (declared @internal on VisualNovelEngine). A load calls resetGame() before it merges the save’s storage, so the same change keeps a key from the current session out of a loaded game.

2.9.0 made the same change in resetGame(). Its tests are “Resets the storage to what the game declared” in cypress/e2e/actions/end.spec.js and “Loads a save without the variables of the game being played” in cypress/e2e/components/load-screen.spec.js.