Becoming a Maintainer
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 installA 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:
- 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 rungit status: it shows nothing, because the committed bundles matchsrc/. - Run one spec:
bun run test --spec cypress/e2e/actions/dialog.spec.js. It plays 67 tests in about a minute and ends withAll specs passed!. - Run the whole suite:
bun run test. It runs 69 specs and 610 tests in about eleven minutes, and they all pass. - Look at the release before it. In a second worktree, check out the
v2.8.1tag, install and build there, and run two specs:git worktree add ../monogatari-2.8.1 v2.8.1, then in that folderbun install,bun run buildandbunx 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). - Play the starter game. Serve
dist/(cd dist && python3 -m http.server 8080, or any static server) and openhttp://localhost:8080. Play through the sample story. Open the browser’s developer tools and typemonogatari.state()in the console: it prints the current label and step and what is on screen.
Checkpoint. Every item holds:
bun run buildpasses and leavesgit statusclean.- You know which two tests fail on the
v2.8.1tag and why, and which commit fixed them. Find out withgit log -Sbefore you open the answer. - You can say where the starter game’s copy of the engine lives (
dist/engine/core/), and why a change tosrc/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.
- Serve
dist/as in stage 1 and open the game. - Open the developer tools (F12), go to Sources, press Ctrl+P and open
lifecycle.ts. - Find
export const proceedand set a breakpoint on its lineawait shouldProceed(engine, { userInitiated, skip, autoPlay });(line 1107 ondevelopat 2.9.0). - 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
- Which action takes
'show scen beach', misspelled? - Why does a click during the typing animation finish the line instead of moving on?
- The quick menu’s Save button is a
<button>inside the game screen. Why doesn’t clicking it also move the game forward?
Answers
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.idprints"Dialog". v2 has no script check that warns about it.Dialog.shouldProceed()(insrc/actions/Dialog.ts) runs on every click. While thefinished_typingglobal is false and the type-writer has text, it callsengine.stopTyping()and throws'TypeWriter effect has not finished.'. The rejection stopsproceed()beforenext(), so the click only finishes the line.- 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 thedata-actionhandler thatbind()sets up insrc/monogatari.tscallsevent.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.
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 installgit log -Sfinds the commit that added a piece of code: herefea01a2e, “Fix types not being generated & character positioning so move works”, the commit taggedv2.8.1.$FIX^is the commit before it,86659baf, where the bug is still there.bun installthere rewrites one line ofbun.lock; leave it.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.jsRead 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
moveclass, CSS transitions run onleftandtranslate, and they last as long astransition 3ssays, or 0.2 seconds by default.Watch it fail.
bunx cypress run --browser chromium --spec cypress/e2e/actions/show_character.spec.jsends 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.
Find the code.
ShowCharacterputs every word afterwithon the sprite as a class, somoveis there (grep -n "transition" src/actions/ShowCharacter.tsfinds where it setstransition-durationfromtransition 3s); what the class does is CSS.grep -rn "\[data-sprite\]" src --include=*.cssleads tosrc/components/game-screen/index.css. Read the[data-sprite]rule: the sprite is centered withmargin: 0 auto; left: 0; right: 0, the positions overrideleftandrightwithinitial, and the.moverule is commented out. Margins set toautoandinitialvalues can’t be animated, so the browser jumps. Fix it yourself before you look at the real fix.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.jsRepeat until all 16 tests pass.
Compare with the real fix:
git show $FIX -- src/components/game-screen/index.css src/style/variables.css. It positions the sprite withleftand thetranslateproperty (left: 50%; translate: -50%for center), which both animate, and gives.movea transition onleft, translatewhose 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.cssprints nothing: your rebuilt stylesheet is byte for byte the one the release committed.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.
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
Stampaction,stamp Approvedis a line of narration, so the first test never sees “After.”.The action,
src/actions/Stamp.ts. An action records what it shows instate(so a load can rebuild it) and inhistory(so a rollback can undo it), and undoes itself inrevert():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 instate.revert()pops it back.onLoad()rebuilds the stamp fromstateafter a load, callingdidApply()with both flags off so the load doesn’t record it a second time. That’s the same patternShowImageuses.The component,
src/components/stamp-badge/index.ts, and its stylesheetsrc/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 wayChoiceandMessagecreate theirs.Make them built-ins. In
src/index.ts, importStampand add it toMonogatari._actions(anywhere beforeDialog, which must stay last), and importStampBadgeand add it toMonogatari._components. Insrc/index.css, add@import './components/stamp-badge/index.css';with the other components.Build:
bun run build. It lints, type-checks and rebuilds everything in about 9 seconds.git statusnow shows your new files, the rebuiltdist/engine/core/andlib/bundles, and new declarations indist/types/.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 loadedThe record. A real change would also add a page for the statement in
docs/script-actions/and one for the element indocs/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:
- In the first test, why is
goldback to 0 after the rollback, and why does the game land on step 0 and not step 1? - In the second test, the rollback “works” (no error), yet the game stays on “You have 5 gold.”. What happened?
- In the third test, what did the load do to show “You have 5 gold.” again?
- 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
- v2 has no snapshots: nothing restores
storageon a rollback except the reverting actions themselves.rollback()callsprevious(), which callsrevert()on the statement before the current one, the Function statement, and itsRevertfunction took the 5 gold back.ReversibleFunction.didRevert()returns{ advance: true, step: true }(the function didn’t returnfalse), sorevert()stepped back and reverted the statement before it as well, the line “You find a purse.”, whichDialogshows again and stops on. revert()insrc/engine/lifecycle.tsrefuses to revert a plain function (if (typeof actionToRevert === 'function') { return Promise.reject (); }).previous()catches that, movesstepback by one and callsproceed(), 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 aFunctionstatement with aRevert.cy.load()callsloadFromSlot('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’sreset(), history emptied, storage back to its structure from boot), reads the slot, passesgamethrough the migrations insrc/migrations/, writes it back withstate(),history()andstorage(), and callsonLoad()on every action inloadingOrdergroups so each one rebuilds what it shows. Then the line at step 2 runs again with{{gold}}read from the loaded storage.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:
onLoad()insrc/monogatari.ts(line 682) sorts theloadingOrdervalues 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 withloadingOrder = 10would load before one with2. Only a reviewer who knew it caught it. 2.9.0 sorts them as numbers and addedcypress/e2e/actions/action.spec.js, which checks the order.- CI (
.github/workflows/test.yml) builds the engine and runs Cypress against the fresh build. Nothing compares the committeddist/engine/core/,dist/types/andlib/withsrc/, so a branch that forgets to commit its rebuilt bundles passes CI and ships stale files. Runbun run buildandgit statuson every branch you review. src/components/credits-screen/index.cssis not imported bysrc/index.css. Nothing tells you a component’s stylesheet is missing from the build. 2.9.0 imports it, andcypress/e2e/components/credits-screen.spec.jschecks 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 thatdist/types/is generated, but the build now fails whendist/types/index.d.tsis missing, which does the same job. - The record: the version in
package.jsonwent from 2.8.0 to 2.8.1 and the rebuiltdist/engine/,dist/types/andlib/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-jsintosrc/vendor/(which also changedpackage.json’s dependencies andeslint.config.mjs), new exports inpackage.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
translateproperty and adds two variables. A game that restyled[data-sprite]positions withtransformin its ownstyle/main.cssmay 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):
Build, and check the tree is clean:
bun run build, thengit status.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: 539Make 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:distnames thedist/folder at the tag, so the zip has no top folder, like the published one. Both list 417 entries, anddiff -rprintssame files, same contents.Check the docs:
restless-dreams docs lint docsandrestless-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.