@gameslate/sdk 0.3.7 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,6 +13,62 @@ const Hex = z
13
13
  .regex(/^0x[0-9a-fA-F]{1,8}$/, 'a hex address such as 0x801EF6AA')
14
14
  .transform(h => Number.parseInt(h, 16));
15
15
  const Expected = z.union([z.number(), z.object({ min: z.number(), max: z.number() })]);
16
+ /** A guest value to watch while driving: `{ "peek": "0x800dc50c:4", "equals": 4 }`. */
17
+ const PeekCheck = z.object({
18
+ peek: z.string().regex(/^0x[0-9a-fA-F]{1,8}:[124]$/, 'a guest address and size: 0x800dc50c:4'),
19
+ equals: z.number().int(),
20
+ });
21
+ /** What a moment must read: the plugin's state, field by field (counters exact or in a range). */
22
+ const ExpectSchema = z.object({
23
+ phase: z.string().optional(),
24
+ locationId: z.string().optional(),
25
+ difficulty: z.string().optional(),
26
+ variant: z.string().optional(),
27
+ roomId: z.number().int().optional(),
28
+ counters: z.record(z.string(), Expected).default({}),
29
+ /** what the inventory must hold, must not hold, or must hold exactly (any order) */
30
+ inventory: z
31
+ .object({
32
+ has: z.array(z.string()).default([]),
33
+ lacks: z.array(z.string()).default([]),
34
+ exactly: z.array(z.string()).optional(),
35
+ })
36
+ .optional(),
37
+ /** the equipped item, or null for nothing */
38
+ equipped: z.string().nullable().optional(),
39
+ /** flags that must read true or false (a flag the state doesn't report is a mismatch) */
40
+ flags: z.record(z.string(), z.boolean()).default({}),
41
+ });
42
+ /** Wait on the plugin's own state, for moments no fixed address shows (a PlayState that moves):
43
+ * `{ "state": { "phase": "in_stage", "locationId": "lost_woods_intro" } }`. */
44
+ const StateCheck = z.object({ state: ExpectSchema });
45
+ /* `times`: how many reads in a row must match. Transitions can pass through a state for a frame
46
+ * (MM's opening reads as gameplay between its scripted shots), which shouldn't count. */
47
+ const Times = { times: z.number().int().min(1).default(1) };
48
+ const WaitCheck = z.union([PeekCheck.extend(Times), StateCheck.extend(Times)]);
49
+ /* One step of driving the game to its moment, run through `gameslate drive`. */
50
+ const StepSchema = z.union([
51
+ z.object({
52
+ /** a key (X keysym name) to press, once, or until a value matches; several keys take
53
+ * turns (a map where Start selects and A reads on through the briefing) */
54
+ press: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]),
55
+ holdMs: z.number().int().min(0).default(100),
56
+ until: WaitCheck.optional(),
57
+ everyMs: z.number().int().min(0).default(2000),
58
+ maxTries: z.number().int().min(1).default(20),
59
+ }),
60
+ z.object({
61
+ waitFor: WaitCheck,
62
+ timeoutMs: z.number().int().min(0).default(30_000),
63
+ everyMs: z.number().int().min(100).default(1000),
64
+ }),
65
+ /** the screen the game drew, saved under this name beside the spec */
66
+ z.object({ frame: z.string().min(1) }),
67
+ /** a pause, for screens nothing in memory marks (a boot, a menu's fade) */
68
+ z.object({ waitMs: z.number().int().min(0) }),
69
+ ]);
70
+ /* the web app's tabs; one missing for a game (a pack without missions) is reported, not an error */
71
+ const UI_TABS = ['Map', 'Inventory', 'Missions', 'Ref'];
16
72
  export const VerifySpecSchema = z.object({
17
73
  /** the game id the daemon must report */
18
74
  game: z.string().min(1),
@@ -31,20 +87,31 @@ export const VerifySpecSchema = z.object({
31
87
  port: z.number().int().default(55355),
32
88
  })
33
89
  .optional(),
90
+ /** any emulator, started with this command (the ROM on its command line, so the core finds it) */
91
+ emulator: z
92
+ .object({
93
+ command: z.array(z.string()).min(1),
94
+ /** as for RetroArch: through GameSlate's launch wrapper where only a parent may read */
95
+ launchPrefix: z.array(z.string()).default([]),
96
+ })
97
+ .optional(),
98
+ /** GameSlate's `dist/gameslate.mjs`, whose `drive` commands run the steps */
99
+ gameslate: z.string().optional(),
100
+ /** how to get to the moment: keys, waits on values, screenshots (docs/emulator-driving.md) */
101
+ steps: z.array(StepSchema).default([]),
34
102
  daemon: z.object({ url: z.string().default('ws://localhost:4310/ws') }).default({}),
35
- /** the GameSlate page to screenshot beside the game */
36
- ui: z.string().optional(),
103
+ /** the GameSlate page to screenshot beside the game: a URL (with its `#token=`), or the URL and
104
+ * the tabs to open and screenshot one by one at the moment */
105
+ ui: z
106
+ .union([
107
+ z.string().transform(url => ({ url, tabs: [...UI_TABS] })),
108
+ z.object({ url: z.string(), tabs: z.array(z.string().min(1)).default([...UI_TABS]) }),
109
+ ])
110
+ .optional(),
37
111
  /** how long to let the game run before reading */
38
112
  settleMs: z.number().int().min(0).default(5000),
39
113
  timeoutMs: z.number().int().min(1000).default(60_000),
40
- expect: z.object({
41
- phase: z.string().optional(),
42
- locationId: z.string().optional(),
43
- difficulty: z.string().optional(),
44
- variant: z.string().optional(),
45
- roomId: z.number().int().optional(),
46
- counters: z.record(z.string(), Expected).default({}),
47
- }),
114
+ expect: ExpectSchema,
48
115
  /** values to read through the emulator too: each must equal the plugin's counter */
49
116
  memory: z
50
117
  .array(z
@@ -59,6 +126,25 @@ export const VerifySpecSchema = z.object({
59
126
  }))
60
127
  .default([]),
61
128
  });
129
+ /**
130
+ * `${NAME}` in any string of a spec, from the environment, so a spec can be shared without one
131
+ * machine's paths (`"${GOPHER64}"`, `"${N64_ROMS}/Mario Kart 64 (U).z64"`). Throws on a name that
132
+ * isn't set.
133
+ */
134
+ export function expandEnv(value, env) {
135
+ if (typeof value === 'string')
136
+ return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => {
137
+ const set = env[name];
138
+ if (set === undefined)
139
+ throw new Error(`the spec uses \${${name}}, which isn't set`);
140
+ return set;
141
+ });
142
+ if (Array.isArray(value))
143
+ return value.map(v => expandEnv(v, env));
144
+ if (typeof value === 'object' && value !== null)
145
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, expandEnv(v, env)]));
146
+ return value;
147
+ }
62
148
  /** What doesn't match: one line each. */
63
149
  export function stateMismatches(expect, state) {
64
150
  const out = [];
@@ -80,6 +166,38 @@ export function stateMismatches(expect, state) {
80
166
  else if (got < want.min || got > want.max)
81
167
  out.push(`counter ${id}: expected ${want.min}..${want.max}, got ${got}`);
82
168
  }
169
+ out.push(...inventoryMismatches(expect.inventory, state.inventory));
170
+ out.push(...equippedAndFlagMismatches(expect, state));
171
+ return out;
172
+ }
173
+ function equippedAndFlagMismatches(expect, state) {
174
+ const out = [];
175
+ if (expect.equipped !== undefined && expect.equipped !== (state.equipped ?? null))
176
+ out.push(`equipped: expected ${expect.equipped ?? 'nothing'}, got ${state.equipped ?? 'nothing'}`);
177
+ for (const [id, want] of Object.entries(expect.flags)) {
178
+ const got = state.flags[id];
179
+ if (got === undefined)
180
+ out.push(`flag ${id}: not reported`);
181
+ else if (got !== want)
182
+ out.push(`flag ${id}: expected ${String(want)}, got ${String(got)}`);
183
+ }
184
+ return out;
185
+ }
186
+ function inventoryMismatches(want, got) {
187
+ if (!want)
188
+ return [];
189
+ const held = new Set(got);
190
+ const out = [
191
+ ...want.has.filter(id => !held.has(id)).map(id => `inventory: missing ${id}`),
192
+ ...want.lacks.filter(id => held.has(id)).map(id => `inventory: has ${id}, expected not`),
193
+ ];
194
+ if (want.exactly) {
195
+ const expected = new Set(want.exactly);
196
+ const extra = got.filter(id => !expected.has(id));
197
+ const missing = want.exactly.filter(id => !held.has(id));
198
+ if (extra.length || missing.length)
199
+ out.push(`inventory: expected exactly [${want.exactly.join(', ')}], got [${got.join(', ')}]`);
200
+ }
83
201
  return out;
84
202
  }
85
203
  /** RetroArch's network command reading a value with RetroAchievements' addressing. */
@@ -116,20 +234,92 @@ async function memoryProblems(spec, state, effects) {
116
234
  }
117
235
  return out;
118
236
  }
119
- /** Runs one check: start the game, let it settle, compare, screenshot, stop. */
237
+ /* A watched value (through `gameslate drive peek`) or the plugin's state (from the daemon). */
238
+ async function checkMatches(d, check) {
239
+ if ('state' in check) {
240
+ const parsed = GameStateSchema.safeParse(await d.effects.state(d.spec));
241
+ return parsed.success && stateMismatches(check.state, parsed.data).length === 0;
242
+ }
243
+ const out = await d.effects.drive(d.spec, ['peek', String(d.pid), check.peek]);
244
+ const values = JSON.parse(out);
245
+ return (typeof values === 'object' &&
246
+ values !== null &&
247
+ Reflect.get(values, check.peek) === check.equals);
248
+ }
249
+ const describeCheck = (check) => 'state' in check
250
+ ? `the state ${JSON.stringify(check.state)}`
251
+ : `${check.peek} = ${check.equals}`;
252
+ /* One step; a problem when it couldn't do what it says, or null. */
253
+ async function runStep(d, step, frames) {
254
+ if ('frame' in step) {
255
+ await d.effects.drive(d.spec, ['frame', String(d.pid), step.frame]);
256
+ frames.push(step.frame);
257
+ return null;
258
+ }
259
+ if ('waitMs' in step) {
260
+ await d.effects.wait(step.waitMs);
261
+ return null;
262
+ }
263
+ if ('waitFor' in step) {
264
+ let streak = 0;
265
+ for (let waited = 0; waited <= step.timeoutMs; waited += step.everyMs) {
266
+ streak = (await checkMatches(d, step.waitFor)) ? streak + 1 : 0;
267
+ if (streak >= step.waitFor.times)
268
+ return null;
269
+ await d.effects.wait(step.everyMs);
270
+ }
271
+ return `waited ${step.timeoutMs} ms for ${describeCheck(step.waitFor)}`;
272
+ }
273
+ const keys = typeof step.press === 'string' ? [step.press] : step.press;
274
+ let streak = 0;
275
+ for (let i = 0; i < (step.until ? step.maxTries : 1); i++) {
276
+ const key = keys[i % keys.length] ?? '';
277
+ await d.effects.drive(d.spec, ['press', '--pid', String(d.pid), key, String(step.holdMs)]);
278
+ if (!step.until)
279
+ return null;
280
+ await d.effects.wait(step.everyMs);
281
+ streak = (await checkMatches(d, step.until)) ? streak + 1 : 0;
282
+ if (streak >= step.until.times)
283
+ return null;
284
+ }
285
+ return `pressed ${keys.join('/')} ${step.maxTries} times without ${step.until ? describeCheck(step.until) : ''}`;
286
+ }
287
+ /** Drives the game to its moment; the first problem stops it. */
288
+ async function runSteps(spec, effects, pid) {
289
+ const frames = [];
290
+ if (!spec.steps.length)
291
+ return { problem: null, frames };
292
+ if (pid === undefined)
293
+ return { problem: 'steps need an emulator the run started', frames };
294
+ for (const step of spec.steps) {
295
+ const problem = await runStep({ spec, effects, pid }, step, frames).catch((e) => e instanceof Error ? e.message : String(e));
296
+ if (problem)
297
+ return { problem, frames };
298
+ }
299
+ return { problem: null, frames };
300
+ }
301
+ /** Runs one check: start the game, drive it to its moment, let it settle, compare, screenshot, stop. */
120
302
  export async function runVerify(spec, effects) {
121
303
  const game = await effects.launch(spec);
122
304
  try {
305
+ const driven = await runSteps(spec, effects, game.pid);
306
+ if (driven.problem)
307
+ return {
308
+ ok: false,
309
+ problems: [driven.problem],
310
+ screenshots: driven.frames,
311
+ state: null,
312
+ };
123
313
  await effects.wait(spec.settleMs);
124
314
  const raw = await effects.state(spec).catch((e) => e);
125
315
  if (raw instanceof Error)
126
- return { ok: false, problems: [raw.message], screenshots: [], state: null };
316
+ return { ok: false, problems: [raw.message], screenshots: driven.frames, state: null };
127
317
  const parsed = GameStateSchema.safeParse(raw);
128
318
  if (!parsed.success)
129
319
  return {
130
320
  ok: false,
131
321
  problems: [`the daemon's state: ${parsed.error.message}`],
132
- screenshots: [],
322
+ screenshots: driven.frames,
133
323
  state: null,
134
324
  };
135
325
  const state = parsed.data;
@@ -137,7 +327,7 @@ export async function runVerify(spec, effects) {
137
327
  ...stateMismatches(spec.expect, state),
138
328
  ...(await memoryProblems(spec, state, effects)),
139
329
  ];
140
- const screenshots = await effects.screenshots(spec);
330
+ const screenshots = [...driven.frames, ...(await effects.screenshots(spec))];
141
331
  return { ok: problems.length === 0, problems, screenshots, state };
142
332
  }
143
333
  finally {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gameslate/sdk",
3
- "version": "0.3.7",
3
+ "version": "0.3.9",
4
4
  "description": "Build plugins for GameSlate, the second-screen companion for PC games: the plugin contract, game-state and catalogue schemas, and the plugin builder.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -69,6 +69,22 @@ evaluator in the SDK decides "done", "collected" and "available". Rules:
69
69
  - Give counters a `role` (`health`, `magic`, `armor`, `keys`) so shared UI finds them.
70
70
  - Use `format: 'percent'` with a `max` for meters.
71
71
 
72
+ **What to put in a pack** (Mario Kart 64 and Star Fox 64 in gameslate-n64 are worked examples):
73
+
74
+ - **Inventory:** what the player holds or chose (driver, held item), as `slotGrid`s; the run's
75
+ numbers (place, lap, time, shields) as `counters` layouts. A shield or HP gets `role: 'health'`
76
+ and `max` naming another counter when its maximum changes (`shieldMax`).
77
+ - **Missions from the save:** one per thing the save records (a cup's trophy per class, a planet's
78
+ medal), with steps for each tier, and `availableWhen` for what the game unlocks later (Extra
79
+ after a 150cc gold in every cup, read from the unlock function, not a wiki).
80
+ - **Missions from live play:** a level's target while flying it (`availableWhen: { at }`,
81
+ `progress: { counter, target }`, steps per requirement).
82
+ - **Reference and chips:** tables the game's code defines (cups, points, routes), in your own
83
+ words; chips that ask about the current location.
84
+ - **Facts come from the code that decides them.** A game can show one number and check another:
85
+ Star Fox 64's HUD flags a medal at 200 hits on Macbeth, but the level's end checks 150, and
86
+ that's what the save records. Read the function that writes the save.
87
+
72
88
  ## 4. Memory addresses, verified
73
89
 
74
90
  **Pin the build.** List the exact builds you verified in the source's `supportedBuildIds` (a
@@ -86,6 +102,46 @@ comments like `/* 0x0E9C */` are not a source.
86
102
 
87
103
  **Console decompilations:**
88
104
 
105
+ `gameslate-plugin addresses <spec.json> [--out plugin/addresses.ts]` does steps 2, 3 and 5 below
106
+ in one go: it reads the globals from the decomp's maps (ld `.map` or splat `symbol_addrs*.txt`),
107
+ subtracts a revision delta if given, compiles a probe of `offsetof`, `sizeof` and constants
108
+ against the headers, and writes a table whose header names the commit and every source. A symbol
109
+ the maps lack or a value clang can't fold fails the run. Example spec (the one that reproduced
110
+ Mario Kart 64's verified addresses):
111
+
112
+ ```json
113
+ {
114
+ "decomp": "${MK64_DECOMP}",
115
+ "symbolFiles": ["build/us/mk64.us.map"],
116
+ "includes": ["<ultra64.h>", "common_structs.h", "save_data.h", "course.h"],
117
+ "clang": { "args": ["--target=mips-unknown-linux-gnu", "-mabi=32", "-fno-pic", "-D_LANGUAGE_C",
118
+ "-DTARGET_N64=1", "-DVERSION_US=1", "-D_MIPS_SZLONG=32", "-nostdinc",
119
+ "-isystem", "${CLANG_INCLUDE}", "-Iinclude", "-Iinclude/libc", "-Isrc", "-Ibuild/us", "-I."] },
120
+ "symbols": ["gGamestate", "gPlayers", "gSaveData"],
121
+ "offsets": ["Player.rotation", "SaveData.main.saveInfo.grandPrixPoints"],
122
+ "sizes": ["Player", "CourseVtx"],
123
+ "constants": { "COURSE_LUIGI_RACEWAY": "COURSE_LUIGI_RACEWAY" }
124
+ }
125
+ ```
126
+
127
+ A decomp that generates headers at build time (Paper Mario's `item_enum.h`) needn't be built:
128
+ list them in `"stubHeaders"` and the probe gets empty ones (a layout that really needs one still
129
+ fails to compile). Constants come back signed.
130
+
131
+ **Always list `"expectSizes"`** for the structs you read, from the decomp's `// size = 0x…`
132
+ comments or a symbol's `size:` over its count: the run fails if the probe disagrees. And compile
133
+ the probe in the C standard the game was built with (`-std=gnu89` for IDO and KMC GCC games):
134
+ Dr. Mario 64's `bool` is a 4-byte enum under C89 but clang's 1-byte `_Bool` under C17, which put
135
+ every field after it 6 bytes early while looking perfectly plausible.
136
+
137
+ For another revision add `"subtract": "0xA190"` (and check the delta against verified leads
138
+ first). Commit the spec and the generated table; the decomp and ROM stay local.
139
+
140
+ 0. **Check GameSlate can attach before writing a reader:** start the game in the emulator and
141
+ `gameslate drive peek <pid> <a code address>:4`; the word must equal the ROM's bytes for that
142
+ function (the symbol file's `rom:` offset). Paper Mario needed two core fixes here: its boot
143
+ chip (CIC-6103) loads the game 1 MB below the header's entry point, and its low memory has no
144
+ `osMemSize`.
89
145
  1. Build the decomp and check the output's **md5 equals the player's ROM**. Mind the region: some
90
146
  Makefiles default to another region and still print "OK" against their own checksum.
91
147
  2. Probe the struct offsets by compiling the decomp's headers for the console's ABI. For N64 that's
@@ -95,6 +151,16 @@ comments like `/* 0x0E9C */` are not a source.
95
151
  trust it only with a check from the same build, such as "this state's update function is the
96
152
  one the map says".
97
153
 
154
+ 5. **The decomp builds another revision** (Star Fox 64's builds US 1.1, the player has 1.0):
155
+ global addresses often differ by a constant per segment. Check every verified lead against
156
+ its symbol (`symbol − lead`); if they all agree, take the remaining globals as symbol − delta,
157
+ say so in the source, and verify the new ones live. Types and struct layouts carry over.
158
+ 6. **Prove a save block's address with the game's own checksum:** read the block live, run the
159
+ game's checksum function over it (ported from the decomp), and compare with the stored one. A
160
+ blank save reads as zeros anywhere, so a zero read proves nothing.
161
+ 7. **Sizes and signs come from declarations and probes, never from guesses:** a 14-byte struct
162
+ isn't 16 (`CourseVtx` has 2-byte alignment); a `u8` read as `getInt8` turns 0xFD into -3.
163
+
98
164
  **Leads, from LiveSplit or RetroAchievements:**
99
165
 
100
166
  - A lead is not a source. Verify every value live, across levels, menus and loads.
@@ -139,6 +205,34 @@ Every image of a game uses one format. In the sandbox:
139
205
  - **Data licensing:** ship the extractor, never its output. Textures, models and renders are
140
206
  built on the player's machine and never committed.
141
207
 
208
+ ### Maps from a ROM (Mario Kart 64 in gameslate-n64 is the worked example)
209
+
210
+ 1. **Follow the game's own load path** in the decomp: the table that names each level's data
211
+ (`gCourseTable`), how each segment is stored (MIO0, raw), how it's unpacked
212
+ (`displaylist_unpack`). Read the ROM's table at runtime and check what you read (MIO0 magic,
213
+ segment numbers) so a different ROM fails loud.
214
+ 2. **Port decoders exactly:** for a byte-coded stream, write down each opcode's argument bytes
215
+ and how many commands it emits. Offsets into the unpacked data depend on every count being right.
216
+ 3. **Draw what the player drives on:** the collision mesh, not the render lists. Use the lists the
217
+ game collides with, apply the same filters (section flags that drop flat or upright triangles,
218
+ vertices flagged "no collision"), keep floors facing up by winding, and colour by surface type.
219
+ Shade by height and draw higher floors later so bridges sit over roads.
220
+ 4. **Location ids are asset ids:** lower-case words, dots and dashes, **no underscores**. The
221
+ `locationId` the live reader reports must equal them.
222
+ 5. **Place the player:** the layer's affine maps world x/z onto the drawing exactly as it was
223
+ drawn. Find the heading convention live: drive straight, then steer one way, and compare the
224
+ movement with the yaw (MK64: yaw θ drives along (−sin θ, cos θ)). Mirror modes negate x: put the
225
+ player back on the unmirrored map.
226
+ 6. **Look at it.** Render the SVGs (`rsvg-convert -w 500 map.svg -o map.png`) and compare with
227
+ the game's own minimap.
228
+ 7. **A game needs a registry entry** (`gameslate-registry/games/<id>/manifest.json`: title,
229
+ capabilities with `map_2d`, difficulties, item names; locations empty) before the web app shows
230
+ extracted maps. Doom's is the pattern. Don't hand-edit `index.json` and `channels.json`: write a
231
+ spec (id, title, subtitle, romIds, capabilities, locations) from the plugin's own data and run
232
+ the gameslate repo's `yarn vite-node tools/registry-add-game.ts <spec.json>`, which writes the
233
+ manifest, keeps any hints, sets the index entry and rehashes channels with the registry
234
+ builders' own writers (gameslate-n64's `tools/registry-specs.ts` writes its specs).
235
+
142
236
  ## 6. Tests
143
237
 
144
238
  - **Decoders:** fixture snapshot in, expected `GameState` out, including menus, no save, and edge
@@ -152,11 +246,18 @@ Every image of a game uses one format. In the sandbox:
152
246
  - **Every bug fix gets a test that fails without the fix.** Break the code, watch it fail, restore.
153
247
  - **No game data in fixtures:** build synthetic ones (bytes you wrote) and record what the reference
154
248
  tool produced from them.
249
+ - **Tests against the player's own files** run only when one is given
250
+ (`describe.runIf(process.env.MK64_ROM)`), read it in `beforeAll` (a describe body runs at
251
+ collection even when skipped, and a missing file fails the whole file), and pin live facts:
252
+ positions read in a real race must land on the decoded floors.
253
+ - **Get an independent review** of a decoder against the decomp's source (the
254
+ `review-correctness` lens, or a fresh agent given the code and the decomp's paths, not your
255
+ conclusions). On Mario Kart 64 it found three real bugs the renders didn't show.
155
256
 
156
257
  ## 7. Verify live
157
258
 
158
- Use the `verify-gameslate-plugin` skill. It runs the game from a save state, reads what your plugin
159
- reports, screenshots the game and GameSlate, and checks them against `verify.json`. Until a build
259
+ Use the `verify-gameslate-plugin` skill. It drives the game to a known moment, reads what your
260
+ plugin reports, screenshots the game and GameSlate, and checks them against `verify.json`. Until a build
160
261
  passes, say so in the README ("unverified: offsets from leads") and keep it out of a release.
161
262
 
162
263
  ## 8. Release
@@ -177,6 +278,32 @@ plugin exactly as the core will before running it. Then bump `version`, tag `vX.
177
278
  - **Big inputs:** files over 256 MiB are identified by size and modification time, not hashed.
178
279
  Don't rely on a byte change inside a huge file being noticed unless its size or mtime changes too.
179
280
  - **Emulators:** the core finds an N64 game's RAM by the ROM's boot code. The ROM must be on the
180
- emulator's command line, and the game must have booted.
281
+ emulator's command line, and the game must have booted. CIC-6103 and 6106 games (Paper Mario,
282
+ Banjo-Kazooie) load below their header's entry point; the core works that out from the boot
283
+ code's CRC.
284
+ - **A symbol may be a pointer, not the struct.** The gap to the next symbol in the map is its
285
+ size: Super Smash Bros.' `gSCManagerBattleState` is 4 bytes, a pointer that the opening movies
286
+ aim at their own staged fights. Read through it, and check the pointer lands in RAM.
287
+ - **The game's own mode variable can mislead.** Smash's 1P battle runs with the scene still
288
+ reading Title (the 1P intro sets it as its exit, and the battle starts without changing it).
289
+ Check each phase against the screen live, and combine signals (previous scene, which state a
290
+ pointer aims at) when one variable isn't enough.
291
+ - **Attract demos** run the real game loop with the demo's own data (Paper Mario's demo story,
292
+ Dr. Mario's demo bottles, Smash's auto-demo and openings): find the flag or scene that marks
293
+ them before trusting any value, and make them read as the title.
294
+ - **The game mode can be a function pointer:** when the decomp keeps the current mode in a
295
+ file-static the symbol maps don't list, read the mode table instead (Paper Mario:
296
+ `gMainGameMode[0].step` equals a `state_step_*` symbol).
297
+ - **A field in the wrong place compiles and vanishes.** TypeScript's excess-property check
298
+ doesn't look inside a conditional spread (`...(x ? { roomId } : {})`), and the daemon's schema
299
+ drops unknown keys, so a room put beside `position` instead of inside it never arrives (Quest
300
+ 64's first route caught it; its unit test checked the same wrong place). Write state fields
301
+ directly, and let a route's `expect` check what the daemon actually sends.
302
+ - **Unnamed values and globals:** a decomp with few names (Kirby 64) still gives addresses: a
303
+ splat `D_<address>` is its address. Cite the function that reads it, and confirm each live.
304
+ - **Menus may read only the d-pad.** Gopher64's d-pad is `w` `a` `s` `d` and its arrows are the
305
+ stick (`~/.config/gopher64/config.json`); Kirby 64's menus ignore the stick.
306
+ - **Menus remember:** many games save the last menu choices, so a route that only presses Start
307
+ lands somewhere else next time. Pin each choice with the game's own menu variables.
181
308
  - **Prove it on real data before writing to a player's files.** Back up what's there before the
182
309
  first run on a real machine.
@@ -19,7 +19,15 @@ one moment that's **not** gameplay (title or file select), so "no save loaded" i
19
19
  ## 2. Get to the moment
20
20
 
21
21
  **Drive the game yourself; don't wait for a person.** For an emulated console, this loop is
22
- proven (GameSlate's `docs/emulator-driving.md`):
22
+ proven, and GameSlate's `gameslate drive` does each step (`docs/emulator-driving.md`):
23
+
24
+ ```sh
25
+ gameslate drive press Return 120 # keys, with hold times
26
+ gameslate drive peek <pid> 0x800dc50c:4 # guest values, read frozen
27
+ gameslate drive frame <pid> screen.png # the screen the game drew
28
+ ```
29
+
30
+ The steps:
23
31
 
24
32
  1. **Pause:** `SIGSTOP` the emulator process. `SIGCONT` resumes it. Memory stays readable while
25
33
  it's stopped.
@@ -50,31 +58,74 @@ Script the route per game as inputs plus checks, such as "Start until game state
50
58
 
51
59
  ## 3. Write `verify.json`
52
60
 
61
+ An emulator, the route to the moment (`steps`), and what the moment must read. This one passed on
62
+ Mario Kart 64 on 2026-11-30: from boot to the start of a Grand Prix, untouched by a person. Each
63
+ menu choice (1 player, Grand Prix, 50cc, Mushroom Cup) is pinned by the game's own menu variables
64
+ (`gMainMenuSelection`, `gPlayerCount`, `gGameModeMenuColumn`, `gCupSelection` from the decomp's
65
+ map), because the game saves the last choices.
66
+
53
67
  ```json
54
68
  {
55
- "game": "2ship2harkinian",
56
- "retroarch": {
57
- "binary": "/path/to/retroarch",
58
- "core": "/path/to/mupen64plus_next_libretro.so",
59
- "rom": "/path/to/game.z64",
60
- "stateSlot": 1,
61
- "config": "verify-retroarch.cfg"
62
- },
63
- "ui": "http://localhost:4310/",
64
- "settleMs": 5000,
69
+ "game": "mario-kart-64",
70
+ "gameslate": "/path/to/gameslate/dist/gameslate.mjs",
71
+ "emulator": { "command": ["/path/to/gopher64", "/path/to/Mario Kart 64 (U).z64"] },
72
+ "steps": [
73
+ { "waitFor": { "peek": "0x800dc50c:4", "equals": 4 }, "timeoutMs": 60000, "everyMs": 2000 },
74
+ { "press": "Return", "holdMs": 120, "until": { "peek": "0x800dc50c:4", "equals": 0 } },
75
+ { "press": "Return", "holdMs": 120, "until": { "peek": "0x8018eded:1", "equals": 3 } },
76
+ { "press": "Left", "holdMs": 120, "until": { "peek": "0x8018edf3:1", "equals": 1 } },
77
+ { "press": "Shift_L", "holdMs": 120, "until": { "peek": "0x8018eded:1", "equals": 4 } },
78
+ { "press": "Up", "holdMs": 120, "until": { "peek": "0x800e86ac:1", "equals": 0 } },
79
+ { "press": "Shift_L", "holdMs": 120, "until": { "peek": "0x8018eded:1", "equals": 5 } },
80
+ { "press": "Up", "holdMs": 120, "until": { "peek": "0x800e86b0:1", "equals": 0 } },
81
+ { "press": "Shift_L", "holdMs": 120, "until": { "peek": "0x8018eded:1", "equals": 6 } },
82
+ { "press": "Return", "holdMs": 120, "until": { "peek": "0x8018edec:1", "equals": 1 } },
83
+ { "press": "Left", "holdMs": 120, "until": { "peek": "0x8018ee09:1", "equals": 0 } },
84
+ { "press": "Return", "holdMs": 120, "until": { "peek": "0x800dc50c:4", "equals": 4 } },
85
+ { "press": "Shift_L", "holdMs": 8000 },
86
+ { "frame": "mk64-gp-start.png" }
87
+ ],
88
+ "settleMs": 0,
65
89
  "expect": {
66
90
  "phase": "in_stage",
67
- "locationId": "south_clock_town",
68
- "difficulty": "day_1",
69
- "counters": { "rupees": 123, "health": { "min": 0.4, "max": 0.6 } }
70
- },
71
- "memory": [{ "address": "0x801EF6AA", "size": 2, "signed": true, "counter": "rupees" }]
91
+ "locationId": "luigi-raceway",
92
+ "variant": "grand_prix",
93
+ "difficulty": "50cc",
94
+ "counters": { "lap": 1, "place": { "min": 1, "max": 8 }, "raceTime": { "min": 0.1, "max": 5 } }
95
+ }
72
96
  }
73
97
  ```
74
98
 
99
+ - **Steps:**
100
+ - `press` sends a key to the emulator's window (focused first). With `until`, it repeats every
101
+ `everyMs` until the peeked value matches, up to `maxTries`. Given several keys
102
+ (`["Return", "Shift_L"]`), they take turns: menus differ in which button they take. Star
103
+ Fox 64's map needs Start to pick the planet and A through the briefing.
104
+ - `waitFor` waits on a check.
105
+ - `waitMs` pauses, for screens nothing in memory marks.
106
+ - `frame` saves the screen the game drew.
107
+ - A check is a peeked value (`{ "peek": "0x…:4", "equals": 4 }`) or the plugin's own state
108
+ (`{ "state": { "phase": "in_stage", "locationId": "lost_woods_intro" } }`), for moments
109
+ whose address moves.
110
+ - `"times": 3` needs that many matching reads in a row. Transitions can pass through a state
111
+ for an instant: MM's opening reads as gameplay between its shots.
112
+
113
+ The first step that can't do what it says stops the run and names itself.
114
+ - **Pin every menu choice.** A route that presses Start until "racing" goes wherever the saved
115
+ cursors point; after one run in 2-player Versus, the next run raced there too. Wait for each menu
116
+ screen by its variable, then press a direction until the cursor variable reads your choice.
117
+ - **Boot isn't the moment.** A state variable can already hold your target value during the boot
118
+ logo (MK64's game state reads 4, "racing", before the title), and keys are ignored there. Wait
119
+ for a value only the moment has, or for the attract demo after the logo.
120
+ - **Guard against games that drive themselves.** Attract demos cycle through the same states
121
+ your route waits on: a route whose keys never arrived once "passed" every step on the demo. Make
122
+ `expect` specific enough that the demo can't match it (this course, this mode, this class).
123
+ - Without `steps`, a `retroarch` block (binary, core, ROM, `stateSlot`) loads a save state
124
+ instead. That's the fallback when no route from boot is practical.
75
125
  - Paths are relative to the file. Keep one file per moment (`verify/<moment>.json`), next to the
76
- tests. They hold no game data; the ROM and the state stay on your machine.
77
- - `memory` reads each address through RetroArch (`READ_CORE_RAM`, RetroAchievements'
126
+ tests. They hold no game data; the ROM, any state, and the frames stay on your machine
127
+ (git-ignore `verify/*.png`).
128
+ - With RetroArch, `memory` reads each address through RetroArch (`READ_CORE_RAM`, RetroAchievements'
78
129
  addressing; the tool converts a guest address for you) and requires it to equal the plugin's
79
130
  counter. That second opinion catches a wrong offset that still looks plausible. Use it for at
80
131
  least one value per struct the plugin reads (save, live game state).
@@ -84,23 +135,45 @@ Script the route per game as inputs plus checks, such as "Start until game state
84
135
 
85
136
  ## 4. Run it
86
137
 
138
+ **Keep the emulator's window in front.** Keys go to whichever window has the keyboard. `press`
139
+ refuses to type into another window: it waits up to 30 s for you (or the person at the machine)
140
+ to click the emulator, and stops the run if focus moves while a key is held. Under WSLg a Windows
141
+ app in front leaves X with no focused window, so click the emulator once when it opens. Tell
142
+ anyone at the machine before a run, and that a long route (Paper Mario's opening is several
143
+ minutes of text) needs them to leave the keyboard alone throughout: sending a message to an agent
144
+ puts their terminal in front and stalls the run.
145
+
87
146
  1. Build the plugin: `yarn check`.
88
147
  2. Start a local GameSlate daemon with your build:
89
148
  `GAMESLATE_PLUGINS_DIR=$PWD/dist node <gameslate>/dist/gameslate.mjs`.
90
149
  3. `yarn dlx -p @gameslate/sdk gameslate-plugin verify verify/<moment>.json`
91
150
 
92
- It starts RetroArch on the state, waits `settleMs`, then reads the daemon's next state for the
93
- game. It compares that state with `expect` and the emulator's reads with `memory`, takes a game
94
- screenshot (RetroArch's `SCREENSHOT`, into its screenshot directory), and screenshots the
95
- GameSlate page if Playwright is installed. Then it stops RetroArch. It exits 0 only when
96
- everything matched.
151
+ It starts the emulator (`emulator.command`, with `${NAME}` taken from the environment, so specs
152
+ hold no local paths), runs the `steps` through `gameslate drive`, waits `settleMs`, then reads the
153
+ daemon's next state for the game. It compares that state with `expect` (and, with RetroArch, the
154
+ emulator's own reads with `memory`), saves the frames the steps asked for, and screenshots the
155
+ GameSlate page if Playwright is installed. Then it stops the emulator. It exits 0 only when
156
+ everything matched. Run it twice: a route that passes once can depend on what the last run saved.
97
157
 
98
- ## 5. Look at the screenshots
158
+ ## 5. Look at the screenshots, and every tab
99
159
 
100
160
  The JSON checks what you predicted. The screenshots catch what you didn't: a pin in the wrong
101
161
  room, a counter shown under the wrong label, a menu reported as gameplay. Open both and compare
102
162
  them with the game's screen. Write down anything odd as a finding, even if the JSON passed.
103
163
 
164
+ At the moment, `verify` also screenshots the web app's tabs when the spec has `ui`: a URL with
165
+ its pairing token (`"ui": "http://localhost:4310/#token=${GAMESLATE_TOKEN}"` opens Map,
166
+ Inventory, Missions and Ref in turn) or `{ "url": …, "tabs": ["Inventory"] }`. Look at each: the
167
+ counters, the item lit in a grid, the mission list, the map's arrow against the game's minimap.
168
+ A local daemon's token is in its config:
169
+ `export GAMESLATE_TOKEN=$(node -p "require('$HOME/.config/gameslate/config.json').pairingToken")`
170
+ (don't paste it anywhere else). To see extracted maps, run the daemon with `GAMESLATE_LOCAL_ASSETS_DIR` (and
171
+ `GAMESLATE_REGISTRY_DIR` for a registry entry not deployed yet).
172
+ "Couldn't load this game's map data from the registry" means the game has no registry entry yet.
173
+
174
+ For values the route doesn't show, drive to them: Luigi Raceway's first row of item boxes is on
175
+ the start straight, so holding A long enough fetches an item to check the held-item read.
176
+
104
177
  ## 6. Record the result
105
178
 
106
179
  - In the README, list each verified build id with the date, the moments, and the emulator.
@@ -2,3 +2,8 @@ node_modules/
2
2
  dist/
3
3
  .env
4
4
  .env.*
5
+ # Yarn's generated install files (Plug'n'Play)
6
+ .pnp.*
7
+ .yarn/install-state.gz
8
+ # frames from gameslate-plugin verify: game-derived, keep them local
9
+ verify/*.png