This page is the way into the v2 engine for someone who knows JavaScript or TypeScript and the web platform, and nothing about Monogatari yet. It takes you in seven stages from a fresh clone to the work a maintainer of the 2.8 line does: fixing a bug anywhere without breaking what the rest of the engine relies on, adding an action or a component with its Cypress spec, reviewing someone else’s change, and cutting a patch release.

Each stage has a goal, the pages to read in order, something to do, and a checkpoint: a spec that passes, a command and its output, or a question you can answer from the code. Don’t move on until the checkpoint holds. Every exercise on this page was run on the v2.8.1 tag on a Linux machine with Chromium; when your output differs, find out why before you go on. It is good practice.

NOTE

Like the rest of Working on Monogatari, this page assumes a computer with Git, Bun, Node and a terminal, and a network connection (the Cypress specs load their art and sound from a server). Making a game never needs any of it.

How the exercises work

v2 has no unit-test harness: its tests are Cypress specs that open the starter game, dist/index.html, in a real browser and drive it. So the exercises are scratch specs: a file you add under cypress/e2e/, run with bunx cypress run --browser chromium --spec <file>, and never commit.

Exercises that change the engine happen in a separate worktree, a second checkout of the repository in a folder of its own, so your own branch never sees them. From your clone:

git worktree add ../monogatari-scratch v2.8.1
cd ../monogatari-scratch
bun install

A worktree has no node_modules until you run bun install in it. git status lists your scratch files as untracked, so they can’t slip into a commit you stage by name. Remove the worktree with git worktree remove --force ../monogatari-scratch when you’re done with it.

Every scratch spec uses the commands in cypress/support/commands.js: cy.open() loads dist/index.html and sets the alias this.monogatari to the engine, cy.loadTestAssets() points the asset paths at the test server and declares the test characters, cy.start() clicks Start, cy.proceed() and cy.rollback() move the game, cy.save(slot) and cy.load(slot) save and load. Testing the Engine describes each.

Stage 1: run everything

Goal. A clone that builds, whose specs you can run, and whose starter game you can play.

Read, in this order: Setting Up the Repository, then Repository Layout.

Do:

  1. Install and build. Follow Setting Up the Repository to bun run build. It cleans the build output, lints, type-checks and builds; on the machine these pages were written on it took 7 seconds and ended with 🎉 Build completed successfully!. Then run git status: it shows nothing, because the committed bundles match src/.
  2. Run one spec: bun run test --spec cypress/e2e/actions/dialog.spec.js. It plays 67 tests in about a minute and ends with All specs passed!.
  3. Run the whole suite: bun run test. It runs 69 specs and 610 tests in about eleven minutes, and they all pass.
  4. Look at the release before it. In a second worktree, check out the v2.8.1 tag, install and build there, and run two specs: git worktree add ../monogatari-2.8.1 v2.8.1, then in that folder bun install, bun run build and bunx cypress run --browser chromium --spec 'cypress/e2e/actions/show_scene.spec.js,cypress/e2e/components/load-screen.spec.js'. Two tests fail there. Keep their names; the checkpoint asks about them. Remove the worktree when you’re done (git worktree remove ../monogatari-2.8.1).
  5. Play the starter game. Serve dist/ (cd dist && python3 -m http.server 8080, or any static server) and open http://localhost:8080. Play through the sample story. Open the browser’s developer tools and type monogatari.state() in the console: it prints the current label and step and what is on screen.

Checkpoint. Every item holds:

  • bun run build passes and leaves git status clean.
  • You know which two tests fail on the v2.8.1 tag and why, and which commit fixed them. Find out with git log -S before you open the answer.
  • You can say where the starter game’s copy of the engine lives (dist/engine/core/), and why a change to src/ is committed together with it.
Why two tests fail on v2.8.1

The failures are “Show Scene: Shows the correct background on when both scene and background are used” and “Load Screen: Gives priority to the last known background”. Both compare a background with url("https://datadyne.perfectdark.space/monogatari/assets/images/christmas.png").

git log -S 'datadyne.hyuchia.com' -- cypress finds commit 4b5fff30, which moved the test assets in cypress/support/commands.js from datadyne.perfectdark.space to datadyne.hyuchia.com but left the two specs expecting the old host, which no longer resolves. Change the host in both specs and Show Scene passes.

Load Screen still fails: the save slot shows a data:image/jpeg URL, a screenshot of the game. git log -S "'Screenshots': true" -- dist/js/options.js finds commit f6bf8beb, which turned save screenshots on in the starter game, and the specs load the starter game’s js/options.js. Turning them off in that test (this.monogatari.setting ('Screenshots', false);, next to its TypeAnimation line) makes it pass. Both fixes were run on the tag: the two specs then pass 3 of 3 and 5 of 5. These were bugs in the tests, not in the engine, and 2.9.0 fixed them: git log --oneline v2.8.1..develop -- cypress/e2e/actions/show_scene.spec.js finds the commit.

Stage 2: trace one click

Goal. Follow a click from the game screen to the line it shows, through the files and functions that do the work.

Read, in this order: Reading the Code, Architecture, then How Each Part Works and its Statements and Actions page.

Do:

Trace a click through the engine’s events

Work in your scratch worktree. Save this as cypress/e2e/scratch.spec.js. It listens to the two events the engine fires around every statement, willRunAction and didRunAction, and checks their order:

context('Scratch', () => {
  beforeEach(() => {
    cy.open();
    cy.loadTestAssets();
  });

  it('runs two statements on one click', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.script({
      'Start': [
        'First.',
        'show scene #000000',
        'Second.',
        'end',
      ],
    });

    const seen = [];

    for (const name of ['willRunAction', 'didRunAction']) {
      this.monogatari.on(name, (event) => {
        seen.push(`${name} ${event.detail.action.constructor.id}`);
      });
    }

    cy.start();
    cy.get('text-box').contains('First.');
    cy.wrap(seen).should('deep.equal', ['willRunAction Dialog', 'didRunAction Dialog']);

    cy.then(() => {
      seen.length = 0;
    });

    cy.get('game-screen').click();
    cy.get('text-box').contains('Second.');
    cy.wrap(this.monogatari).invoke('state', 'step').should('equal', 2);
    cy.wrap(seen).should('deep.equal', [
      'willRunAction Scene',
      'didRunAction Scene',
      'willRunAction Dialog',
      'didRunAction Dialog',
    ]);
  });
});

Run it with bunx cypress run --browser chromium --spec cypress/e2e/scratch.spec.js. It passes. One click ran two statements. Before you read the answer, find in src/engine/lifecycle.ts why.

Why two statements ran on one click

The click reaches the listener in GameScreen.bind() (src/components/game-screen/index.ts), which calls engine.proceed(). proceed() in src/engine/lifecycle.ts waits for shouldProceed(), sets the _engine_block global, runs willProceed() and calls next(), which adds 1 to step and, on the next turn of the event loop, calls run() with show scene #000000. run() matches the statement to Scene, fires willRunAction, calls willApply(), apply() and didApply(), and fires didRunAction. Scene.didApply() returns { advance: true }, so run() calls next() again and Second. runs too. Dialog.didApply() returns { advance: false }, so the chain stops there and the game waits for the next click. next() clears _engine_block once the statement it ran has finished.

Stop the engine at a breakpoint

The browser bundle has a linked source map that holds every file of src/, so the developer tools show the TypeScript files and stop in them.

  1. Serve dist/ as in stage 1 and open the game.
  2. Open the developer tools (F12), go to Sources, press Ctrl+P and open lifecycle.ts.
  3. Find export const proceed and set a breakpoint on its line await shouldProceed(engine, { userInitiated, skip, autoPlay }); (line 1107 on develop at 2.9.0).
  4. Click Start, wait for the first line of text, then click the game screen.

The game stops on your breakpoint. The call stack reads, from the top: proceed in src/engine/lifecycle.ts line 1107, proceed in src/monogatari.ts line 2041 (the engine object’s wrapper), and the click listener in src/components/game-screen/index.ts line 30, called by Artemis’s delegated event handler. Step into shouldProceed() to watch it ask every action and component, then press F8 to let the game go on. (This stack was read through the Chrome DevTools Protocol on the starter game, with the source map applied.)

Put a breakpoint on line 345 of the same file instead, the first line of run(), and click Start: the stack is run in lifecycle.ts, run in src/monogatari.ts line 1820, and the start listener that setup() registers in src/monogatari.ts, at line 2034.

Three questions to answer from the code

  1. Which action takes 'show scen beach', misspelled?
  2. Why does a click during the typing animation finish the line instead of moving on?
  3. The quick menu’s Save button is a <button> inside the game screen. Why doesn’t clicking it also move the game forward?
Answers
  1. Dialog. It accepts any string and is registered last, so a statement nothing else matches becomes a line of narration that reads “show scen beach”. In the console, monogatari.prepareAction('show scen beach', { cycle: 'Application' }).constructor.id prints "Dialog". v2 has no script check that warns about it.
  2. Dialog.shouldProceed() (in src/actions/Dialog.ts) runs on every click. While the finished_typing global is false and the type-writer has text, it calls engine.stopTyping() and throws 'TypeWriter effect has not finished.'. The rejection stops proceed() before next(), so the click only finishes the line.
  3. Two reasons. The game screen’s listener is bound to [data-screen="game"] *:not([data-choice]):not([data-action]):not([data-delete]) and returns early when the click is inside a [data-action]. And the data-action handler that bind() sets up in src/monogatari.ts calls event.stopPropagation() before running the listener.

Checkpoint. You can draw the path of a click from memory: the game screen’s listener calls proceed(), which asks every action’s and component’s shouldProceed() (and refuses while a modal is visible, in distraction-free mode, or while _engine_block or the deprecated block is set), sets _engine_block, runs willProceed(), and calls next(), which adds 1 to step and calls run(); run() matches the statement in prepareAction() and calls willApply(), apply() and didApply(), which either advances again or waits. Your scratch spec passes and your breakpoint stopped where you set it.

Stage 3: reproduce a real bug, then fix it

Goal. Turn a report into a spec that fails, find the code, fix it, and prove the fix.

Read, in this order: Testing the Engine, Debugging the Engine, and the triage section of How a Change Gets In.

Do. You’ll reproduce the bug that release 2.8.1 fixed. The report: a character shown with show character y happy at center with move jumps to its new position instead of sliding there, and the transition 3s property makes no difference.

  1. Find the fix and check out the commit before it, in a worktree of its own. From your clone:

    FIX=$(git log --format=%h -1 -S 'translate: -50%' -- src/components/game-screen/index.css)
    git show --stat $FIX
    git worktree add ../monogatari-bug $FIX^
    cd ../monogatari-bug
    bun install

    git log -S finds the commit that added a piece of code: here fea01a2e, “Fix types not being generated & character positioning so move works”, the commit tagged v2.8.1. $FIX^ is the commit before it, 86659baf, where the bug is still there. bun install there rewrites one line of bun.lock; leave it.

  2. Bring in the spec that came with the fix. The fix added three tests to cypress/e2e/actions/show_character.spec.js. Take the file from the fix:

    git checkout $FIX -- cypress/e2e/actions/show_character.spec.js

    Read the three new tests (“Transitions the sprite between positions when the move property is used”, “Anchors the sprite to each position”, “Uses the default move duration when no transition property is given”). They say what the player should see: the sprite gets the move class, CSS transitions run on left and translate, and they last as long as transition 3s says, or 0.2 seconds by default.

  3. Watch it fail. bunx cypress run --browser chromium --spec cypress/e2e/actions/show_character.spec.js ends with 14 passing and 2 failing:

    1) Show Character
         Transitions the sprite between positions when the move property is used:
        running transitions
        + expected - actual
    
        -[]
        +[ 'left', 'translate' ]
    
    2) Show Character
         Uses the default move duration when no transition property is given:
        AssertionError: expected 'all' to equal 'left, translate'

    No transition runs at all. A test you never saw fail proves nothing: if these had passed here, they wouldn’t be testing the bug.

  4. Find the code. ShowCharacter puts every word after with on the sprite as a class, so move is there (grep -n "transition" src/actions/ShowCharacter.ts finds where it sets transition-duration from transition 3s); what the class does is CSS. grep -rn "\[data-sprite\]" src --include=*.css leads to src/components/game-screen/index.css. Read the [data-sprite] rule: the sprite is centered with margin: 0 auto; left: 0; right: 0, the positions override left and right with initial, and the .move rule is commented out. Margins set to auto and initial values can’t be animated, so the browser jumps. Fix it yourself before you look at the real fix.

  5. Rebuild only the stylesheet and run the spec again. The specs load dist/engine/core/monogatari.css, so rebuild it after every change to the CSS:

    bun build.ts --css
    bunx cypress run --browser chromium --spec cypress/e2e/actions/show_character.spec.js

    Repeat until all 16 tests pass.

  6. Compare with the real fix: git show $FIX -- src/components/game-screen/index.css src/style/variables.css. It positions the sprite with left and the translate property (left: 50%; translate: -50% for center), which both animate, and gives .move a transition on left, translate whose duration and easing come from two new variables, --character-move-speed (0.2s) and --character-move-easing (ease). With the real fix in place, git diff $FIX -- dist/engine/core/monogatari.css prints nothing: your rebuilt stylesheet is byte for byte the one the release committed.

  7. Clean up: go back to your clone and git worktree remove --force ../monogatari-bug.

The other half of the same commit

The commit’s title has two parts. “Types not being generated”: at the parent commit, bun build.ts --types prints ✅ Type declarations built successfully, yet ls dist/types finds nothing. build.ts ran tsc --emitDeclarationOnly, and tsconfig.json sets "noEmit": true, so tsc emitted nothing and exited with 0. Release 2.8.0 was published to npm without type declarations although package.json pointed at them. The fix added --noEmit false and --rootDir, and made the build fail when dist/types/index.d.ts is missing: a check for the symptom, so the same mistake can’t pass silently again. The same commit also vendored the random-js library into src/vendor/random-js/ and rebuilt every bundle. A release commit that mixes three changes is harder to review; How a Change Gets In asks for one change per commit.

Checkpoint. The spec failed (14 passing, 2 failing) before your fix and passes (16 of 16) after it, and you can say why a CSS-only fix only needs bun build.ts --css to reach the specs. You can also say why the “Anchors the sprite to each position” test passed before the fix too: it pins the behavior the fix had to keep, not the bug.

Stage 4: add an action and a component

Goal. A new statement and the element it shows, registered as built-ins, with a spec, and with what the docs and the record need.

Read, in this order: Statements and Actions and Components and Screens, src/lib/Action.ts again, and, for the side of the same work a game’s developer sees, Extending Monogatari.

Do. In your scratch worktree, you’ll add stamp Approved, a statement that stamps its words over the scene until the next stamp, and the <stamp-badge> element that shows them.

  1. Write the spec first, cypress/e2e/actions/stamp.spec.js. It shows the stamp, rolls back, and loads a save:

    context('Stamp', () => {
      beforeEach(() => {
        cy.open();
        cy.loadTestAssets();
      });
    
      it('Shows the stamp and replaces it with the next one', function() {
        this.monogatari.setting('TypeAnimation', false);
        this.monogatari.script({
          'Start': ['Before.', 'stamp Approved', 'After.', 'stamp Denied', 'Last.', 'end'],
        });
    
        cy.start();
        cy.get('stamp-badge').should('not.exist');
    
        cy.proceed();
        cy.get('text-box').contains('After.');
        cy.get('stamp-badge').should('have.length', 1).and('contain', 'Approved');
        cy.wrap(this.monogatari).invoke('state', 'stamp').should('equal', 'stamp Approved');
    
        cy.proceed();
        cy.get('text-box').contains('Last.');
        cy.get('stamp-badge').should('have.length', 1).and('contain', 'Denied');
      });
    
      it('Puts the previous stamp back on rollback', function() {
        this.monogatari.setting('TypeAnimation', false);
        this.monogatari.script({
          'Start': ['Before.', 'stamp Approved', 'After.', 'stamp Denied', 'Last.', 'end'],
        });
    
        cy.start();
        cy.proceed();
        cy.proceed();
        cy.get('stamp-badge').should('contain', 'Denied');
    
        cy.rollback();
        cy.get('text-box').contains('After.');
        cy.get('stamp-badge').should('have.length', 1).and('contain', 'Approved');
        cy.wrap(this.monogatari).invoke('state', 'stamp').should('equal', 'stamp Approved');
    
        cy.rollback();
        cy.get('text-box').contains('Before.');
        cy.get('stamp-badge').should('not.exist');
        cy.wrap(this.monogatari).invoke('state', 'stamp').should('equal', '');
      });
    
      it('Brings the stamp back when a game is loaded', function() {
        this.monogatari.setting('TypeAnimation', false);
        this.monogatari.script({
          'Start': ['stamp Approved', 'Stamped.', 'end'],
        });
    
        cy.start();
        cy.get('text-box').contains('Stamped.');
    
        cy.save(1).then(() => {
          cy.proceed();
          cy.get('main-screen').should('be.visible');
          cy.get('stamp-badge').should('not.exist');
    
          cy.load(1).then(() => {
            cy.get('game-screen').should('be.visible');
            cy.get('stamp-badge').should('have.length', 1).and('contain', 'Approved');
          });
        });
      });
    });

    Run it: all three tests fail. With no Stamp action, stamp Approved is a line of narration, so the first test never sees “After.”.

  2. The action, src/actions/Stamp.ts. An action records what it shows in state (so a load can rebuild it) and in history (so a rollback can undo it), and undoes itself in revert():

    import { ActionApplyResult, ActionRevertResult } from '../lib/types';
    import Action from './../lib/Action';
    
    /**
     * `stamp <words>` puts the words over the scene until the next `stamp`.
     */
    export class Stamp extends Action {
      static override id = 'Stamp';
    
      static override async setup(): Promise<void> {
        this.engine.history('stamp');
        this.engine.state({ stamp: '' });
      }
    
      static override async reset(): Promise<void> {
        this.engine.element().find('stamp-badge').remove();
        this.engine.state({ stamp: '' });
      }
    
      static override async onLoad(): Promise<void> {
        const statement = this.engine.state('stamp') as string;
    
        if (statement === '') {
          return;
        }
    
        const action = this.engine.prepareAction(statement, { cycle: 'Application' });
    
        if (action !== null) {
          await action.willApply();
          await action.apply();
          await action.didApply({ updateHistory: false, updateState: false });
        }
      }
    
      static override matchString([action]: string[]): boolean {
        return action === 'stamp';
      }
    
      text: string;
    
      constructor([, ...words]: string[]) {
        super();
        this.text = words.join(' ');
      }
    
      override async apply(): Promise<void> {
        this.engine.element().find('stamp-badge').remove();
    
        const badge = document.createElement('stamp-badge');
    
        (badge as HTMLElement & { setProps: (props: Record<string, unknown>) => void }).setProps({ text: this.text });
    
        this.engine.element().find('[data-screen="game"] [data-content="visuals"]').append(badge);
      }
    
      override async didApply({ updateHistory = true, updateState = true } = {}): Promise<ActionApplyResult> {
        if (updateHistory === true) {
          (this.engine.history('stamp') as string[]).push(this.engine.state('stamp') as string);
        }
    
        if (updateState === true) {
          this.engine.state({ stamp: this._statement as string });
        }
    
        return { advance: true };
      }
    
      override async revert(): Promise<void> {
        this.engine.element().find('stamp-badge').remove();
    
        const previous = (this.engine.history('stamp') as string[]).pop() ?? '';
    
        this.engine.state({ stamp: previous });
    
        if (previous !== '') {
          const action = this.engine.prepareAction(previous, { cycle: 'Application' });
    
          if (action !== null) {
            await action.apply();
          }
        }
      }
    
      override async didRevert(): Promise<ActionRevertResult> {
        return { advance: true, step: true };
      }
    }
    
    export default Stamp;

    didApply() pushes the stamp being replaced onto the history, then records the new statement in state. revert() pops it back. onLoad() rebuilds the stamp from state after a load, calling didApply() with both flags off so the load doesn’t record it a second time. That’s the same pattern ShowImage uses.

  3. The component, src/components/stamp-badge/index.ts, and its stylesheet src/components/stamp-badge/index.css:

    import { Properties } from '@aegis-framework/pandora';
    import Component from '../../lib/Component';
    
    export interface StampBadgeProps extends Properties {
        text: string;
    }
    
    /**
     * The words a `stamp` statement puts over the scene.
     */
    class StampBadge extends Component<StampBadgeProps> {
        static override tag = 'stamp-badge';
    
        constructor() {
            super();
    
            this.props = {
                text: ''
            };
        }
    
        override render(): string {
            return `<span data-content="text">${this.props.text}</span>`;
        }
    }
    
    export default StampBadge;
    stamp-badge {
      position: absolute;
      top: 1rem;
      right: 1rem;
      padding: 0.5rem 1rem;
      border: 2px solid var(--character-name-color);
      color: var(--character-name-color);
      background: var(--main-color);
    }

    The action creates the element and calls setProps() before it appends it, the way Choice and Message create theirs.

  4. Make them built-ins. In src/index.ts, import Stamp and add it to Monogatari._actions (anywhere before Dialog, which must stay last), and import StampBadge and add it to Monogatari._components. In src/index.css, add @import './components/stamp-badge/index.css'; with the other components.

  5. Build: bun run build. It lints, type-checks and rebuilds everything in about 9 seconds. git status now shows your new files, the rebuilt dist/engine/core/ and lib/ bundles, and new declarations in dist/types/.

  6. Run the spec again. All three tests pass:

    ✓ Shows the stamp and replaces it with the next one
    ✓ Puts the previous stamp back on rollback
    ✓ Brings the stamp back when a game is loaded
  7. The record. A real change would also add a page for the statement in docs/script-actions/ and one for the element in docs/components/, and commit the rebuilt bundles with the source in the same branch (How a Change Gets In).

Checkpoint. In your scratch worktree the stamp spec passes and bun run build passes. You can say why Stamp must come before Dialog in _actions, why didApply() and not apply() writes to state and history, and why onLoad() passes updateHistory: false. Keep the worktree for stages 5 and 6.

Stage 5: rollback and saving, deeply

Goal. Know what a rollback undoes and what it can’t, what a save holds, and what a load rebuilds.

Read, in this order: State, Storage and Rollback and Saving and Loading, then src/engine/persistence.ts and src/migrations/index.ts.

Do. Save this as cypress/e2e/scratch-saves.spec.js in your scratch worktree and run it:

context('Scratch: rollback and saves', () => {
  beforeEach(() => {
    cy.open();
    cy.loadTestAssets();
  });

  const purse = {
    'Function': {
      'Apply': function() {
        this.storage({ gold: this.storage('gold') + 5 });
      },
      'Revert': function() {
        this.storage({ gold: this.storage('gold') - 5 });
      },
    },
  };

  it('undoes a storage change only through the Revert function', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.storage({ gold: 0 });
    this.monogatari.script({
      'Start': ['You find a purse.', purse, 'You have {{gold}} gold.', 'end'],
    });

    cy.start();
    cy.proceed();
    cy.get('text-box').contains('You have 5 gold.');
    cy.wrap(this.monogatari).invoke('storage', 'gold').should('equal', 5);

    cy.rollback();
    cy.get('text-box').contains('You find a purse.');
    cy.wrap(this.monogatari).invoke('storage', 'gold').should('equal', 0);
    cy.wrap(this.monogatari).invoke('state', 'step').should('equal', 0);
  });

  it('cannot roll back over a plain function', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.storage({ gold: 0 });
    this.monogatari.script({
      'Start': [
        'You find a purse.',
        function() {
          this.storage({ gold: this.storage('gold') + 5 });
        },
        'You have {{gold}} gold.',
        'end',
      ],
    });

    cy.start();
    cy.proceed();
    cy.get('text-box').contains('You have 5 gold.');

    cy.rollback();
    cy.wait(500);
    cy.get('text-box').contains('You have 5 gold.');
    cy.wrap(this.monogatari).invoke('storage', 'gold').should('equal', 5);
    cy.wrap(this.monogatari).invoke('state', 'step').should('equal', 2);
  });

  it('saves the state, the history and the storage, and loads them back', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.storage({ gold: 0 });
    this.monogatari.script({
      'Start': ['You find a purse.', purse, 'You have {{gold}} gold.', 'end'],
    });

    cy.start();
    cy.proceed();
    cy.get('text-box').contains('You have 5 gold.');

    cy.save(1).then(() => {
      cy.then(() => this.monogatari.Storage.get('Save_1')).then((slot) => {
        expect(Object.keys(slot)).to.include.members(['name', 'date', 'image', 'game']);
        expect(Object.keys(slot.game)).to.have.members(['history', 'state', 'storage']);
        expect(slot.game.state.step).to.equal(2);
        expect(slot.game.storage.gold).to.equal(5);
      });

      cy.rollback();
      cy.get('text-box').contains('You find a purse.');
      cy.wrap(this.monogatari).invoke('storage', 'gold').should('equal', 0);

      cy.load(1).then(() => {
        cy.get('text-box').contains('You have 5 gold.');
        cy.wrap(this.monogatari).invoke('storage', 'gold').should('equal', 5);
        cy.wrap(this.monogatari).invoke('state', 'step').should('equal', 2);
      });
    });
  });
});

All three pass. Answer from the code before you open the answers:

  1. In the first test, why is gold back to 0 after the rollback, and why does the game land on step 0 and not step 1?
  2. In the second test, the rollback “works” (no error), yet the game stays on “You have 5 gold.”. What happened?
  3. In the third test, what did the load do to show “You have 5 gold.” again?
  4. A player saved at step 40 of a label, and the next release of the game shortened that label to 30 statements. What happens when they load?
Answers
  1. v2 has no snapshots: nothing restores storage on a rollback except the reverting actions themselves. rollback() calls previous(), which calls revert() on the statement before the current one, the Function statement, and its Revert function took the 5 gold back. ReversibleFunction.didRevert() returns { advance: true, step: true } (the function didn’t return false), so revert() stepped back and reverted the statement before it as well, the line “You find a purse.”, which Dialog shows again and stops on.
  2. revert() in src/engine/lifecycle.ts refuses to revert a plain function (if (typeof actionToRevert === 'function') { return Promise.reject (); }). previous() catches that, moves step back by one and calls proceed(), which moves it forward again and runs “You have {{gold}} gold.” a second time. The gold stays at 5. A game that needs rollback over code must use a Function statement with a Revert.
  3. cy.load() calls loadFromSlot('Save_1') and then runs the statement at the saved step, the same thing the load screen’s slots do (src/components/slot-container/index.ts). loadFromSlot() resets the game (resetGame(): every action’s reset(), history emptied, storage back to its structure from boot), reads the slot, passes game through the migrations in src/migrations/, writes it back with state(), history() and storage(), and calls onLoad() on every action in loadingOrder groups so each one rebuilds what it shows. Then the line at step 2 runs again with {{gold}} read from the loaded storage.
  4. loadFromSlot() checks the step against the label’s length and moves it back to the label’s last statement (30 statements: step 29). The player lands on a different line than the one they saved on, and the state they restored may not match it. Release notes for a game should say when saves from an older version won’t land where they were; monogatari.upgrade() lets a game migrate its stored data between versions.

Checkpoint. Your spec passes. You can explain what history is for and what state is for, which of the two a save keeps (both, with storage), why an action’s onLoad() must not write history again, and what loadingOrder changes.

Stage 6: review changes, and break the rules on purpose

Goal. Read someone else’s change and say what it breaks before a player finds out.

Read, in this order: Reviewing a Change and Design Decisions and Why.

Do:

Break a rule the spec catches

In your scratch worktree, delete the if (updateHistory === true) { … } block from Stamp.didApply(), rebuild the bundle with bun build.ts --browser, and run the stamp spec. The rollback test fails:

1) Stamp
     Puts the previous stamp back on rollback:
   AssertionError: Timed out retrying after 4000ms: Expected to find element: `stamp-badge`, but never found it.

Without the history, revert() has nothing to pop, so going back from “Last.” to “After.” removes the badge instead of putting “Approved” back. The first and third tests still pass: showing and loading don’t need the history. Put the block back and rebuild.

Find what nothing catches

Some mistakes pass the build and every spec. Look for these in the code of the v2.8.1 tag (git switch --detach v2.8.1 in your scratch worktree); each was real there:

  1. onLoad() in src/monogatari.ts (line 682) sorts the loadingOrder values with .sort(), which compares them as text. Try it in Node: [...new Set([0, -2, 1, 2, 10])].sort() gives [ -2, 0, 1, 10, 2 ]. An action with loadingOrder = 10 would load before one with 2. Only a reviewer who knew it caught it. 2.9.0 sorts them as numbers and added cypress/e2e/actions/action.spec.js, which checks the order.
  2. CI (.github/workflows/test.yml) builds the engine and runs Cypress against the fresh build. Nothing compares the committed dist/engine/core/, dist/types/ and lib/ with src/, so a branch that forgets to commit its rebuilt bundles passes CI and ships stale files. Run bun run build and git status on every branch you review.
  3. src/components/credits-screen/index.css is not imported by src/index.css. Nothing tells you a component’s stylesheet is missing from the build. 2.9.0 imports it, and cypress/e2e/components/credits-screen.spec.js checks a rule from it reaches the page.

Review a real commit

Review the 2.8.1 commit, git show fea01a2e, item by item against Reviewing a Change, and write down what you would ask its author.

What a review of fea01a2e finds
  • The tests: three new tests in cypress/e2e/actions/show_character.spec.js, two of which fail before the fix (stage 3). Good. Nothing tests that dist/types/ is generated, but the build now fails when dist/types/index.d.ts is missing, which does the same job.
  • The record: the version in package.json went from 2.8.0 to 2.8.1 and the rebuilt dist/engine/, dist/types/ and lib/ are in the same commit. There is no changelog file in v2 to update.
  • Scope: the commit mixes the character positioning fix, the type declarations fix, vendoring random-js into src/vendor/ (which also changed package.json’s dependencies and eslint.config.mjs), new exports in package.json, and a README rewrite. Ask for them to be separate commits next time: each is easier to review, revert or bisect on its own.
  • Compatibility: the CSS now uses the translate property and adds two variables. A game that restyled [data-sprite] positions with transform in its own style/main.css may now combine both; worth a line in the release notes.
  • Not caught here: the two specs that fail on the tag because of the test asset host (stage 1) were already failing before this commit and still were after it. 2.9.0 fixed them.

Checkpoint. For every item of the review checklist, you can name what checks it for you (ESLint, tsc, a Cypress spec, the build’s own checks) or say that nothing does and the reviewer must.

Stage 7: build, release and publish the docs

Goal. Produce everything a 2.8.x release ships, and know which steps need the people who own the accounts.

Read, in this order: Building and Packaging, The Starter Game and Desktop Hosts, Releasing a 2.8.x Patch and Writing and Publishing the Docs.

Do, in your clone on the v2.8.1 tag (git switch --detach v2.8.1):

  1. Build, and check the tree is clean: bun run build, then git status.

  2. See what npm would publish, without publishing: npm pack --dry-run. It lists every file, then a summary:

    npm notice Tarball Details
    npm notice name: @monogatari/core
    npm notice version: 2.8.1
    npm notice filename: monogatari-core-2.8.1.tgz
    npm notice package size: 5.2 MB
    npm notice unpacked size: 19.2 MB
    npm notice shasum: …
    npm notice integrity: …
    npm notice total files: 539
  3. Make the starter game’s zip outside the repository and compare it with the published one. From your clone:

    mkdir -p /tmp/monogatari-release/mine /tmp/monogatari-release/theirs
    git archive --format=zip -o /tmp/monogatari-release/monogatari-v2.8.1.zip v2.8.1:dist
    cd /tmp/monogatari-release
    curl -sS -o published.zip https://storage.monogatari.io/releases/monogatari-v2.8.1.zip
    unzip -q monogatari-v2.8.1.zip -d mine
    unzip -q published.zip -d theirs
    diff -r mine theirs && echo "same files, same contents"

    v2.8.1:dist names the dist/ folder at the tag, so the zip has no top folder, like the published one. Both list 417 entries, and diff -r prints same files, same contents.

  4. Check the docs: restless-dreams docs lint docs and restless-dreams orbit validate docs/maintainers/README.md.

Checkpoint. You can list what a 2.8.x release changes and in which order (the version, the build, the commit, the tag, npm, the zip, the docs), you’ve run every step above, and you know which steps you don’t run without the people who own the npm package, the storage.monogatari.io bucket and the docs site: publishing and uploading.

After the path

You’re ready for real work. How a Change Gets In says how to pick something up and get it merged. Keep Debugging the Engine and the Glossary at hand, and read Design Decisions and Why before you propose changing one of them. Remove your scratch worktree when you no longer need it.