@gameslate/sdk 0.3.23 → 0.3.25

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.
package/README.md CHANGED
@@ -66,6 +66,21 @@ no file system, no network. Read the game through `GameMemory`, the player's fil
66
66
  `InputFile`, and bytes with `Bytes`. Return data (states, drawings, pixels, meshes, notes); the core
67
67
  validates it and writes every file.
68
68
 
69
+ The sandbox refuses a call of more than 65535 arguments, where Node (and so vitest) takes far more:
70
+ `Math.min(...xs)`, `out.push(...items)` or `String.fromCharCode(...bytes)` over a map's worth of
71
+ data passes the tests and fails in the core. So `gameslate-plugin build` refuses a spread argument,
72
+ and `x.apply(t, list)` (also `x['apply']`, `apply.call`), `Reflect.apply(fn, t, list)` and
73
+ `Reflect.construct(C, list)` with a list that isn't an array literal, in the plugin's own code,
74
+ naming the file and line; a file it can't parse fails the build too. Fold and append by loop with
75
+ `extent(values, what)` (`{ min, max }`; throws on no values or a non-finite one) and
76
+ `append(into, items)` from `@gameslate/sdk`. A spread whose length the code fixes (four header
77
+ bytes, a triangle's corners) stays with `/* spread-ok: <why> */` on the line directly above its
78
+ statement (a function, class, `export default` or class property counts as one). The marker covers
79
+ the calls that start on that statement's first line, including those of a statement nested there
80
+ (`for (…) f(...p)`), and nothing on later lines: not a loop body, not a multi-line arrow's body. A
81
+ marker needs a reason and must mark something. Dependencies under `node_modules` aren't checked
82
+ (they can't be marked).
83
+
69
84
  A file the asset code needs from the web (a port's source at a pinned commit) is a download in the
70
85
  game's manifest entry: `downloads: [{ id, url, sha256 }]`, an exact https URL. The core fetches it
71
86
  when a build for that game starts, checks the hash, and hands it to `listAssets` / `buildAsset` as
@@ -75,23 +90,32 @@ the input `downloads/<id>`; the player sees it among the plugin's permissions.
75
90
 
76
91
  `0.3.x` speaks plugin contract (`sdkApi`) 3: new 0.3 versions add tools, never change the contract. The core refuses a plugin built for another contract.
77
92
 
78
- - **0.3.22** (not yet published): plugins may bundle WebAssembly. `gameslate-plugin build`
93
+ - **0.3.25**: `extent` and `append` fold and append by loop; `gameslate-plugin build` refuses a
94
+ call whose argument count is an array's length (a spread argument, `.apply`, `Reflect.apply`,
95
+ `Reflect.construct`) unless a `/* spread-ok: <why> */` marker sits directly above its
96
+ statement: the sandbox refuses more than 65535 arguments. The sdk now depends on `typescript` (the check
97
+ parses the plugin's source).
98
+ - **0.3.24**: `gameslate-plugin addresses` takes `sourceTypes` (`[{ file, types }]`): types a
99
+ decomp declares only in a `.c` file, lifted into the probe at probe time so their `offsetof`
100
+ and `sizeof` can be checked. A declaration inside an `#if` region, or holding a preprocessor
101
+ line, is refused.
102
+ - **0.3.22**: plugins may bundle WebAssembly. `gameslate-plugin build`
79
103
  copies `wasm/*.wasm` into the build and pins each in the manifest's `wasm`; code calls them with
80
104
  `wasmModule('<file>.wasm')` (`call`, `read`, `write`, `memoryBytes`). A module may import only
81
105
  `env.memory` and, in asset code, `gameslate.input_read`; the core caps its memory and stops a
82
106
  call at the time budget. `InputFile.handle` names an input to `input_read`. The build skill's
83
107
  "WebAssembly for hot loops" has the toolchain flags.
84
- - **0.3.19** (not yet published): no plugin code runs outside the sandbox.
108
+ - **0.3.19**: no plugin code runs outside the sandbox.
85
109
  - `extract` (`afterAssets`, `pythonExtract`) is gone from the contract: the manifest schema is
86
110
  strict and refuses it, and `gameslate-plugin build` refuses an `extract.ts`;
87
111
  - games declare `downloads: [{ id, url, sha256 }]`, fetched by the core and read as the input
88
112
  `downloads/<id>`;
89
113
  - a `notes` asset output (`{ kind: 'notes', id, json }`, the text of one JSON object), written as
90
114
  `notes/<id>.json` for a pack's `localSource`.
91
- - **Next** (not yet published): `gameslate-plugin addresses` takes `statics`, file-static
92
- variables placed at their object's section base in the ld map plus the offset their accessor
93
- shows (IDO keeps statics out of the map), each with its `evidence`.
94
- - **0.3.9** (not yet published): `gameslate-plugin addresses` takes `expectSizes` and fails
115
+ - **Earlier 0.3** (version not recorded): `gameslate-plugin addresses` takes `statics`,
116
+ file-static variables placed at their object's section base in the ld map plus the offset
117
+ their accessor shows (IDO keeps statics out of the map), each with its `evidence`.
118
+ - **0.3.9**: `gameslate-plugin addresses` takes `expectSizes` and fails
95
119
  when the probe disagrees with a size the decomp states. `verify.json`'s `expect` also checks the inventory (`has`,
96
120
  `lacks`, `exactly`), the equipped item (`null` for nothing) and flags; a flag the state doesn't
97
121
  report is a mismatch, not false.
@@ -121,27 +121,32 @@ if (command === 'build' && dir && values.out) {
121
121
  const table = buildAddressTable(spec, {
122
122
  read: file => fs.readFileSync(path.join(decomp, file), 'utf8'),
123
123
  compile: source => {
124
+ /* the probe holds decomp text (sourceTypes): it never outlives the compile */
124
125
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gs-probe-'));
125
- const probe = path.join(dir, 'probe.c');
126
- fs.writeFileSync(probe, source);
127
- const stubs = path.join(dir, 'stubs');
128
- for (const h of spec.stubHeaders) {
129
- fs.mkdirSync(path.dirname(path.join(stubs, h)), { recursive: true });
130
- fs.writeFileSync(
131
- path.join(stubs, h),
132
- '/* stub: generated by the decomp build */\n',
133
- );
126
+ try {
127
+ const probe = path.join(dir, 'probe.c');
128
+ fs.writeFileSync(probe, source);
129
+ const stubs = path.join(dir, 'stubs');
130
+ for (const h of spec.stubHeaders) {
131
+ fs.mkdirSync(path.dirname(path.join(stubs, h)), { recursive: true });
132
+ fs.writeFileSync(
133
+ path.join(stubs, h),
134
+ '/* stub: generated by the decomp build */\n',
135
+ );
136
+ }
137
+ /* after the decomp's own include paths: a real header wins over a stub */
138
+ const args = [
139
+ ...spec.clang.args,
140
+ ...(spec.stubHeaders.length ? ['-idirafter', stubs] : []),
141
+ ];
142
+ return execFileSync(spec.clang.binary, [...args, '-S', '-o', '-', probe], {
143
+ cwd: decomp,
144
+ encoding: 'utf8',
145
+ maxBuffer: 64 * 1024 * 1024,
146
+ });
147
+ } finally {
148
+ fs.rmSync(dir, { recursive: true, force: true });
134
149
  }
135
- /* after the decomp's own include paths: a real header wins over a stub */
136
- const args = [
137
- ...spec.clang.args,
138
- ...(spec.stubHeaders.length ? ['-idirafter', stubs] : []),
139
- ];
140
- return execFileSync(spec.clang.binary, [...args, '-S', '-o', '-', probe], {
141
- cwd: decomp,
142
- encoding: 'utf8',
143
- maxBuffer: 64 * 1024 * 1024,
144
- });
145
150
  },
146
151
  });
147
152
  const commit = (() => {
@@ -158,6 +163,7 @@ if (command === 'build' && dir && values.out) {
158
163
  `gameslate-plugin addresses ${path.basename(specFile)}:`,
159
164
  `- symbols from ${spec.symbolFiles.join(', ')}${spec.subtract ? `, less 0x${spec.subtract.toString(16)} (another revision)` : ''};`,
160
165
  `- offsets, sizes and constants from a probe of ${spec.includes.join(', ') || 'no headers'},`,
166
+ ...spec.sourceTypes.map(s => ` with ${s.types.join(', ')} lifted from ${s.file},`),
161
167
  ` compiled by ${spec.clang.binary} ${spec.clang.args.filter(a => !a.startsWith('-I')).join(' ')}.`,
162
168
  ].join('\n');
163
169
  const text = addressModule(table, provenance);
@@ -4,6 +4,7 @@ import { createHash } from 'node:crypto';
4
4
  import fs from 'node:fs';
5
5
  import { createRequire } from 'node:module';
6
6
  import path from 'node:path';
7
+ import { checkSpreadLimit } from './spread-limit.mjs';
7
8
  import { renderLicences } from './third-party-licences.mjs';
8
9
  import { zipFolder } from './zip.mjs';
9
10
 
@@ -24,7 +25,9 @@ export { zipEntries } from './zip.mjs';
24
25
  * registry/ the plugin's registry data, copied as it is (the core checks it on load:
25
26
  * src/host/plugin-registry.ts; `gameslate-plugin validate` runs the same check)
26
27
  * Sandbox scripts are built for a neutral platform, so a Node API in them fails the build. No plugin
27
- * code runs outside the sandbox: an `extract.ts` (the old unsandboxed hooks) fails the build.
28
+ * code runs outside the sandbox: an `extract.ts` (the old unsandboxed hooks) fails the build. A
29
+ * call whose argument count is an array's length (`f(...xs)`, `.apply`) fails it too, unless its
30
+ * site is marked as staying small: the sandbox refuses more than 65535 (spread-limit.mjs).
28
31
  *
29
32
  * With `release` (a folder), it also writes what a release uploads, side by side:
30
33
  * <id>-<version>.zip the built folder, under <id>/
@@ -68,11 +71,22 @@ const nodeResolution = {
68
71
 
69
72
  const hashOf = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
70
73
 
71
- /* a sandbox script: `entry`'s default export handed to the sdk's `expose` function */
74
+ const SANDBOX_ENTRY = 'sandbox-entry.ts';
75
+
72
76
  /* the absolute paths of the modules an esbuild result bundled */
73
77
  const inputsOf = (srcDir, result) =>
74
78
  Object.keys(result.metafile.inputs).map(input => path.resolve(srcDir, input));
75
79
 
80
+ /* the absolute paths of the modules that put code into the bundle (an output's inputs: a module
81
+ * only imported for what tree shaking dropped isn't one), without the generated entry */
82
+ const contributorsOf = (srcDir, result) =>
83
+ Object.values(result.metafile.outputs).flatMap(output =>
84
+ Object.keys(output.inputs)
85
+ .filter(input => input !== SANDBOX_ENTRY)
86
+ .map(input => path.resolve(srcDir, input)),
87
+ );
88
+
89
+ /* a sandbox script: `entry`'s default export handed to the sdk's `expose` function */
76
90
  async function buildSandboxed({ srcDir, entry, expose, outfile, alias }) {
77
91
  const result = await esbuild.build({
78
92
  absWorkingDir: srcDir,
@@ -83,7 +97,7 @@ async function buildSandboxed({ srcDir, entry, expose, outfile, alias }) {
83
97
  `${expose}(plugin);`,
84
98
  ].join('\n'),
85
99
  resolveDir: srcDir,
86
- sourcefile: 'sandbox-entry.ts',
100
+ sourcefile: SANDBOX_ENTRY,
87
101
  loader: 'ts',
88
102
  },
89
103
  outfile,
@@ -98,6 +112,7 @@ async function buildSandboxed({ srcDir, entry, expose, outfile, alias }) {
98
112
  metafile: true,
99
113
  logLevel: 'warning',
100
114
  });
115
+ checkSpreadLimit(contributorsOf(srcDir, result), path.dirname(srcDir));
101
116
  return inputsOf(srcDir, result);
102
117
  }
103
118
 
@@ -0,0 +1,6 @@
1
+ /** One source file's problems, each `<file>:<line>: <what>` (see spread-limit.mjs). */
2
+ export function spreadProblems(file: string, text: string): string[];
3
+
4
+ /** Throws, listing every problem, when the plugin code in `modules` calls with an unbounded
5
+ * argument count; files are named relative to `baseDir`. */
6
+ export function checkSpreadLimit(modules: readonly string[], baseDir: string): void;
@@ -0,0 +1,202 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import ts from 'typescript';
4
+
5
+ /*
6
+ * The core's QuickJS sandbox refuses a call of more than 65535 arguments; Node takes far more, so
7
+ * `Math.min(...xs)` over a big map passes vitest and fails in the sandbox (DK64's Frantic Factory,
8
+ * 2026-12-06). The build refuses every call whose argument count is the length of an array:
9
+ * a spread argument, and `.apply` (also as `['apply']` and `apply.call`), `Reflect.apply` and
10
+ * `Reflect.construct` with a list that isn't an array literal.
11
+ *
12
+ * A site whose length the code fixes (a triangle's corners) stays only with a block comment
13
+ * `spread-ok: <why>` on the line directly above its statement. A statement here is also a function,
14
+ * class, `export default` or class property declaration. The marker covers the calls that start on
15
+ * that statement's first line, its own and those of statements nested on the same line
16
+ * (`for (…) f(...xs)`), and nothing on later lines: not a loop body, not an arrow's body. A marker
17
+ * needs a reason, and one that marks nothing is refused.
18
+ *
19
+ * The plugin's own source is read, not the bundle: esbuild drops plain comments, so the marker
20
+ * wouldn't reach the bundle. Only the modules that put code into the bundle are read (esbuild's
21
+ * metafile), and not those under node_modules: a dependency can't be marked.
22
+ */
23
+
24
+ const MARKER = /^\/\*\s*spread-ok\b:?\s*(.*?)\s*\*\/$/s;
25
+ const LIMIT =
26
+ "the sandbox refuses a call of more than 65535 arguments: fold or append by loop (extent, append from '@gameslate/sdk'), or mark a statement whose spread stays small with /* spread-ok: <why> */ on the line directly above";
27
+
28
+ const lineAt = (source, pos) => source.getLineAndCharacterOfPosition(pos).line + 1;
29
+ const lineOf = (source, node) => lineAt(source, node.getStart(source));
30
+
31
+ /* what a marker can lead */
32
+ const isStatement = node =>
33
+ (node.kind >= ts.SyntaxKind.FirstStatement && node.kind <= ts.SyntaxKind.LastStatement) ||
34
+ ts.isFunctionDeclaration(node) ||
35
+ ts.isClassDeclaration(node) ||
36
+ ts.isExportAssignment(node) ||
37
+ ts.isPropertyDeclaration(node);
38
+
39
+ /* the statement `node` is in, and any enclosing one that starts on the same line */
40
+ function statementsOf(source, node) {
41
+ const found = [];
42
+ for (let n = node.parent; n !== undefined && !ts.isSourceFile(n); n = n.parent) {
43
+ if (!isStatement(n)) continue;
44
+ const first = found[0];
45
+ if (first !== undefined && lineOf(source, n) !== lineOf(source, first)) break;
46
+ found.push(n);
47
+ }
48
+ return found;
49
+ }
50
+
51
+ /* a list whose length is fixed in the source: an array literal without spreads */
52
+ const isFixedList = node =>
53
+ ts.isArrayLiteralExpression(node) && !node.elements.some(e => ts.isSpreadElement(e));
54
+
55
+ /* `object.name` or `object['name']`, parentheses skipped: `{ object, name }`, or undefined */
56
+ function memberOf(expression) {
57
+ const e = ts.skipParentheses(expression);
58
+ if (ts.isPropertyAccessExpression(e)) return { object: e.expression, name: e.name.text };
59
+ if (ts.isElementAccessExpression(e) && ts.isStringLiteralLike(e.argumentExpression))
60
+ return { object: e.expression, name: e.argumentExpression.text };
61
+ return undefined;
62
+ }
63
+
64
+ /* the list `call` spreads into a call through apply or Reflect: `{ rule, list }`, or undefined */
65
+ function appliedList(call) {
66
+ const member = memberOf(call.expression);
67
+ if (!member) return undefined;
68
+ const object = ts.skipParentheses(member.object);
69
+ const onReflect = ts.isIdentifier(object) && object.text === 'Reflect';
70
+ const args = call.arguments;
71
+ if (onReflect && member.name === 'apply') return { rule: 'Reflect.apply', list: args[2] };
72
+ if (onReflect && member.name === 'construct')
73
+ return { rule: 'Reflect.construct', list: args[1] };
74
+ if (member.name === 'apply') return { rule: '.apply with an argument list', list: args[1] };
75
+ if (member.name === 'call' && memberOf(object)?.name === 'apply')
76
+ return { rule: '.apply.call with an argument list', list: args[2] };
77
+ return undefined;
78
+ }
79
+
80
+ /** Sites in `source` that pass an array's length of arguments: `{ node, call, rule }`. */
81
+ function unboundedSites(source) {
82
+ const found = [];
83
+ const visit = node => {
84
+ if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
85
+ for (const arg of node.arguments ?? [])
86
+ if (ts.isSpreadElement(arg))
87
+ found.push({ node: arg, call: node, rule: 'a spread argument' });
88
+ }
89
+ if (ts.isCallExpression(node)) {
90
+ const applied = appliedList(node);
91
+ if (applied?.list && !isFixedList(applied.list))
92
+ found.push({ node: applied.list, call: node, rule: applied.rule });
93
+ }
94
+ ts.forEachChild(node, visit);
95
+ };
96
+ visit(source);
97
+ return found;
98
+ }
99
+
100
+ /* the spread-ok marker on the line directly above one of the statements whose first line `site`'s
101
+ * call starts on: `{ pos, reason }`, or undefined */
102
+ function markerOf(source, site) {
103
+ const statements = statementsOf(source, site.node);
104
+ const first = statements[0];
105
+ if (first === undefined || lineOf(source, site.call) !== lineOf(source, first))
106
+ return undefined;
107
+ for (const statement of statements) {
108
+ const ranges = ts.getLeadingCommentRanges(source.text, statement.getFullStart()) ?? [];
109
+ for (const range of ranges) {
110
+ if (lineAt(source, range.end) !== lineOf(source, statement) - 1) continue;
111
+ const match = MARKER.exec(source.text.slice(range.pos, range.end));
112
+ if (match) return { pos: range.pos, reason: match[1] ?? '' };
113
+ }
114
+ }
115
+ return undefined;
116
+ }
117
+
118
+ /* the positions of every spread-ok comment in `source`; every token is visited (getChildren,
119
+ * not forEachChild), since a comment after `(` is trivia of the parenthesis, not of a node */
120
+ function markerPositions(source) {
121
+ const found = new Set();
122
+ const collect = ranges => {
123
+ for (const range of ranges ?? [])
124
+ if (MARKER.test(source.text.slice(range.pos, range.end))) found.add(range.pos);
125
+ };
126
+ const visit = node => {
127
+ collect(ts.getLeadingCommentRanges(source.text, node.pos));
128
+ collect(ts.getTrailingCommentRanges(source.text, node.end));
129
+ for (const child of node.getChildren(source)) visit(child);
130
+ };
131
+ visit(source);
132
+ return found;
133
+ }
134
+
135
+ function scriptKindOf(file) {
136
+ if (/\.tsx$/.test(file)) return ts.ScriptKind.TSX;
137
+ if (/\.[cm]?ts$/.test(file)) return ts.ScriptKind.TS;
138
+ if (/\.jsx$/.test(file)) return ts.ScriptKind.JSX;
139
+ if (/\.[cm]?js$/.test(file)) return ts.ScriptKind.JS;
140
+ throw new Error(`${file}: not a script the spread check can read`);
141
+ }
142
+
143
+ /**
144
+ * The problems in one source file, each `<file>:<line>: <what>`: unmarked sites, markers without
145
+ * a reason and markers that mark nothing. `file` names it in the messages. Throws on a file that
146
+ * doesn't parse: a misparse can hide a spread.
147
+ */
148
+ export function spreadProblems(file, text) {
149
+ const source = ts.createSourceFile(
150
+ file,
151
+ text,
152
+ ts.ScriptTarget.Latest,
153
+ true,
154
+ scriptKindOf(file),
155
+ );
156
+ const [syntax] = source.parseDiagnostics;
157
+ if (syntax)
158
+ throw new Error(
159
+ `${file}:${lineAt(source, syntax.start)}: the spread check can't parse it: ${ts.flattenDiagnosticMessageText(syntax.messageText, ' ')}`,
160
+ );
161
+ const problems = [];
162
+ const used = new Set();
163
+ for (const site of unboundedSites(source)) {
164
+ const marker = markerOf(source, site);
165
+ if (!marker) {
166
+ problems.push({ line: lineOf(source, site.node), text: `${site.rule}: ${LIMIT}` });
167
+ continue;
168
+ }
169
+ if (used.has(marker.pos)) continue;
170
+ used.add(marker.pos);
171
+ if (!marker.reason)
172
+ problems.push({
173
+ line: lineAt(source, marker.pos),
174
+ text: 'a spread-ok marker needs a reason: /* spread-ok: <why it stays small> */',
175
+ });
176
+ }
177
+ for (const pos of markerPositions(source))
178
+ if (!used.has(pos))
179
+ problems.push({
180
+ line: lineAt(source, pos),
181
+ text: 'a spread-ok marker that marks no spread, .apply or Reflect call: it goes on the line directly above the statement',
182
+ });
183
+ return problems.sort((a, b) => a.line - b.line).map(p => `${file}:${p.line}: ${p.text}`);
184
+ }
185
+
186
+ /* modules read as code, not data an esbuild loader bundles (JSON, text) */
187
+ const CODE = /\.([cm]?[jt]sx?)$/;
188
+
189
+ /**
190
+ * Throws, listing every problem, when the plugin code in `modules` (absolute paths) calls with an
191
+ * unbounded argument count. Files are named relative to `baseDir`.
192
+ */
193
+ export function checkSpreadLimit(modules, baseDir) {
194
+ const own = modules.filter(m => CODE.test(m) && !m.split(path.sep).includes('node_modules'));
195
+ const problems = own.flatMap(m =>
196
+ spreadProblems(path.relative(baseDir, m), fs.readFileSync(m, 'utf8')),
197
+ );
198
+ if (problems.length)
199
+ throw new Error(
200
+ `plugin code calls with an unbounded argument count:\n${problems.map(p => ` ${p}`).join('\n')}`,
201
+ );
202
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The least and greatest of `values`. Throws on none, or on one that isn't a finite number: either
3
+ * would frame or band a drawing on NaN or infinite pixels. `what` names the values in the error.
4
+ */
5
+ export declare function extent(values: Iterable<number>, what: string): {
6
+ min: number;
7
+ max: number;
8
+ };
9
+ /** Appends `items` to `into`, in order. */
10
+ export declare function append<T>(into: T[], items: Iterable<T>): void;
package/lib/arrays.js ADDED
@@ -0,0 +1,31 @@
1
+ /*
2
+ * Folds and appends by loop, never by spreading an array into a call: the core's QuickJS sandbox
3
+ * refuses a call of more than 65535 arguments where Node takes far more, so `Math.min(...xs)` over
4
+ * a big map passes vitest and fails in the sandbox (`gameslate-plugin build` refuses the spread).
5
+ */
6
+ /**
7
+ * The least and greatest of `values`. Throws on none, or on one that isn't a finite number: either
8
+ * would frame or band a drawing on NaN or infinite pixels. `what` names the values in the error.
9
+ */
10
+ export function extent(values, what) {
11
+ let min = Infinity;
12
+ let max = -Infinity;
13
+ let seen = false;
14
+ for (const v of values) {
15
+ if (!Number.isFinite(v))
16
+ throw new Error(`${what} include ${v}`);
17
+ seen = true;
18
+ if (v < min)
19
+ min = v;
20
+ if (v > max)
21
+ max = v;
22
+ }
23
+ if (!seen)
24
+ throw new Error(`no ${what}`);
25
+ return { min, max };
26
+ }
27
+ /** Appends `items` to `into`, in order. */
28
+ export function append(into, items) {
29
+ for (const item of items)
30
+ into.push(item);
31
+ }
@@ -9,6 +9,20 @@ export declare const AddressSpecSchema: z.ZodObject<{
9
9
  subtract: z.ZodDefault<z.ZodUnion<[z.ZodNumber, z.ZodEffects<z.ZodString, number, string>]>>;
10
10
  /** headers the probe includes, in order */
11
11
  includes: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
12
+ /** types a `.c` file declares for itself, lifted into the probe after the includes (in
13
+ * order) at probe time: the decomp's text never enters the spec or the repo */
14
+ sourceTypes: z.ZodDefault<z.ZodArray<z.ZodObject<{
15
+ /** relative to the decomp */
16
+ file: z.ZodEffects<z.ZodString, string, string>;
17
+ /** a typedef's `Name`, or `struct|union|enum Tag` */
18
+ types: z.ZodArray<z.ZodString, "many">;
19
+ }, "strip", z.ZodTypeAny, {
20
+ file: string;
21
+ types: string[];
22
+ }, {
23
+ file: string;
24
+ types: string[];
25
+ }>, "many">>;
12
26
  /** headers the decomp generates at build time, given as empty files so an unbuilt checkout
13
27
  * compiles; a layout that really needs one still fails to compile, loudly */
14
28
  stubHeaders: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
@@ -60,6 +74,10 @@ export declare const AddressSpecSchema: z.ZodObject<{
60
74
  decomp: string;
61
75
  symbolFiles: string[];
62
76
  subtract: number;
77
+ sourceTypes: {
78
+ file: string;
79
+ types: string[];
80
+ }[];
63
81
  stubHeaders: string[];
64
82
  clang: {
65
83
  binary: string;
@@ -85,6 +103,10 @@ export declare const AddressSpecSchema: z.ZodObject<{
85
103
  };
86
104
  includes?: string[] | undefined;
87
105
  subtract?: string | number | undefined;
106
+ sourceTypes?: {
107
+ file: string;
108
+ types: string[];
109
+ }[] | undefined;
88
110
  stubHeaders?: string[] | undefined;
89
111
  symbols?: string[] | undefined;
90
112
  statics?: Record<string, {
@@ -136,9 +158,15 @@ export declare function probeEntries(spec: Pick<AddressSpec, 'offsets' | 'sizes'
136
158
  })[];
137
159
  export declare function probeSource(includes: readonly string[], entries: ReadonlyArray<{
138
160
  expr: string;
139
- }>): string;
161
+ }>, declarations?: readonly string[]): string;
140
162
  /** probe_N's value from clang's assembly (`probe_3:` then `.4byte 612` or `.word 612`). */
141
163
  export declare function parseProbeAssembly(asm: string, count: number): number[];
164
+ /** A type's declaration as `file` writes it: `typedef struct|union|enum [Tag] { … } Name;` for
165
+ * `Name`, or `struct|union|enum Tag { … };` (or a typedef with that tag) for `struct Tag`, at
166
+ * file scope. Throws naming the file and the type unless the file declares it exactly once, or
167
+ * when its text depends on the preprocessor (it sits in an `#if` region, or holds a directive):
168
+ * the probe's macros aren't the file's, so the lifted layout could silently differ. */
169
+ export declare function liftType(text: string, file: string, type: string): string;
142
170
  export interface AddressTable {
143
171
  symbols: Record<string, number>;
144
172
  offsets: Record<string, number>;
@@ -4,8 +4,9 @@ import { z } from 'zod';
4
4
  * plugin's addresses have a source instead of being typed in. Globals come from the build's
5
5
  * symbol map (a GNU ld map, or splat's `symbol_addrs` files), less a constant when the decomp
6
6
  * builds another revision than the player's ROM. Struct offsets, sizes and constants come from a
7
- * probe compiled with clang against the decomp's own headers for the console's ABI: no code runs,
8
- * the compiler folds each value into the assembly. The effects (files, clang) are parameters.
7
+ * probe compiled with clang against the decomp's own headers (and typedefs lifted from its `.c`
8
+ * files) for the console's ABI: no code runs, the compiler folds each value into the assembly.
9
+ * The effects (files, clang) are parameters.
9
10
  */
10
11
  const Hex = z.union([
11
12
  z.number().int(),
@@ -24,6 +25,23 @@ export const AddressSpecSchema = z.object({
24
25
  subtract: Hex.default(0),
25
26
  /** headers the probe includes, in order */
26
27
  includes: z.array(z.string()).default([]),
28
+ /** types a `.c` file declares for itself, lifted into the probe after the includes (in
29
+ * order) at probe time: the decomp's text never enters the spec or the repo */
30
+ sourceTypes: z
31
+ .array(z.object({
32
+ /** relative to the decomp */
33
+ file: z
34
+ .string()
35
+ .regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*\.c$/, 'a .c file relative to the decomp')
36
+ .refine(f => !f.split('/').includes('..'), 'a path inside the decomp'),
37
+ /** a typedef's `Name`, or `struct|union|enum Tag` */
38
+ types: z
39
+ .array(z
40
+ .string()
41
+ .regex(/^(?:(?:struct|union|enum) )?[A-Za-z_][A-Za-z0-9_]*$/, 'a typedef name or struct|union|enum Tag'))
42
+ .min(1),
43
+ }))
44
+ .default([]),
27
45
  /** headers the decomp generates at build time, given as empty files so an unbuilt checkout
28
46
  * compiles; a layout that really needs one still fails to compile, loudly */
29
47
  stubHeaders: z.array(z.string().regex(/^[A-Za-z0-9_./-]+\.h$/)).default([]),
@@ -142,10 +160,11 @@ export function probeEntries(spec) {
142
160
  })),
143
161
  ];
144
162
  }
145
- export function probeSource(includes, entries) {
163
+ export function probeSource(includes, entries, declarations = []) {
146
164
  return [
147
165
  '/* generated by gameslate-plugin addresses: each value folds into the assembly */',
148
166
  ...includes.map(h => `#include ${h.startsWith('<') ? h : `"${h}"`}`),
167
+ ...declarations,
149
168
  ...entries.map((e, i) => `const long probe_${i} = (long)(${e.expr});`),
150
169
  '',
151
170
  ].join('\n');
@@ -168,6 +187,93 @@ export function parseProbeAssembly(asm, count) {
168
187
  return v;
169
188
  });
170
189
  }
190
+ /** C source with its comments and string and character literals blanked to spaces (newlines
191
+ * kept), so a brace inside one doesn't count and every position still matches the original. */
192
+ function blankCommentsAndLiterals(text) {
193
+ const blank = (s) => s.replace(/[^\n]/g, ' ');
194
+ return text.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*|"(?:\\[\s\S]|[^"\\\n])*"|'(?:\\[\s\S]|[^'\\\n])*'/g, blank);
195
+ }
196
+ /* `[typedef] struct|union|enum [Tag] {`; a function or an initialiser matches too, but never
197
+ * ends in a declarator its type's name can equal */
198
+ const TYPE_OPEN = /\b(typedef\s+)?(struct|union|enum)\b([^;{}]*)\{/g;
199
+ const DECLARATOR_END = /^\s*([A-Za-z_][A-Za-z0-9_]*)?\s*;/;
200
+ const CONDITIONAL = /^[ \t]*#[ \t]*(if|ifdef|ifndef|endif)\b/gm;
201
+ const DIRECTIVE_LINE = /^[ \t]*#/m;
202
+ /** Where the brace at `open` closes in `code`, if it does. */
203
+ function closingBrace(code, open) {
204
+ let depth = 0;
205
+ for (let at = open; at < code.length; at++) {
206
+ if (code[at] === '{')
207
+ depth++;
208
+ else if (code[at] === '}' && --depth === 0)
209
+ return at;
210
+ }
211
+ return undefined;
212
+ }
213
+ /** Each `TYPE_OPEN` at file scope (outside every brace), with how many `#if` regions it is in. */
214
+ function fileScopeOpens(code) {
215
+ const directives = [...code.matchAll(CONDITIONAL)].map(d => ({
216
+ at: d.index,
217
+ step: d[1] === 'endif' ? -1 : 1,
218
+ }));
219
+ const out = [];
220
+ let depth = 0;
221
+ let at = 0;
222
+ for (const open of code.matchAll(TYPE_OPEN)) {
223
+ for (; at < open.index; at++) {
224
+ if (code[at] === '{')
225
+ depth++;
226
+ else if (code[at] === '}')
227
+ depth--;
228
+ }
229
+ if (depth !== 0)
230
+ continue;
231
+ const conditionals = directives
232
+ .filter(d => d.at < open.index)
233
+ .reduce((n, d) => n + d.step, 0);
234
+ out.push({ open, conditionals });
235
+ }
236
+ return out;
237
+ }
238
+ /** A type's declaration as `file` writes it: `typedef struct|union|enum [Tag] { … } Name;` for
239
+ * `Name`, or `struct|union|enum Tag { … };` (or a typedef with that tag) for `struct Tag`, at
240
+ * file scope. Throws naming the file and the type unless the file declares it exactly once, or
241
+ * when its text depends on the preprocessor (it sits in an `#if` region, or holds a directive):
242
+ * the probe's macros aren't the file's, so the lifted layout could silently differ. */
243
+ export function liftType(text, file, type) {
244
+ const code = blankCommentsAndLiterals(text);
245
+ const found = [];
246
+ for (const { open, conditionals } of fileScopeOpens(code)) {
247
+ const tag = open[3]?.trim();
248
+ const tagName = tag ? `${open[2]} ${tag}` : undefined;
249
+ const close = closingBrace(code, open.index + open[0].length - 1);
250
+ /* an open that never closes and isn't this type's (two `#ifdef` function headers sharing
251
+ * one body) is skipped */
252
+ if (close === undefined) {
253
+ if (tagName === type)
254
+ throw new Error(`${file}: ${type}'s braces never close`);
255
+ continue;
256
+ }
257
+ const end = DECLARATOR_END.exec(code.slice(close + 1));
258
+ /* a plain declaration must end at its brace: `struct S { … } var;` defines a variable */
259
+ if (!end || (!open[1] && end[1]))
260
+ continue;
261
+ if (end[1] !== type && tagName !== type)
262
+ continue;
263
+ if (conditionals > 0)
264
+ throw new Error(`${file}: ${type} is declared inside an #if region: not lifted`);
265
+ const declaration = text.slice(open.index, close + 1 + end[0].length);
266
+ if (DIRECTIVE_LINE.test(declaration))
267
+ throw new Error(`${file}: ${type}'s declaration holds a preprocessor line: not lifted`);
268
+ found.push(declaration);
269
+ }
270
+ const [declaration] = found;
271
+ if (!declaration)
272
+ throw new Error(`${file} declares no ${type} to lift ("typedef struct|union|enum { … } Name;" or "struct|union|enum Tag { … };" at file scope)`);
273
+ if (found.length > 1)
274
+ throw new Error(`${file} declares ${type} ${found.length} times`);
275
+ return declaration;
276
+ }
171
277
  /** Each file-static at its object's section base plus the accessor's offset, into `known`. */
172
278
  function placeStatics(spec, sections, known) {
173
279
  for (const [name, st] of Object.entries(spec.statics)) {
@@ -202,9 +308,16 @@ export function buildAddressTable(spec, effects) {
202
308
  const table = { symbols: {}, offsets: {}, sizes: {}, constants: {} };
203
309
  for (const s of [...spec.symbols, ...Object.keys(spec.statics)])
204
310
  table.symbols[s] = ((known.get(s) ?? 0) - spec.subtract) >>> 0;
311
+ /* `Tri` and `struct Tri` lift the same text: declare it once */
312
+ const declarations = [
313
+ ...new Set(spec.sourceTypes.flatMap(({ file, types }) => {
314
+ const text = effects.read(file);
315
+ return types.map(t => liftType(text, file, t));
316
+ })),
317
+ ];
205
318
  const entries = probeEntries(spec);
206
319
  if (entries.length) {
207
- const values = parseProbeAssembly(effects.compile(probeSource(spec.includes, entries)), entries.length);
320
+ const values = parseProbeAssembly(effects.compile(probeSource(spec.includes, entries, declarations)), entries.length);
208
321
  entries.forEach((e, i) => {
209
322
  table[e.kind][e.name] = values[i] ?? 0;
210
323
  });
package/lib/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export * from './pins.js';
8
8
  export * from './chips.js';
9
9
  export * from './pack.js';
10
10
  export * from './views.js';
11
+ export * from './arrays.js';
11
12
  export * from './bytes.js';
12
13
  export * from './navigation.js';
13
14
  export * from './plugin-manifest.js';
package/lib/index.js CHANGED
@@ -8,6 +8,7 @@ export * from './pins.js';
8
8
  export * from './chips.js';
9
9
  export * from './pack.js';
10
10
  export * from './views.js';
11
+ export * from './arrays.js';
11
12
  export * from './bytes.js';
12
13
  export * from './navigation.js';
13
14
  export * from './plugin-manifest.js';
@@ -7,8 +7,10 @@ export function wasmModule(file) {
7
7
  throw new Error('the core gave no WebAssembly capability');
8
8
  return bridge;
9
9
  };
10
+ /* spread-ok: a WebAssembly export's parameters, a handful of numbers */
11
+ const call = (fn, ...args) => host().call(file, fn, ...args);
10
12
  return {
11
- call: (fn, ...args) => host().call(file, fn, ...args),
13
+ call,
12
14
  read: (ptr, length) => new Uint8Array(host().read(file, ptr, length)),
13
15
  /* an exact-size copy, so only these bytes cross */
14
16
  write: (ptr, bytes) => host().write(file, ptr, bytes.slice().buffer),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gameslate/sdk",
3
- "version": "0.3.23",
3
+ "version": "0.3.25",
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",
@@ -76,6 +76,7 @@
76
76
  "@jitl/quickjs-wasmfile-release-sync": "0.31.0",
77
77
  "esbuild": "^0.24.0",
78
78
  "quickjs-emscripten-core": "0.31.0",
79
+ "typescript": "^5.7.2",
79
80
  "zod": "^3.24.1"
80
81
  },
81
82
  "gameslate": {
@@ -173,6 +173,25 @@ A decomp that generates headers at build time (Paper Mario's `item_enum.h`) need
173
173
  list them in `"stubHeaders"` and the probe gets empty ones (a layout that really needs one still
174
174
  fails to compile). Constants come back signed.
175
175
 
176
+ A struct the decomp declares only inside a `.c` file (Donkey Kong 64's `CollisionStaticTri` in
177
+ `src/global/6AD90_collision.c`) can't be included, and its layout must still come from `offsetof`,
178
+ not from typing it in. Name the file and the types instead:
179
+ `"sourceTypes": [{ "file": "src/global/6AD90_collision.c", "types": ["CollisionStaticTri"] }]`.
180
+ A type is a typedef's `Name` (`typedef struct|union|enum [Tag] { … } Name;`) or a tagged
181
+ `struct|union|enum Tag` (`enum SurfaceKind { … };`, whose values `constants` can then name). At
182
+ probe time the run lifts each declaration out of the file into the probe, after the `includes`
183
+ (which must declare what it uses, such as `s16`), in the order listed. The spec holds only names,
184
+ so no decomp code reaches the repo, whatever its licence. It fails naming the file and the type
185
+ when the file doesn't declare it exactly once at file scope, and when the preprocessor shapes it
186
+ (it sits in an `#if` region, or holds a directive): the probe's macros aren't the file's, so the
187
+ layout could change without a word. A macro the `.c` defines for itself (an array length) fails
188
+ the compile. Not lifted: several declarators or a pointer one (`} A, *APtr;`), an attribute after
189
+ the brace (a packed struct must never lose it), `typedef const struct`. A forward
190
+ `typedef struct Tag Name;` with a separate `struct Tag { … };` is lifted as `struct Tag`, and
191
+ `offsets` and `sizes` name it that way too (`struct Tag.field`). The probe's temp file holds the
192
+ lifted text and is removed after the compile; clang's errors echo it too, so don't quote them in
193
+ commits or issues.
194
+
176
195
  **Always list `"expectSizes"`** for the structs you read, from the decomp's `// size = 0x…`
177
196
  comments or a symbol's `size:` over its count: the run fails if the probe disagrees. And compile
178
197
  the probe in the C standard the game was built with (`-std=gnu89` for IDO and KMC GCC games):
@@ -735,6 +754,116 @@ the plugin repos) in the same change as the fix. The next game should not have t
735
754
  player in from above: check every exit lands over a drawn floor in plan, and most on the
736
755
  ground, not ±N units for all. The player's wall and ceiling queries pass through water, so
737
756
  draw only water faces that point up (BK, 2026-12-05).
757
+ - **Draw links the game makes, never links you guess.** Mario Party's first map joined board
758
+ chains to the nearest space within 500 units and drew the joins as paths; a fork could show a
759
+ road the board doesn't have, and a link it didn't find looked like a dead end. Read the joins
760
+ from the board code; where you can't, mark the loose end "not read" rather than drawing or
761
+ hiding it (fail-loud, MP1 review, 2026-12-05).
762
+ - **Reusing a sibling game's decoder: compare the routines instruction by instruction.** Walk
763
+ both ROMs' functions to `jr ra`; if only `lui`/`addiu` address halves and `jal` targets differ,
764
+ it's the same algorithm (decoding thousands of files only shows it doesn't crash). Move the
765
+ shared decoder out of the first game's folder so no pack imports another. A table only asm
766
+ names can be pinned by scanning the ROM for `jal <fn>` and the `addiu a1,zero,imm` beside it
767
+ (MP1, 2026-12-05).
768
+ - **Bound a map by every place the game can put a player**, not just what's drawn: invisible
769
+ event spots and the standoff of a waiting player (MP1's ±60, from a table in `.data`).
770
+ - **An asset-table entry of size 0 means "missing".** Its offset points at the next entry's
771
+ data, so following it reads another level (two of Conker's levels showed the same spawns).
772
+ Return null, with a regression test whose size-0 entry points at real data (Conker,
773
+ 2026-12-05).
774
+ - **Collision from display lists: port the game's walker exactly**, quirks included: Conker's
775
+ G_VTX fills slots from `first` up to `count`, not `first + count`; G_TRI1 slots are 7 bits,
776
+ G_TRI2/TRI4 5 bits. Prove each with a golden only the right width passes, and set the bits a
777
+ neighbouring field's wrong mask would pick up, or mask mutations survive. Check the game's
778
+ array sizes against the data (`verts[31]` against 32-vertex loads) and say which reading
779
+ you take.
780
+ - **Band a painter's-order drawing by height, not by colour runs.** A layer per run of one
781
+ colour made 324 layers on one Conker level and passed the 99-layer cap on DK64's Jungle
782
+ Japes; a fixed number of height bands, each drawn water, then ground, then hazard, don't
783
+ blow up.
784
+ - **A game's "no data" fallback is rarely a fact about the level.** Conker's spawn fallback
785
+ reads the first record of a block every level shares: refuse the level instead, and show by
786
+ census that no supported level hits it. Likewise check where water lives (props and zones,
787
+ not the mesh's materials) before claiming it's drawn, and when walls are resolved in
788
+ hand-written asm, say the wall threshold is a drawing choice.
789
+ - **Code that follows a decomp's routines step by step is derived from it**, even with no lines
790
+ copied: give each such file the `/*! Derived from … */` header so the notice ships in the
791
+ bundle. A notices test that checks wording must slice out that decomp's own section, or
792
+ another section's "Derived from it:" hides the mutation (Conker review, 2026-12-05).
793
+ - **`listAssets` stays cheap** by reading only the asset table, through word-aligned windows
794
+ converted per window to big-endian (z64/v64/n64), never the whole ROM.
795
+ - **A decomp's copy of a standard library is not the decomp's to license.** DK64's decomp
796
+ (CC0) reconstructs gzip 1.2.4 (GPL) for its boot loader; a header reader written from it
797
+ carried gzip's flag names and step order into MIT code. Read standard formats from their
798
+ RFC, reuse the repo's licensed inflater, and when an agent has already read the GPL copy, have
799
+ a fresh agent rewrite it from a prose spec. A census of the ROM keeps that spec small: every
800
+ DK64 stream has FLG 0 or FNAME, so accept those and throw on the rest (DK64 review,
801
+ 2026-12-05).
802
+ - **Classify triangles on the stored integers, before scaling.** Dividing first turns an exact
803
+ zero cross product into rounding noise, so edge-on faces slip into the floors (DK64).
804
+ - **Check a known-wet map before trusting the floors for water.** DK64 keeps water as rectangles
805
+ in the map file, apart from the collision mesh. Asset tables can redirect one entry to
806
+ another's data (bit 31 in DK64): follow redirects with a hop limit, and test a loop.
807
+ - **Confirm a sine table's period from the disassembly** (4096 steps in DK64) before setting a
808
+ heading offset and sign, and test the arrow against the direction of movement.
809
+ - **ROM-gated tests assert structure, not ROM counts or ids.** "Which spawns have no floor" or
810
+ "216 maps have files" read from the ROM are derived data; instead assert bounds and shapes,
811
+ such as the unreadable map ids forming one run at the end (DK64 review).
812
+ - **A place that covers several maps can't get a drawing.** DK64's live reader groups 95
813
+ unnamed maps as a world's "elsewhere"; plan for one place per map when a game has unnamed
814
+ maps.
815
+ - **A place name is a stated fact: two written sources, or the id.** Name a map only as far as
816
+ two written sources agree (decomp code or tables, a survey note, a recorded live run), cite both
817
+ beside the name, and otherwise name it by id ("map 0x38") while the live read supplies context.
818
+ Uncited player knowledge isn't a source: 33 of 44 names in DK64's first pass didn't survive
819
+ this. Slug unnamed places by id alone (`map-0c`), so a later name or ruling never changes a
820
+ slug; and a decomp's `.data` tables copied from the ROM (DK64's map → world table) are the
821
+ publisher's data, read live, not committed (DK64 review, 2026-12-05).
822
+ - **A counter declared only for `describeState` also reaches the AI.** Shared code puts every
823
+ declared counter the state carries into LIVE_STATE (`readableCountersFor`): DK64's world counter
824
+ told the model the main menu was "a shop". Send such a counter only where its value means
825
+ something to the model, and throw in `describeState` where it must be present.
826
+ - **The 65535-argument limit.** The core's QuickJS sandbox refuses a call of more than 65535
827
+ arguments; Node allows far more, so `Math.min(...xs)`, `out.push(...items)` and
828
+ `String.fromCharCode(...bytes)` over map-sized data pass vitest and throw in the sandbox (DK64's
829
+ Frantic Factory, 2026-12-06). `gameslate-plugin build` (sdk >= 0.3.25) reads your own code (what
830
+ `live.ts` and `assets.ts` bundle, not `node_modules`) and refuses, naming file:line, a spread
831
+ argument to any call or `new`, and `x.apply(t, list)`, `x['apply'](t, list)`,
832
+ `Function.prototype.apply.call(f, t, list)`, `Reflect.apply` and `Reflect.construct` unless the
833
+ list is an array literal without spreads; a file it can't parse fails too. Fold with
834
+ `extent(values, 'corner xs')` (it throws on no values or a non-finite one, so a bad frame fails
835
+ loud) and append with `append(into, items)`, both from `@gameslate/sdk`. When the length is fixed,
836
+ prefer plain arguments (`f(p[0], p[1], p[2])`). Otherwise put `/* spread-ok: <why it stays small>
837
+ */` on the line directly above the statement (a function, class, `export default` or class
838
+ property counts); it covers only calls that start on that statement's first line, never a loop
839
+ body or a multi-line arrow's body below, and the build refuses an empty reason or a marker that
840
+ marks nothing. Decode text in chunks of at most 0x2000 bytes (marked) or by loop. Dependencies
841
+ aren't checked: if one handles map-sized arrays, test a big input in the sandbox
842
+ (`@gameslate/sdk/host`). After a change that grows the geometry, run `gameslate extract-assets
843
+ <game> --input <rom> --out-dir <scratch>` (the core's `dist/gameslate.mjs` with
844
+ `GAMESLATE_PLUGINS_DIR=<plugin>/dist`).
845
+ - **Follow every source the floor or water query asks.** DK64's floor query merges the map mesh,
846
+ placed models and actor boxes; Conker's water height comes from water props, trigger-zone
847
+ volumes and surface type 8 at once. Port the game's query, not one of its sources, and say in
848
+ Known Gaps which sources are built at run time (animated bones, actor floors, scripted water)
849
+ and so aren't drawn.
850
+ - **A trigger volume isn't a surface.** Port its contains-test exactly (Conker's
851
+ `zone_isOutside`: thresholds, integer truncation, rotation order), draw the floors it holds as
852
+ water rather than its outline, check whether overlaps resolve last-wins or highest-wins, and
853
+ check any pre-filter the caller applies (a bounds box that rotates when the test doesn't).
854
+ Recolour floors under water as water, so a band painter can't hide a pond under ground of the
855
+ same band.
856
+ - **Prove a rotation's sign at a non-90° angle, axes combined.** A 90° turn or one axis lets a
857
+ sign error through, and a ROM check over mostly unrotated objects can't see it: derive order and
858
+ sign from the game's matrix chain (row vectors, `guMtxCatF` is a × b), pin per-axis goldens,
859
+ order goldens and an independent matrix oracle. Use the SDK's documented conventions, not the
860
+ decomp's copy of libultra, which is Nintendo's code.
861
+ - **Read the spawn function before blaming a spawn with no floor.** DK64's "nothing under"
862
+ spawns were doorway walk-ins (the kong walks 50 units along its yaw): test the walk's end over
863
+ a floor instead of raising a cap.
864
+ - **Padded record files:** accept a zero tail shorter than one record, refuse anything else.
865
+ - **Keep exploration tests out of a shared tree.** A `*.scratch.test.ts` broke another agent's
866
+ check: explore from the scratchpad.
738
867
  - **Mirror modes: draw the course as built.** `roomId` means a room to shared code (layer
739
868
  choice, actor filters, AI prompts: "I'm in Room 1"), so never use it for a mode. Where the
740
869
  game mirrors its world (Mario Kart 64's Extra cups), the reader negates x and the heading