roamwright 0.61.8 → 0.61.10

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.
@@ -57,3 +57,95 @@ test('remote-runner.sh rejects invalid slot names and missing required config',
57
57
  assert.equal(bad.status, 2);
58
58
  assert.match(bad.stderr, /invalid slot/);
59
59
  });
60
+
61
+ test('speed-guard.sh dispatches m1 and shared modes cleanly and validates arguments', t => {
62
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'rw-speed-guard-'));
63
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
64
+ const tools = path.join(root, 'tools');
65
+ fs.mkdirSync(tools, { recursive: true });
66
+ fs.writeFileSync(path.join(root, 'index.html'), '');
67
+ const fakeRunner = path.join(tools, 'runner.sh');
68
+ fs.writeFileSync(fakeRunner, '#!/bin/sh\necho "$TEST_HERE $TEST_KIND $TEST_REPO $*"\nexit 0\n', { mode: 0o755 });
69
+ const guard = path.join(TOOLS_DIR, 'speed-guard.sh');
70
+ const env = {
71
+ ...process.env,
72
+ GUARD_TOOLS_DIR: tools,
73
+ GUARD_ROOT: root,
74
+ GUARD_RUNNER: fakeRunner,
75
+ GUARD_RUNNER_PREFIX: 'TEST',
76
+ };
77
+ const m1 = spawnSync('sh', [guard, 'm1', 'http://localhost:8765/'], { encoding: 'utf8', env });
78
+ assert.equal(m1.status, 0);
79
+ assert.equal(m1.stdout.trim(), `1 measure ${root} city-flight.cjs --chrome --guard http://localhost:8765/`);
80
+ assert.equal(spawnSync('sh', [guard, 'm1', 'https://example.com/'], { env }).status, 2);
81
+ assert.equal(spawnSync('sh', [guard, 'bogus'], { env }).status, 2);
82
+ });
83
+
84
+ test('look-guard.sh parses filters and invokes the configured runner and comparator', t => {
85
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'rw-look-guard-sh-'));
86
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
87
+ const tools = path.join(root, 'tools');
88
+ fs.mkdirSync(tools, { recursive: true });
89
+ const fakeRunner = path.join(tools, 'runner.sh');
90
+ fs.writeFileSync(fakeRunner, '#!/bin/sh\necho "RUN:$TEST_KIND:$TEST_BASE2:$*"\n', { mode: 0o755 });
91
+ const fakeCompare = path.join(tools, 'compare.cjs');
92
+ fs.writeFileSync(fakeCompare, 'console.log("CMP:" + process.argv.slice(2).join("|"));\n');
93
+ const look = path.join(TOOLS_DIR, 'look-guard.sh');
94
+ const env = {
95
+ ...process.env,
96
+ LOOK_TOOLS_DIR: tools,
97
+ LOOK_ROOT: root,
98
+ LOOK_OUT: path.join(root, 'out'),
99
+ LOOK_RUNNER: fakeRunner,
100
+ LOOK_RUNNER_PREFIX: 'TEST',
101
+ LOOK_COMPARE_SCRIPT: fakeCompare,
102
+ LOOK_BASELINE: path.join(tools, 'base.yaml'),
103
+ };
104
+ const res = spawnSync('sh', [look, 'compare', 'http://localhost:8788/', '--land=north', '--strict'], { encoding: 'utf8', env });
105
+ assert.equal(res.status, 0, res.stderr);
106
+ const lines = res.stdout.trim().split('\n');
107
+ assert.match(lines[0], /^RUN:look:http:\/\/localhost:8788\/:look-guard\.cjs .* --land=north$/);
108
+ assert.equal(lines[1], `CMP:${path.join(root, 'out', 'look.yaml')}|${path.join(tools, 'base.yaml')}|--strict`);
109
+ assert.equal(spawnSync('sh', [look, '--unknown'], { env }).status, 2);
110
+ });
111
+
112
+ test('phone-guard.py parses baselines, extracts probe metrics, evaluates floors, and formats kept baselines', t => {
113
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'rw-phone-guard-'));
114
+ t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
115
+ const baseline = path.join(tmp, 'phone-baseline.yaml');
116
+ fs.writeFileSync(
117
+ baseline,
118
+ '# header\npreset: medium\nstanding:\n location/harbour: 55\nflown:\n location/harbour: { least: 48, over100: 1, over50: 2 }\n',
119
+ );
120
+ const script = [
121
+ 'import importlib.util, json, sys',
122
+ 'spec = importlib.util.spec_from_file_location("pg", sys.argv[1])',
123
+ 'mod = importlib.util.module_from_spec(spec)',
124
+ 'spec.loader.exec_module(mod)',
125
+ 'preset, standing, flown = mod.read_baseline(sys.argv[2])',
126
+ 'st = mod.parse_standing_log(["LOG note probe at harbour, medium: 56 59 58 frames shown"])',
127
+ 'fl = mod.parse_flown_log(["LOG note flown leg1: 52 frames a second, 2 stood over 25 ms, 1 over 50, 0 over 100", "LOG note flown leg2: 50 frames a second, 3 stood over 25 ms, 2 over 50, 1 over 100"])',
128
+ 'out = {',
129
+ ' "preset": preset, "standing": standing, "flown": flown,',
130
+ ' "st": st, "fl": fl,',
131
+ ' "ok_st": mod.evaluate_standing(st, standing["location/harbour"]),',
132
+ ' "fail_st": mod.evaluate_standing(50, standing["location/harbour"]),',
133
+ ' "ok_fl": mod.evaluate_flown(fl, flown["location/harbour"]),',
134
+ ' "fail_fl": mod.evaluate_flown({"least": 45, "over50": 1, "over100": 0}, flown["location/harbour"]),',
135
+ ' "kept": mod.format_baseline("# header\\n", preset, {"location/harbour": st}, {"location/harbour": fl}, margin=3),',
136
+ '}',
137
+ 'print(json.dumps(out))',
138
+ ].join('\n');
139
+ const run = spawnSync('python3', ['-c', script, path.join(TOOLS_DIR, 'phone-guard.py'), baseline], { encoding: 'utf8' });
140
+ assert.equal(run.status, 0, run.stderr);
141
+ const parsed = JSON.parse(run.stdout);
142
+ assert.equal(parsed.preset, 'medium');
143
+ assert.equal(parsed.st, 58);
144
+ assert.deepEqual(parsed.fl, { least: 50, over50: 2, over100: 1 });
145
+ assert.equal(parsed.ok_st, true);
146
+ assert.equal(parsed.fail_st, false);
147
+ assert.equal(parsed.ok_fl, true);
148
+ assert.equal(parsed.fail_fl, false);
149
+ assert.match(parsed.kept, /location\/harbour: 55/);
150
+ assert.match(parsed.kept, /least: 47, over100: 1, over50: 2/);
151
+ });
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('node:fs');
4
+ const os = require('node:os');
5
+ const path = require('node:path');
6
+ const test = require('node:test');
7
+ const { resolveServeScript } = require('./bake-publish.cjs');
8
+ const { formatSetCostReport, parseSetCostArgs } = require('./set-cost.cjs');
9
+
10
+ test('resolveServeScript finds engine scripts/serve.py by default and honors caller overrides', t => {
11
+ const found = resolveServeScript();
12
+ assert.ok(found.endsWith(path.join('scripts', 'serve.py')));
13
+ assert.ok(fs.existsSync(found));
14
+
15
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'rw-serve-resolve-'));
16
+ t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
17
+ const custom = path.join(tmp, 'custom-serve.py');
18
+ fs.writeFileSync(custom, '');
19
+ assert.equal(resolveServeScript({ serveScript: custom }), custom);
20
+ });
21
+
22
+ test('parseSetCostArgs applies default address and splits comma-separated set ids', () => {
23
+ assert.deepEqual(parseSetCostArgs([], 'location/harbour'), { address: 'location/harbour', only: [] });
24
+ assert.deepEqual(parseSetCostArgs(['location/market', 'gate,dock'], 'location/harbour'), {
25
+ address: 'location/market',
26
+ only: ['gate', 'dock'],
27
+ });
28
+ });
29
+
30
+ test('formatSetCostReport sorts slowest first and flags sets exceeding the frame-hold limit', () => {
31
+ const pass = formatSetCostReport(
32
+ [
33
+ { id: 'dock', ms: 16, took: 120, stood: true },
34
+ { id: 'gate', ms: 34, took: 240, stood: true },
35
+ ],
36
+ { address: 'location/harbour', limitMs: 40 },
37
+ );
38
+ assert.equal(pass.failed, false);
39
+ assert.equal(pass.sorted[0].id, 'gate');
40
+ assert.match(pass.lines.at(-1), /2 sets raised on location\/harbour: 0 held a frame over 40 ms/);
41
+
42
+ const fail = formatSetCostReport(
43
+ [
44
+ { id: 'dock', ms: 16, took: 120, stood: true },
45
+ { id: 'citadel', ms: 58, took: 400, stood: false },
46
+ ],
47
+ { address: 'location/harbour', limitMs: 40 },
48
+ );
49
+ assert.equal(fail.failed, true);
50
+ assert.equal(fail.held.length, 1);
51
+ assert.match(fail.lines[0], /\(not fetched\).*HELD/);
52
+ assert.match(fail.lines.at(-1), /FAILED: citadel held a frame/);
53
+ });
@@ -0,0 +1,301 @@
1
+ // Offline scene-script physical plausibility and pacing linter (no browser).
2
+ // Walks a scene's timed step array, camera keys, and narration captions to flag impossible
3
+ // walking/riding speeds, sliding moves, out-of-reach hand actions, long strike run-ins, empty
4
+ // carry poses, overlapping standing actors, mid-scene hour shifts, distant or fast cameras,
5
+ // over-fast caption reading speeds, and cues past the scene's duration.
6
+ //
7
+ // const { lintCatalog, formatLintReport, parseSceneLintArgs } = require('roamwright/tools/scene-lint.cjs');
8
+ //
9
+ // A world passes its own actor foot/kind lookup functions and verb table as data.
10
+ 'use strict';
11
+
12
+ /** Default physical and pacing thresholds (metres, seconds, metres/second, chars/second). */
13
+ const DEFAULT_LIMITS = Object.freeze({
14
+ sprint: 5.5,
15
+ run: 2.4,
16
+ gallop: 12,
17
+ shiftTime: 0.6,
18
+ shiftFar: 0.5,
19
+ handoverReach: 1.3,
20
+ runInSpeed: 4.2,
21
+ runInMax: 1,
22
+ bladeReach: 2.2,
23
+ standApart: 0.4,
24
+ camFar: 22,
25
+ camFarShare: 0.34,
26
+ camFast: 7,
27
+ readingRate: 17,
28
+ captionMargin: 2.4,
29
+ captionStart: 1.6,
30
+ lateEpsilon: 0.01,
31
+ });
32
+
33
+ /** Default finding kinds treated as hard errors (exit 1 when present). */
34
+ const DEFAULT_ERRORS = Object.freeze(new Set(['FAST', 'SLIDE', 'REACH', 'EMPTY', 'OVERLAP', 'HOUR', 'LATE']));
35
+
36
+ /** Default generic verb names and hand-reach distances (metres). Worlds override with their own verbs as data. */
37
+ const DEFAULT_VERBS = Object.freeze({
38
+ anchor: 'anchor',
39
+ place: 'place',
40
+ show: 'show',
41
+ hide: 'hide',
42
+ couple: 'couple',
43
+ pose: 'pose',
44
+ carryPose: 'carry',
45
+ flatPoses: ['dead', 'lie'],
46
+ hour: 'hour',
47
+ move: ['move', 'back'],
48
+ rideTag: 'ride',
49
+ act: 'act',
50
+ handReach: { give: 1.3, take: 1.3, punch: 2.6, stay: 1.2 },
51
+ prop: 'prop',
52
+ propHand: 'hand',
53
+ propMove: 'to',
54
+ propDrop: ['hide', 'lay', 'throw', 'to', 'show'],
55
+ strike: ['attack', 'spring', 'duel'],
56
+ });
57
+
58
+ /**
59
+ * Parses CLI flags for a scene-lint command (`--errors`, `--json`, and optional scene ids).
60
+ *
61
+ * @param {string[]} argv Raw CLI arguments (excluding `node` and script path).
62
+ * @returns {{ errorsOnly: boolean, asJson: boolean, only: string[] }}
63
+ */
64
+ function parseSceneLintArgs(argv) {
65
+ return {
66
+ errorsOnly: argv.includes('--errors'),
67
+ asJson: argv.includes('--json'),
68
+ only: argv.filter(a => !a.startsWith('--')),
69
+ };
70
+ }
71
+
72
+ /**
73
+ * Lints a single scene script for physically impossible motions, camera violations, and caption pacing.
74
+ *
75
+ * @param {object} event Scene definition (`{ id, dur, cast, steps, cam, camOn, narration }`).
76
+ * @param {object} [options]
77
+ * @param {(id: string, cast: object) => boolean} [options.isOnFoot] Returns true when the cast member is on foot (default: always true).
78
+ * @param {(id: string) => string | undefined} [options.actorKind] Returns a non-human creature kind if applicable (default: undefined).
79
+ * @param {Partial<typeof DEFAULT_LIMITS>} [options.limits] Threshold overrides.
80
+ * @param {Partial<typeof DEFAULT_VERBS>} [options.verbs] World-specific verb names and hand-reach table.
81
+ * @returns {Array<{ kind: string, t: number, text: string }>}
82
+ */
83
+ function lintScene(event, { isOnFoot = () => true, actorKind = () => undefined, limits = {}, verbs = {} } = {}) {
84
+ const cfg = { ...DEFAULT_LIMITS, ...limits };
85
+ const v = { ...DEFAULT_VERBS, ...verbs, handReach: { ...DEFAULT_VERBS.handReach, ...(verbs.handReach || {}) } };
86
+ const moveVerbs = new Set(v.move);
87
+ const propDropVerbs = new Set(v.propDrop);
88
+ const strikeVerbs = new Set(v.strike);
89
+ const flatPoses = new Set(v.flatPoses);
90
+
91
+ const found = [];
92
+ const say = (kind, t, text) => found.push({ kind, t, text });
93
+ const cast = event.cast ?? {};
94
+ const steps = [...(event.steps ?? [])].sort((a, b) => a[0] - b[0]);
95
+ const at = {}; // where each of the cast is, [east, south], and until when they are on their way there
96
+ const busy = {};
97
+ const shown = {};
98
+ const pose = {};
99
+ const holds = {}; // the prop each holds
100
+ const coupled = new Set();
101
+ let known = true; // false after the scene's place moves ('anchor'): offsets are then from somewhere else
102
+
103
+ for (const id in cast) {
104
+ at[id] = cast[id].p ? [cast[id].p[0], cast[id].p[1]] : null;
105
+ shown[id] = !cast[id].hide;
106
+ pose[id] = cast[id].pose ?? 'idle';
107
+ if (cast[id].couple) coupled.add(id).add(cast[id].couple[0]);
108
+ }
109
+ const apart = (a, b) => (at[a] && at[b] ? Math.hypot(at[a][0] - at[b][0], at[a][1] - at[b][1]) : NaN);
110
+ const ridesProp = s => steps.some(o => o[1] === v.prop && o[3] === v.propMove && Math.abs(o[0] - s[0]) < 0.05 && o[8] === s[5]);
111
+
112
+ for (const s of steps) {
113
+ const [t, verb, who] = s;
114
+ if (t > event.dur + cfg.lateEpsilon) say('LATE', t, `a '${verb}' step at ${t} s, after the scene's ${event.dur} s`);
115
+ if (verb === v.anchor) known = false;
116
+ else if (verb === v.place) {
117
+ at[who] = [s[3], s[4]];
118
+ known = true;
119
+ } else if (verb === v.show) shown[who] = true;
120
+ else if (verb === v.hide) shown[who] = false;
121
+ else if (verb === v.couple) coupled.add(who).add(s[3]);
122
+ else if (verb === v.pose) {
123
+ pose[who] = s[3];
124
+ if (s[3] === v.carryPose && !holds[who] && !coupled.has(who)) say('EMPTY', t, `${who} carries a load, with nothing in the hands`);
125
+ } else if (verb === v.hour && !s[3]) {
126
+ say('HOUR', t, `the hour moves to ${s[2]} inside the scene`); // at a cut to another place and day it may
127
+ } else if (moveVerbs.has(verb)) {
128
+ const from = at[who];
129
+ const to = [s[3], s[4]];
130
+ const far = from && known ? Math.hypot(to[0] - from[0], to[1] - from[1]) : NaN;
131
+ const pace = far / Math.max(0.01, s[5]);
132
+ const carried = s[7] === v.rideTag || ridesProp(s) || coupled.has(who);
133
+ if (!carried && shown[who] !== false && Number.isFinite(far)) {
134
+ const walking = isOnFoot(who, cast);
135
+ const kind = actorKind(who);
136
+ if (walking && s[5] < cfg.shiftTime && far > cfg.shiftFar)
137
+ say('SLIDE', t, `${who} is moved ${far.toFixed(1)} m in ${s[5]} s: too short a time to walk it`);
138
+ else if (walking && pace > cfg.sprint) say('FAST', t, `${who} is sent ${far.toFixed(1)} m in ${s[5]} s (${pace.toFixed(1)} m/s)`);
139
+ else if (walking && pace > cfg.run) say('RUN', t, `${who} runs ${far.toFixed(1)} m in ${s[5]} s (${pace.toFixed(1)} m/s)`);
140
+ else if (!walking && !kind && pace > cfg.gallop)
141
+ say('FAST', t, `${who} rides ${far.toFixed(1)} m in ${s[5]} s (${pace.toFixed(1)} m/s)`);
142
+ }
143
+ at[who] = to;
144
+ busy[who] = t + s[5];
145
+ } else if (verb === v.act && typeof s[4] === 'string' && v.handReach[s[3]] && known) {
146
+ const far = apart(who, s[4]);
147
+ if (far > v.handReach[s[3]]) say('REACH', t, `${who} is to ${s[3]} ${s[4]} from ${far.toFixed(1)} m away`);
148
+ } else if (verb === v.prop && s[3] === v.propHand) {
149
+ const giver = Object.keys(holds).find(id => holds[id] === who);
150
+ if (giver && s[6] && known) {
151
+ const far = apart(giver, s[4]);
152
+ if (far > cfg.handoverReach) say('REACH', t, `${who} is handed from ${giver} to ${s[4]} across ${far.toFixed(1)} m`);
153
+ }
154
+ if (giver) delete holds[giver];
155
+ holds[s[4]] = who;
156
+ } else if (verb === v.prop && propDropVerbs.has(s[3])) {
157
+ for (const id in holds) if (holds[id] === who) delete holds[id];
158
+ } else if (strikeVerbs.has(verb) && known && isOnFoot(who, cast)) {
159
+ const far = apart(who, s[3]);
160
+ const runIn = (far - cfg.bladeReach) / cfg.runInSpeed;
161
+ if (runIn > cfg.runInMax)
162
+ say('CHARGE', t, `${who} strikes at ${s[3]} from ${far.toFixed(1)} m: ${runIn.toFixed(1)} s of running in first`);
163
+ }
164
+ // Those who have come to rest stand clear of each other.
165
+ if (known && (verb === v.move[0] || verb === v.place)) {
166
+ for (const other in at) {
167
+ if (other === who || shown[other] === false || shown[who] === false || coupled.has(who) || coupled.has(other)) continue;
168
+ if (flatPoses.has(pose[other]) || flatPoses.has(pose[who])) continue;
169
+ if ((busy[other] ?? 0) > t + (verb === v.move[0] ? s[5] : 0)) continue;
170
+ if (apart(who, other) < cfg.standApart) say('OVERLAP', t, `${who} comes to stand ${apart(who, other).toFixed(2)} m from ${other}`);
171
+ }
172
+ }
173
+ }
174
+
175
+ // Track where each actor is over time to test camera distance and camera carry speed.
176
+ const ways = {};
177
+ for (const id in cast) ways[id] = cast[id].p ? [[0, cast[id].p[0], cast[id].p[1]]] : [];
178
+ for (const s of [...(event.steps ?? [])].sort((a, b) => a[0] - b[0])) {
179
+ const way = ways[s[2]];
180
+ if (!way || typeof s[3] !== 'number' || typeof s[4] !== 'number') continue;
181
+ if (moveVerbs.has(s[1])) {
182
+ const from = way[way.length - 1];
183
+ if (from) way.push([s[0], from[1], from[2]]);
184
+ way.push([s[0] + (typeof s[5] === 'number' ? s[5] : 0), s[3], s[4]]);
185
+ } else if (s[1] === v.place) way.push([s[0], s[3], s[4]]);
186
+ }
187
+ const placeAt = (id, t) => {
188
+ const way = ways[id];
189
+ if (!way.length) return null;
190
+ let i = 0;
191
+ while (i + 1 < way.length && way[i + 1][0] <= t) i++;
192
+ const from = way[i];
193
+ const to = way[i + 1];
194
+ if (!to || to[0] <= from[0] || t <= from[0]) return from;
195
+ const k = (t - from[0]) / (to[0] - from[0]);
196
+ return [t, from[1] + (to[1] - from[1]) * k, from[2] + (to[2] - from[2]) * k];
197
+ };
198
+
199
+ const cam = event.cam ?? [];
200
+ let farTime = 0;
201
+ for (let i = 0; i + 1 < cam.length; i++) {
202
+ const a = cam[i];
203
+ const b = cam[i + 1];
204
+ const span = b[0] - a[0];
205
+ if (b[0] > event.dur + cfg.lateEpsilon) say('LATE', b[0], `a camera key at ${b[0]} s, after the scene's ${event.dur} s`);
206
+ if (b[7] || span <= 0) continue; // a cut
207
+ const speed = Math.hypot(b[1] - a[1], b[2] - a[2], b[3] - a[3]) / span;
208
+ if (speed > cfg.camFast) say('CAMSPEED', a[0], `the camera goes ${speed.toFixed(1)} m/s from ${a[0]} s to ${b[0]} s`);
209
+ const on = event.camOn && cast[event.camOn]?.p ? cast[event.camOn].p : [0, 0]; // a camera carried with one of the cast is counted from them
210
+ const mx = on[0] + (a[1] + b[1]) / 2;
211
+ const mz = on[1] + (a[3] + b[3]) / 2;
212
+ const mid = (a[0] + b[0]) / 2;
213
+ const nearest = Math.min(
214
+ ...Object.keys(cast).map(id => {
215
+ const p = event.camOn ? cast[id].p && [0, cast[id].p[0], cast[id].p[1]] : placeAt(id, mid);
216
+ return p ? Math.hypot(p[1] - mx, p[2] - mz) : Infinity;
217
+ }),
218
+ );
219
+ if (nearest > cfg.camFar) farTime += span;
220
+ }
221
+ if (farTime > event.dur * cfg.camFarShare)
222
+ say('FARCAM', 0, `for ${farTime.toFixed(0)} of ${event.dur} s the camera is over ${cfg.camFar} m from where any of the cast is`);
223
+
224
+ const lines = event.narration ?? [];
225
+ const slot = (event.dur - cfg.captionMargin) / Math.max(1, lines.length);
226
+ lines.forEach((line, i) => {
227
+ if (line.length / slot > cfg.readingRate)
228
+ say(
229
+ 'READ',
230
+ cfg.captionStart + i * slot,
231
+ `caption ${i + 1} has ${line.length} characters and ${slot.toFixed(1)} s (${(line.length / slot).toFixed(0)} a second)`,
232
+ );
233
+ });
234
+ return found;
235
+ }
236
+
237
+ /**
238
+ * Lints a list of scenes, optionally filtering by scene ids and error severity.
239
+ *
240
+ * @param {Array<{ event: object } | object>} scenes Scene entries (`{ event }` or bare event objects).
241
+ * @param {object} [options]
242
+ * @param {string[]} [options.only=[]] Optional scene ids to keep.
243
+ * @param {boolean} [options.errorsOnly=false] When true, keep only findings in `errors`.
244
+ * @param {Set<string>} [options.errors=DEFAULT_ERRORS] Finding kinds that fail the check.
245
+ * @param {(id: string, cast: object) => boolean} [options.isOnFoot] Passed through to `lintScene`.
246
+ * @param {(id: string) => string | undefined} [options.actorKind] Passed through to `lintScene`.
247
+ * @param {Partial<typeof DEFAULT_LIMITS>} [options.limits] Passed through to `lintScene`.
248
+ * @param {Partial<typeof DEFAULT_VERBS>} [options.verbs] Passed through to `lintScene`.
249
+ * @returns {{ report: Array<{ id: string, n: number, dur: number, found: Array<{ kind: string, t: number, text: string }> }>, hasErrors: boolean }}
250
+ */
251
+ function lintCatalog(scenes, { only = [], errorsOnly = false, errors = DEFAULT_ERRORS, isOnFoot, actorKind, limits, verbs } = {}) {
252
+ const unwrap = entry => (entry && entry.event ? entry.event : entry);
253
+ const selected = scenes.map(unwrap).filter(event => !only.length || only.includes(event.id));
254
+ const report = selected.map((event, i) => ({
255
+ id: event.id,
256
+ n: i + 1,
257
+ dur: event.dur,
258
+ found: lintScene(event, { isOnFoot, actorKind, limits, verbs }).filter(f => !errorsOnly || errors.has(f.kind)),
259
+ }));
260
+ const hasErrors = report.some(r => r.found.some(f => errors.has(f.kind)));
261
+ return { report, hasErrors };
262
+ }
263
+
264
+ /**
265
+ * Formats a `lintCatalog` report as either human-readable lines or JSON.
266
+ *
267
+ * @param {Array<{ id: string, n: number, dur: number, found: Array<{ kind: string, t: number, text: string }> }>} report
268
+ * @param {object} [options]
269
+ * @param {boolean} [options.asJson=false] Emit JSON instead of plain text.
270
+ * @returns {string}
271
+ */
272
+ function formatLintReport(report, { asJson = false } = {}) {
273
+ if (asJson) return JSON.stringify(report, null, 1);
274
+ const lines = [];
275
+ const total = {};
276
+ for (const { id, dur, found } of report) {
277
+ if (!found.length) continue;
278
+ lines.push(`${id} (${dur} s)`);
279
+ for (const f of found) {
280
+ total[f.kind] = (total[f.kind] || 0) + 1;
281
+ lines.push(` ${f.kind.padEnd(8)} ${String(f.t.toFixed(1)).padStart(5)} s ${f.text}`);
282
+ }
283
+ }
284
+ lines.push(
285
+ `${report.length} scenes, ${report.filter(r => r.found.length).length} with findings: ` +
286
+ Object.entries(total)
287
+ .map(([k, v]) => `${k} ${v}`)
288
+ .join(', '),
289
+ );
290
+ return lines.join('\n');
291
+ }
292
+
293
+ module.exports = {
294
+ DEFAULT_LIMITS,
295
+ DEFAULT_ERRORS,
296
+ DEFAULT_VERBS,
297
+ parseSceneLintArgs,
298
+ lintScene,
299
+ lintCatalog,
300
+ formatLintReport,
301
+ };
@@ -0,0 +1,75 @@
1
+ 'use strict';
2
+ const assert = require('node:assert/strict');
3
+ const test = require('node:test');
4
+ const { formatLintReport, lintCatalog, lintScene, parseSceneLintArgs } = require('./scene-lint.cjs');
5
+
6
+ test('parseSceneLintArgs extracts flags and scene id filters', () => {
7
+ assert.deepEqual(parseSceneLintArgs(['--errors', 'bridge', '--json', 'harbour']), {
8
+ errorsOnly: true,
9
+ asJson: true,
10
+ only: ['bridge', 'harbour'],
11
+ });
12
+ });
13
+
14
+ test('lintScene flags speed, slide, reach, charge, empty carry, overlap, hour, camera, caption, and late cues', () => {
15
+ const scene = {
16
+ id: 'test_scene',
17
+ dur: 10,
18
+ cast: {
19
+ a: { p: [0, 0] },
20
+ b: { p: [6, 0] },
21
+ rider: { p: [0, 5] },
22
+ },
23
+ steps: [
24
+ [0.2, 'move', 'a', 1, 0, 0.2], // SLIDE (1 m in 0.2 s)
25
+ [0.5, 'move', 'a', 20, 0, 2], // FAST on foot (9.5 m/s)
26
+ [1.0, 'move', 'b', 2, 0, 1], // RUN on foot (4 m/s)
27
+ [1.2, 'move', 'rider', 50, 5, 2], // FAST riding (25 m/s)
28
+ [2.5, 'pose', 'a', 'carry'], // EMPTY carry
29
+ [3.0, 'act', 'a', 'give', 'b'], // REACH (> 1.3 m)
30
+ [3.2, 'prop', 'letter', 'hand', 'a'],
31
+ [3.5, 'prop', 'letter', 'hand', 'b', undefined, 0.3], // REACH handover
32
+ [4.0, 'attack', 'a', 'b'], // CHARGE (> 1 s run-in)
33
+ [4.5, 'hour', 0.8], // HOUR mid-scene
34
+ [5.0, 'place', 'a', 2.1, 0], // OVERLAP with b at [2, 0]
35
+ [11.0, 'pose', 'a', 'idle'], // LATE step
36
+ ],
37
+ cam: [
38
+ [0, 50, 1.6, 50, 0, 1, 0],
39
+ [6, 50, 1.6, 50, 0, 1, 0], // FARCAM (6 of 10 s)
40
+ [7, 0, 1.6, 0, 0, 1, 0], // CAMSPEED (> 7 m/s)
41
+ [11, 0, 1.6, 0, 0, 1, 0], // LATE cam key
42
+ ],
43
+ narration: ['x'.repeat(200)], // READ (> 17 chars/s)
44
+ };
45
+ const findings = lintScene(scene, { isOnFoot: id => id !== 'rider' });
46
+ const kinds = new Set(findings.map(f => f.kind));
47
+ for (const expected of ['SLIDE', 'FAST', 'RUN', 'EMPTY', 'REACH', 'CHARGE', 'HOUR', 'OVERLAP', 'FARCAM', 'CAMSPEED', 'READ', 'LATE']) {
48
+ assert.ok(kinds.has(expected), `expected finding kind ${expected}, got ${[...kinds].join(', ')}`);
49
+ }
50
+ });
51
+
52
+ test('lintCatalog filters by errorsOnly and formats deterministic text and JSON output', () => {
53
+ const clean = {
54
+ id: 'quiet',
55
+ dur: 10,
56
+ cast: { a: { p: [0, 0] } },
57
+ steps: [[1, 'move', 'a', 3, 0, 1]], // RUN warning only, not an error
58
+ cam: [
59
+ [0, 0, 1.6, 4, 0, 1, 0],
60
+ [10, 0, 1.6, 4, 0, 1, 0],
61
+ ],
62
+ narration: ['Short line.'],
63
+ };
64
+ const all = lintCatalog([clean]);
65
+ assert.equal(all.hasErrors, false);
66
+ assert.equal(all.report[0].found.length, 1);
67
+ assert.equal(all.report[0].found[0].kind, 'RUN');
68
+ assert.match(formatLintReport(all.report), /1 scenes, 1 with findings: RUN 1/);
69
+ assert.deepEqual(JSON.parse(formatLintReport(all.report, { asJson: true }))[0].id, 'quiet');
70
+
71
+ const errs = lintCatalog([clean], { errorsOnly: true });
72
+ assert.equal(errs.hasErrors, false);
73
+ assert.equal(errs.report[0].found.length, 0);
74
+ assert.equal(formatLintReport(errs.report), '1 scenes, 0 with findings: ');
75
+ });