@threenative/playtest 0.3.6 → 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.
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { PNG } from 'pngjs';
3
- import { readFile, access, mkdir, writeFile, stat, mkdtemp, readdir, open, rm, rename, unlink, rmdir, copyFile } from 'fs/promises';
4
- import path, { resolve, dirname, join, basename, extname, isAbsolute, relative } from 'path';
5
3
  import { existsSync, realpathSync, createWriteStream, readdirSync, readFileSync, constants as constants$1, rmSync } from 'fs';
4
+ import { execFile, spawn, execFileSync, spawnSync } from 'child_process';
5
+ import path, { resolve, dirname, join, basename, extname, isAbsolute, relative } from 'path';
6
+ import { readFile, access, mkdir, writeFile, stat, mkdtemp, readdir, rm, unlink, rename, open, rmdir, copyFile } from 'fs/promises';
6
7
  import { fileURLToPath } from 'url';
7
8
  import { createHash } from 'crypto';
8
9
  import { tmpdir, homedir, loadavg, availableParallelism, constants } from 'os';
9
- import { execFile, spawn, execFileSync, spawnSync } from 'child_process';
10
10
  import { createRequire } from 'module';
11
11
  import { promisify } from 'util';
12
12
  import { chromium } from 'playwright';
@@ -226,10 +226,15 @@ var browser_exports = {};
226
226
  __export(browser_exports, {
227
227
  PERFORMANCE_BROWSER_ARGS: () => PERFORMANCE_BROWSER_ARGS,
228
228
  WEBGPU_BROWSER_ARGS: () => WEBGPU_BROWSER_ARGS,
229
+ measurementBrowserArgs: () => measurementBrowserArgs,
229
230
  reconcileBrowserPointers: () => reconcileBrowserPointers,
230
231
  resolveBrowserArguments: () => resolveBrowserArguments,
231
232
  softwareAdapterName: () => softwareAdapterName
232
233
  });
234
+ function measurementBrowserArgs(performance2, completion, display, gameThread = "page") {
235
+ const args = completion || performance2 && display === "virtual" ? PERFORMANCE_BROWSER_ARGS : [];
236
+ return gameThread === "worker" ? args.filter((argument) => argument !== "--disable-frame-rate-limit") : args;
237
+ }
233
238
  function resolveBrowserArguments(browserArgs) {
234
239
  return [...browserArgs ?? []];
235
240
  }
@@ -274,10 +279,9 @@ var init_browser = __esm({
274
279
  "--disable-gpu-sandbox",
275
280
  "--ignore-gpu-blocklist",
276
281
  // Keep Vulkan available on both hardware and software adapters.
277
- "--enable-features=Vulkan",
278
- // Forced ANGLE/Vulkan selects NVIDIA locally but breaks hosted software adapters, especially headed.
279
- // Apply that workaround only when the caller explicitly requests the host display.
280
- ...typeof process !== "undefined" && process.env.TN_PLAYTEST_HOST_DISPLAY === "1" ? ["--use-angle=vulkan", "--use-vulkan", "--disable-vulkan-surface"] : []
282
+ "--enable-features=Vulkan"
283
+ // No forced ANGLE/Vulkan (--use-angle=vulkan --use-vulkan --disable-vulkan-surface): on a KDE
284
+ // Xwayland host display it blacked out the sky while the same NVIDIA adapter drew it without them.
281
285
  ];
282
286
  PERFORMANCE_BROWSER_ARGS = [
283
287
  "--disable-frame-rate-limit",
@@ -701,7 +705,7 @@ var init_assertion_schema = __esm({
701
705
  example: { visual: [{ frameDiff: { baselineImage: "artifacts/baseline.png", minChangedPixelRatio: 0.01 }, entityVisible: { entity: "board.e4", minProjectedPixels: 20, throughoutFrames: true }, region: { element: { id: "error" }, minNonblankPixelRatio: 2e-3 } }] },
702
706
  fields: [
703
707
  { description: "Before/after or baseline-image changed-pixel ratio bounds.", name: "frameDiff", type: "{ baselineImage?: project-relative PNG, minChangedPixelRatio?: number, maxChangedPixelRatio?: number }" },
704
- { description: "Static pixel bounds, or a DOM element whose bounds are captured beside the screenshot; the latter accepts exactly one id or selector. Both forms accept nonblank, dark-pixel, and luminance thresholds.", name: "region", type: "static bounds { x: number, y: number, width: number, height: number, minNonblankPixelRatio?: number, maxDarkPixelRatio?: number, minDarkPixelRatio?: number, maxLuminance?: number } or element bounds { element: { id?: string, selector?: string }, minNonblankPixelRatio?: number, maxDarkPixelRatio?: number, minDarkPixelRatio?: number, maxLuminance?: number }" },
708
+ { description: "Static pixel bounds, or a DOM element whose bounds are captured beside the screenshot; the latter accepts exactly one id or selector. Both forms accept nonblank, dark-pixel, and luminance thresholds. A static region also takes `minSharpness` (a ratio, start at 0.3): the share of luminance detail that survives at full resolution against half resolution in the final frame. In-focus frames read 0.39-0.61, a frame a post stage smears reads 0.21-0.24.", name: "region", type: "static bounds { x: number, y: number, width: number, height: number, minSharpness?: number, minNonblankPixelRatio?: number, maxDarkPixelRatio?: number, minDarkPixelRatio?: number, maxLuminance?: number } or element bounds { element: { id?: string, selector?: string }, minNonblankPixelRatio?: number, maxDarkPixelRatio?: number, minDarkPixelRatio?: number, maxLuminance?: number }" },
705
709
  { description: "Entity projected-pixel floor, optionally across all captured samples.", name: "entityVisible", type: "{ entity: string, minProjectedPixels: number, throughoutFrames?: boolean }" }
706
710
  ],
707
711
  cardinality: "array",
@@ -795,7 +799,7 @@ var init_assertion_schema = __esm({
795
799
  { description: "Substring expected in the observed value.", name: "textIncludes", type: "string" },
796
800
  { description: "Require before and after values to differ or remain equal.", name: "changed", type: "boolean" },
797
801
  { description: "Require the value assertion after every labeled scenario step.", name: "throughoutSteps", type: "boolean" },
798
- { description: "Expected values at named scenario-step samples.", name: "atSteps", type: "Array<{ label: string, equals?: json, textIncludes?: string }>" },
802
+ { description: "Expected values at named scenario-step samples.", name: "atSteps", type: "Array<{ label: string, equals?: json, lte?: number, textIncludes?: string }>" },
799
803
  { description: "Written reason for a held invariant whose initial value intentionally satisfies the assertion.", name: "allowTrivial", type: "triviality reason" },
800
804
  { description: "Require at least one alternative path assertion on this resource id.", name: "anyOf", type: "Array<{ path: string, equals?: json, gte?: number, lte?: number, textIncludes?: string, changed?: boolean }>" }
801
805
  ],
@@ -931,7 +935,8 @@ var init_assertion_schema = __esm({
931
935
  description: "Proves a live render sample exists and optionally bounds frame time, an fps floor, per-phase frame budget, whole-frame or per-pass draw calls and triangles.",
932
936
  example: { performance: { maxPassDrawCalls: { shadow: 400 }, maxPhaseMsP95: { render: 12 }, minFps: 30 } },
933
937
  fields: [
934
- { description: "Maximum nearest-rank 95th-percentile frame time in milliseconds.", name: "maxFrameMsP95", type: "number" },
938
+ { description: "Maximum nearest-rank 95th-percentile frame time in milliseconds. Unset, the budget is 16.7 ms (one 60 Hz frame, 60 fps) on every tier; a software adapter is unmeasurable and fails closed. On the runner's virtual display the bound judges the engine's own cost (update plus render, or GPU time when larger) and reports the rAF interval as `gated: false`; on a real display (`TN_PLAYTEST_HOST_DISPLAY=1`) the interval and the cost must both hold. A missing CPU split or GPU reading fails closed. `frameBudget` in the `performance.samples` details reports which applied. A value above 16.7 is an override and needs `maxFrameMsReason`.", name: "maxFrameMsP95", type: "number" },
939
+ { description: "Why this scenario cannot hold 60 fps. Required when `maxFrameMsP95` is above 16.7; printed in the report.", name: "maxFrameMsReason", type: "non-empty string" },
935
940
  { description: "Minimum sustained frames per second, from the median sampled frame.", name: "minFps", type: "number" },
936
941
  { description: "Per-phase millisecond ceilings at nearest-rank p95. Phases: hostGap, update, render, overlay, residual.", name: "maxPhaseMsP95", type: "{ [phase]: number }" },
937
942
  { description: "Maximum observed renderer draw-call count across every pass combined.", name: "maxDrawCalls", type: "number" },
@@ -1085,6 +1090,7 @@ var init_assertion_schema = __esm({
1085
1090
  fields: [
1086
1091
  { description: "Entity id. Defaults to scenario subject.", name: "entity", type: "string" },
1087
1092
  { description: "Animation clip id or name.", name: "clip", type: "string" },
1093
+ { description: "Labeled step whose animation report is judged; default is the last sample.", name: "atStep", type: "string" },
1088
1094
  { description: "Require entering the animation state.", name: "entered", type: "boolean" },
1089
1095
  { description: "Require animation advancement evidence.", name: "advancedFrames", type: "number" },
1090
1096
  { description: "Require the observed clip to report its completion state.", name: "finished", type: "boolean" },
@@ -1142,6 +1148,79 @@ var init_assertion_schema = __esm({
1142
1148
  triviality: "not-applicable",
1143
1149
  trivialityRationale: "A node's presence, visibility, framing and texture state are properties of the scene as built; a crate that is already on screen is the assertion holding, not a trivial pass."
1144
1150
  },
1151
+ {
1152
+ cardinality: "array",
1153
+ description: "Bounds how far a planted foot slides while the subject moves, measured every tick from named foot nodes' world positions, so it holds a procedural rig to the feet-meet-the-floor convention as well as a clip. Browser target only; another target fails it as unobserved.",
1154
+ example: { footSlip: [{ atStep: "run", feet: ["footL", "footR"], maxSlip: 0.35 }] },
1155
+ fields: [
1156
+ { description: "Label of the input step to measure; it is advanced one tick at a time and must move the subject at least 0.5 m.", name: "atStep", type: "string" },
1157
+ { description: "Exact Object3D names of the nodes at the soles, one per foot.", name: "feet", type: "Array<string>" },
1158
+ { description: "Ceiling on planted-foot travel over body travel while a foot is in the lowest quarter of its lift below the body: 0 is planted, 1 skates with the body, above 1 the legs cycle faster than the ground moves. Set this, `maxSlideSpeed`, or both.", name: "maxSlip", type: "positive number" },
1159
+ { description: "Ceiling on a planted foot's world speed in metres per second (planted-foot travel over planted time), independent of the body's speed and of the game's own stride report. A starter-kit character holds 1.", name: "maxSlideSpeed", type: "positive number" },
1160
+ { description: "Seconds per fixed tick, which turns planted ticks into planted time for `maxSlideSpeed`. Default 1/60, the engine's default `step`; name it when the game sets another.", name: "stepSeconds", type: "positive number" },
1161
+ { description: "The moving entity; defaults to the scenario subject.", name: "entity", type: "string" }
1162
+ ],
1163
+ kind: "footSlip",
1164
+ observationPath: "footSlip",
1165
+ requiredCapabilities: ["entity.observe", "scene.nodes"],
1166
+ resultIdPrefix: "footSlip",
1167
+ supportedOn: ["web"],
1168
+ triviality: "not-applicable",
1169
+ trivialityRationale: "The measurement needs the subject to cover ground during the step, so a standing subject fails as unmeasured instead of passing."
1170
+ },
1171
+ {
1172
+ cardinality: "object",
1173
+ description: "Bounds the share of the run in which solid geometry stood between the camera and the subject's world bounds centre, so a camera that clips through a pillar or a wall that eats the framing fails. Browser target only; another target fails it as unobserved.",
1174
+ example: { sightLine: { maxBlockedRatio: 0.02 } },
1175
+ fields: [
1176
+ { description: "The entity whose world bounds centre the camera should see; defaults to the scenario subject.", name: "entity", type: "string" },
1177
+ { description: "Share of samples, 0..1, that may have any solid between the lens and the subject before the run fails; 0 requires a clear line on every sample.", name: "maxBlockedRatio", required: true, type: "number" }
1178
+ ],
1179
+ kind: "sightLine",
1180
+ observationPath: "sightLine",
1181
+ requiredCapabilities: ["camera.observe", "entity.observe"],
1182
+ resultIdPrefix: "sightLine",
1183
+ supportedOn: ["web"],
1184
+ triviality: "not-applicable",
1185
+ trivialityRationale: "The measurement needs the runtime camera and subject to stay framed over time; an initial pose cannot satisfy a temporal share of clear lines."
1186
+ },
1187
+ {
1188
+ cardinality: "object",
1189
+ description: "Bounds the engine's own work counters, read off each TN_FRAME_BUDGET window's counters.engine (and counters.bridgeCrossings): JS-to-Wasm crossings, children reads, scene-walk visits, hierarchy moves, matrix composes, handle shares, content classification, GPU allocations, physics crossings and any counter an engine module adds to globalThis.__tnEngineCost. Each window must hold every bound; a run with fewer windows than minWindows, or a window missing a bounded counter, fails closed. A failure names the counter, the window and the top caller of the TN_BRIDGE_CENSUS before it.",
1190
+ example: { engineCost: { maxPerFrame: { bridgeCrossings: 2e3, childrenReads: 60 }, skipWindows: 1, source: "shooter after-value 1,024 per frame on 2026-10-27, about 2x headroom" } },
1191
+ fields: [
1192
+ { description: "Counter name to its bound on a window's per-frame mean.", name: "maxPerFrame", type: "{ [counter: string]: number }" },
1193
+ { description: "Counter name to its bound on any single frame of a window.", name: "maxInFrame", type: "{ [counter: string]: number }" },
1194
+ { description: "Windows the run must report; default 1.", name: "minWindows", type: "positive integer" },
1195
+ { description: "Windows left unbounded first, the boot (loading, first builds); still and moving count after them. Default 0.", name: "skipWindows", type: "non-negative integer" },
1196
+ { description: "Per-frame bounds on the first `windows` windows only, which the scenario keeps still.", name: "still", type: "{ windows: positive integer, maxPerFrame: { [counter: string]: number } }" },
1197
+ { description: "Bounds on the windows after the still ones, which the scenario fills with play; needs still.", name: "moving", type: "{ maxPerFrame?: { [counter: string]: number }, maxInFrame?: { [counter: string]: number } }" },
1198
+ { description: "Where the bounds came from: the measured after-values and the headroom on them.", name: "source", required: true, type: "string" }
1199
+ ],
1200
+ kind: "engineCost",
1201
+ observationPath: "console",
1202
+ requiredCapabilities: ["browser.console"],
1203
+ resultIdPrefix: "engineCost.",
1204
+ supportedOn: ["web"],
1205
+ triviality: "not-applicable",
1206
+ trivialityRationale: "The counters are measured across the run's frames; an initial value has no frames to count."
1207
+ },
1208
+ {
1209
+ cardinality: "object",
1210
+ description: "Audits the text the page draws for the player: developer left-overs such as debug, TODO, placeholder or an unresolved undefined, and text whose colour is too close to its backing colour. Browser target only; another target fails it as unobserved.",
1211
+ example: { hudAudit: { minContrast: 3, noDebugText: true } },
1212
+ fields: [
1213
+ { description: "WCAG 2.x contrast ratio, 1..21, that every text item over a real backing colour must reach; text drawn straight on the canvas is counted as unjudged.", name: "minContrast", type: "number" },
1214
+ { description: "Require that no text reads like developer copy. Only true is accepted.", name: "noDebugText", type: "true" }
1215
+ ],
1216
+ kind: "hudAudit",
1217
+ observationPath: "hudAudit",
1218
+ requiredCapabilities: ["browser.dom"],
1219
+ resultIdPrefix: "hudAudit.",
1220
+ supportedOn: ["web"],
1221
+ triviality: "not-applicable",
1222
+ trivialityRationale: "The audit reads the live document the player sees, so an initial value cannot prove that developer text never appeared or that a colour stays readable."
1223
+ },
1145
1224
  {
1146
1225
  cardinality: "array",
1147
1226
  description: "Relates a tick-stamped effect to the tick-stamped cause that must precede it \u2014 the 'because' a terminal state needs.",
@@ -1175,7 +1254,9 @@ var init_assertion_schema = __esm({
1175
1254
  fields: [
1176
1255
  { description: "Ceiling on when the start scene's enter() returned, in ms since navigation.", name: "maxEnteredMs", type: "number" },
1177
1256
  { description: "Ceiling on when first-use compilation settled or its budget expired, in ms since navigation.", name: "maxCompileSettledMs", type: "number" },
1178
- { description: "Ceiling on when startup readiness resolved, in ms since navigation.", name: "maxReadyMs", type: "number" }
1257
+ { description: "Ceiling on when startup readiness resolved, in ms since navigation.", name: "maxReadyMs", type: "number" },
1258
+ { description: "Ceiling on the bytes the reveal waited for through ctx.assets that the spawn camera does not show, from the runtime's own measurement; 0 asserts everything awaited is in view.", name: "maxOffscreenBytes", type: "number" },
1259
+ { description: "true: every frame the browser presented between navigation and readiness matches the last one before readiness (the loading cover), so a black, blank or page-background frame fails, and no frame between readiness and the first world frame shows page UI (a HUD) over the cover. Browser target only; elsewhere it fails as unobserved.", name: "steadyCover", type: "boolean" }
1179
1260
  ],
1180
1261
  cardinality: "object",
1181
1262
  kind: "startup",
@@ -1462,6 +1543,42 @@ var init_device_metrics = __esm({
1462
1543
  }
1463
1544
  });
1464
1545
 
1546
+ // src/evaluators/perf-warnings.ts
1547
+ function perfWarnings(consoleLines) {
1548
+ const found = [];
1549
+ for (const line of consoleLines) {
1550
+ if (typeof line !== "string") continue;
1551
+ for (const marker2 of [SCENE_WARNING, BRIDGE_WARNING, HOT_CALL]) {
1552
+ const warning = line.indexOf(marker2);
1553
+ if (warning !== -1) found.push(line.slice(warning).trim());
1554
+ }
1555
+ const at = line.indexOf(PROJECTION);
1556
+ if (at === -1) continue;
1557
+ const text = line.slice(at).trim();
1558
+ let report;
1559
+ try {
1560
+ report = JSON.parse(line.slice(at + PROJECTION.length));
1561
+ } catch {
1562
+ found.push(`${text} (unreadable)`);
1563
+ continue;
1564
+ }
1565
+ if (report.projecting !== false || report.reasonCode === "disabled") continue;
1566
+ if (report.reasonCode === "belowMeshFloor") continue;
1567
+ const cause = report.cause === void 0 ? "" : ` [cause ${report.cause.code ?? "?"}: ${report.cause.hint ?? "no hint"}]`;
1568
+ found.push(`${text}${cause}`);
1569
+ }
1570
+ return found;
1571
+ }
1572
+ var SCENE_WARNING, BRIDGE_WARNING, HOT_CALL, PROJECTION;
1573
+ var init_perf_warnings = __esm({
1574
+ "src/evaluators/perf-warnings.ts"() {
1575
+ SCENE_WARNING = "TN_SCENE_WARNING";
1576
+ BRIDGE_WARNING = "TN_BRIDGE_WARNING";
1577
+ HOT_CALL = "TN_HOT_CALL";
1578
+ PROJECTION = "TN_RENDER_PROJECTION:";
1579
+ }
1580
+ });
1581
+
1465
1582
  // src/evaluators/measures.ts
1466
1583
  function horizontalRadius(transform, direction) {
1467
1584
  const halfExtents = transform?.halfExtents ?? (transform?.scale === void 0 ? void 0 : transform.scale.map((value) => Math.abs(value) * 0.5));
@@ -1747,6 +1864,15 @@ function evaluateDiagnosticsPolicy(report, policy) {
1747
1864
  suggestion: "Inspect console.json and fix the first TN_V8_FRAME_FAILED error."
1748
1865
  });
1749
1866
  }
1867
+ const warnings = perfWarnings((report.observations?.console ?? []).map(({ text }) => text));
1868
+ if (warnings.length > 0) {
1869
+ diagnostics.push({
1870
+ code: "TN_PLAYTEST_PERF_WARNING",
1871
+ message: `${warnings.length} engine performance warning(s): ${warnings.slice(0, 3).join(" | ")}`,
1872
+ severity: "error",
1873
+ suggestion: "Fix what the warning names (a unique geometry or material splitting a batch, a CPU-bound scene) or set renderer.projection: false when the game measured projection as a loss."
1874
+ });
1875
+ }
1750
1876
  const capturedConsoleErrors = consoleErrors(report.observations?.console ?? []);
1751
1877
  if (policy.noConsoleErrors && capturedConsoleErrors.length > 0) {
1752
1878
  diagnostics.push({
@@ -1880,6 +2006,7 @@ function evaluateVisibilityAssertion(assertion, entity, viewport, runtimeDiagnos
1880
2006
  var init_measures = __esm({
1881
2007
  "src/evaluators/measures.ts"() {
1882
2008
  init_assertion_schema();
2009
+ init_perf_warnings();
1883
2010
  init_assertion_report();
1884
2011
  }
1885
2012
  });
@@ -2125,11 +2252,15 @@ function strideReading(observed) {
2125
2252
  return {
2126
2253
  clipGroundSpeed: stride.clipGroundSpeed,
2127
2254
  groundSpeed: stride.groundSpeed,
2255
+ inPlace: stride.inPlace === true,
2128
2256
  overridden: stride.overridden,
2129
2257
  rate: stride.rate,
2130
2258
  synced: stride.synced
2131
2259
  };
2132
2260
  }
2261
+ function strideHasNoFootPlant(reading) {
2262
+ return reading.inPlace && Math.abs(reading.clipGroundSpeed) <= STRIDE_GROUND_SPEED_FLOOR && Math.abs(reading.groundSpeed) > STRIDE_GROUND_SPEED_FLOOR;
2263
+ }
2133
2264
  function appliedStrideRate(reading) {
2134
2265
  return reading.synced ? reading.rate : 1;
2135
2266
  }
@@ -2148,6 +2279,8 @@ function strideFailure(assertion, observed) {
2148
2279
  code: "TN_PLAYTEST_STRIDE_UNOBSERVED",
2149
2280
  detail: "the runtime reported no stride for this clip, so neither the feet nor the ground were measured"
2150
2281
  };
2282
+ if (assertion.strideSynced !== false && strideHasNoFootPlant(reading))
2283
+ return { code: "TN_PLAYTEST_STRIDE_NO_FOOT_PLANT", detail: NO_FOOT_PLANT_DETAIL };
2151
2284
  if (assertion.strideSynced !== void 0 && reading.synced !== assertion.strideSynced)
2152
2285
  return {
2153
2286
  code: "TN_PLAYTEST_STRIDE_NOT_SYNCED",
@@ -2220,12 +2353,13 @@ function runtimeAnimationObservations(value) {
2220
2353
  const gameplay = gameplayObservations(value);
2221
2354
  return isRecord(gameplay?.animation) ? gameplay.animation : void 0;
2222
2355
  }
2223
- var STRIDE_GROUND_SPEED_FLOOR;
2356
+ var STRIDE_GROUND_SPEED_FLOOR, NO_FOOT_PLANT_DETAIL;
2224
2357
  var init_families_observation = __esm({
2225
2358
  "src/evaluators/families-observation.ts"() {
2226
2359
  init_measures();
2227
2360
  init_assertion_report();
2228
2361
  STRIDE_GROUND_SPEED_FLOOR = 1e-3;
2362
+ NO_FOOT_PLANT_DETAIL = "no foot plant found: stride sync is off";
2229
2363
  }
2230
2364
  });
2231
2365
 
@@ -2273,6 +2407,249 @@ var init_protocol = __esm({
2273
2407
  PLAYTEST_FRAME_PASS_KINDS = ["main", "shadow", "reflection", "nested"];
2274
2408
  }
2275
2409
  });
2410
+ function decideDisplayStrategy(input) {
2411
+ if (input.platform !== "linux") return { kind: "host" };
2412
+ const privateXvfb = {
2413
+ kind: "private-xvfb",
2414
+ screen: input.env.TN_XVFB_SCREEN ?? DEFAULT_XVFB_SCREEN
2415
+ };
2416
+ if (!hostDisplayRequested(input.env)) return privateXvfb;
2417
+ const display = input.env.DISPLAY;
2418
+ if (display === void 0 || display.length === 0) {
2419
+ throw new Error("TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: the requested host display requires DISPLAY.");
2420
+ }
2421
+ const available = input.displaySocketExists?.(display) ?? x11DisplayIsUsable(display, input.env);
2422
+ if (!available) {
2423
+ throw new Error(`TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: cannot connect to requested DISPLAY=${display}. Refusing to substitute a private Xvfb.`);
2424
+ }
2425
+ return { display, kind: "existing" };
2426
+ }
2427
+ function hostDisplayRequested(env) {
2428
+ const value = env[HOST_DISPLAY_ENV];
2429
+ return value === "1" || value?.toLowerCase() === "true";
2430
+ }
2431
+ function x11DisplayIsUsable(display, env) {
2432
+ const probe = spawnSync("xdpyinfo", ["-display", display], { env, stdio: "ignore", timeout: 2e3 });
2433
+ if (probe.error) {
2434
+ throw new Error(`TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: cannot verify DISPLAY=${display}: xdpyinfo ${probe.error.message}.`);
2435
+ }
2436
+ return probe.status === 0;
2437
+ }
2438
+ function childEnvForDisplay(env, display) {
2439
+ const child = { ...env };
2440
+ for (const name of STRIPPED_WAYLAND_VARS) delete child[name];
2441
+ child.DISPLAY = display;
2442
+ return child;
2443
+ }
2444
+ function runNeedsPixels(config, scenario) {
2445
+ if (config.headless !== true) return true;
2446
+ const takesScreenshot = scenario.artifacts?.screenshots !== false || scenario.steps.some(({ screenshot }) => screenshot !== void 0);
2447
+ const evaluatesVisual = (scenario.assert?.visual?.length ?? 0) > 0 || (scenario.assert?.tone?.length ?? 0) > 0;
2448
+ return takesScreenshot || evaluatesVisual || scenario.assert?.framebufferCoverage !== void 0;
2449
+ }
2450
+ async function provideDisplay(options = {}) {
2451
+ const env = options.env ?? process.env;
2452
+ const platform = options.platform ?? process.platform;
2453
+ const strategy = decideDisplayStrategy({
2454
+ displaySocketExists: options.displaySocketExists,
2455
+ env,
2456
+ platform
2457
+ });
2458
+ if (strategy.kind === "host") {
2459
+ return {
2460
+ compositor: void 0,
2461
+ display: void 0,
2462
+ env: { ...env },
2463
+ release: async () => void 0,
2464
+ strategy
2465
+ };
2466
+ }
2467
+ if (strategy.kind === "existing") {
2468
+ return {
2469
+ compositor: void 0,
2470
+ display: strategy.display,
2471
+ env: childEnvForDisplay(env, strategy.display),
2472
+ release: async () => void 0,
2473
+ strategy
2474
+ };
2475
+ }
2476
+ const commandExists2 = options.commandExists ?? defaultCommandExists;
2477
+ if (!commandExists2("Xvfb")) {
2478
+ throw new Error(
2479
+ "No usable X display is available and Xvfb is not installed, so this pixel-producing run cannot start (Debian/Ubuntu 'xvfb', Arch 'xorg-server-xvfb', Fedora 'xorg-x11-server-Xvfb'). Refusing to render blind."
2480
+ );
2481
+ }
2482
+ const spawnProcess = options.spawnProcess ?? spawn;
2483
+ const xvfb = spawnProcess("Xvfb", [
2484
+ "-displayfd",
2485
+ "3",
2486
+ "-nolisten",
2487
+ "tcp",
2488
+ // COMPOSITE and SHAPE are what a compositing manager needs before it can blend anything, and
2489
+ // the native desktop runtime refuses to attach its UI overlay to a display without one. Xvfb
2490
+ // does not enable them by default, so every native UI run on a private display reported
2491
+ // `TN_UI_OVERLAY:{"attached":false,"reason":"no compositing manager is running"}` — including
2492
+ // the starter template's own shipped native-playtests/react-hud scenario, which failed out of
2493
+ // the box on a freshly scaffolded project. A browser run does not care either way.
2494
+ "+extension",
2495
+ "COMPOSITE",
2496
+ "+extension",
2497
+ "SHAPE",
2498
+ "-screen",
2499
+ "0",
2500
+ strategy.screen
2501
+ ], { stdio: ["ignore", "ignore", "pipe", "pipe"] });
2502
+ xvfb.on?.("error", () => void 0);
2503
+ try {
2504
+ const number = await readXvfbDisplayNumber(xvfb);
2505
+ const display = `:${number}`;
2506
+ const compositor = await startCompositor(display, { commandExists: commandExists2, env, spawnProcess });
2507
+ return {
2508
+ compositor: compositor?.name,
2509
+ display,
2510
+ env: childEnvForDisplay(env, display),
2511
+ release: async () => {
2512
+ if (compositor !== void 0) await stopChild(compositor.child);
2513
+ await stopChild(xvfb);
2514
+ },
2515
+ strategy
2516
+ };
2517
+ } catch (error) {
2518
+ await stopChild(xvfb);
2519
+ throw error;
2520
+ }
2521
+ }
2522
+ async function startCompositor(display, options) {
2523
+ const choice = COMPOSITORS.find(({ name }) => options.commandExists(name));
2524
+ if (choice === void 0) return void 0;
2525
+ const child = options.spawnProcess(choice.name, [...choice.args], {
2526
+ env: { ...options.env, DISPLAY: display },
2527
+ stdio: "ignore"
2528
+ });
2529
+ let spawnFailed = false;
2530
+ child.on?.("error", () => {
2531
+ spawnFailed = true;
2532
+ });
2533
+ await new Promise((settle) => setTimeout(settle, COMPOSITOR_SETTLE_MS));
2534
+ if (spawnFailed) return void 0;
2535
+ if ((child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null) return void 0;
2536
+ return { child, name: choice.name };
2537
+ }
2538
+ async function readXvfbDisplayNumber(xvfb) {
2539
+ const report = xvfb.stdio[3];
2540
+ if (report === null || report === void 0 || typeof report.on !== "function") {
2541
+ throw new Error("Xvfb was spawned without a display-report descriptor to read.");
2542
+ }
2543
+ const stream = report;
2544
+ return new Promise((resolveDisplay, rejectDisplay) => {
2545
+ let settled = false;
2546
+ const finish = (settle) => {
2547
+ if (settled) return;
2548
+ settled = true;
2549
+ clearTimeout(timer);
2550
+ stream.removeListener("data", onData);
2551
+ stream.removeListener("close", onClose);
2552
+ settle();
2553
+ };
2554
+ const onData = (chunk) => {
2555
+ const number = Number.parseInt(String(chunk).trim(), 10);
2556
+ if (Number.isInteger(number) && number >= 0) finish(() => resolveDisplay(number));
2557
+ };
2558
+ const onClose = () => finish(() => rejectDisplay(new Error("Xvfb exited before it reported a display.")));
2559
+ const timer = setTimeout(() => finish(() => {
2560
+ rejectDisplay(new Error(`Xvfb did not report a display within ${XVFB_DISPLAY_TIMEOUT_MS}ms.`));
2561
+ }), XVFB_DISPLAY_TIMEOUT_MS);
2562
+ stream.on("data", onData);
2563
+ stream.on("close", onClose);
2564
+ });
2565
+ }
2566
+ async function stopChild(child) {
2567
+ const exitedAlready = () => (child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null;
2568
+ if (exitedAlready()) return;
2569
+ child.kill("SIGTERM");
2570
+ const started = Date.now();
2571
+ while (Date.now() - started < 1e3 && !exitedAlready()) {
2572
+ await new Promise((resolveWait) => setTimeout(resolveWait, 25));
2573
+ }
2574
+ if (!exitedAlready()) child.kill("SIGKILL");
2575
+ }
2576
+ function defaultCommandExists(command) {
2577
+ const paths = (process.env.PATH ?? "").split(":").filter((segment) => segment.length > 0);
2578
+ return paths.some((directory) => existsSync(join(directory, command)));
2579
+ }
2580
+ var DEFAULT_XVFB_SCREEN, HOST_DISPLAY_ENV, STRIPPED_WAYLAND_VARS, COMPOSITORS, COMPOSITOR_SETTLE_MS, XVFB_DISPLAY_TIMEOUT_MS;
2581
+ var init_captureEnvironment = __esm({
2582
+ "src/runner/captureEnvironment.ts"() {
2583
+ DEFAULT_XVFB_SCREEN = "1600x900x24";
2584
+ HOST_DISPLAY_ENV = "TN_PLAYTEST_HOST_DISPLAY";
2585
+ STRIPPED_WAYLAND_VARS = ["WAYLAND_DISPLAY", "WAYLAND_SOCKET", "XDG_SESSION_TYPE"];
2586
+ COMPOSITORS = [
2587
+ { args: ["-n"], name: "xcompmgr" },
2588
+ { args: [], name: "picom" },
2589
+ { args: [], name: "compton" }
2590
+ ];
2591
+ COMPOSITOR_SETTLE_MS = 250;
2592
+ XVFB_DISPLAY_TIMEOUT_MS = 3e4;
2593
+ }
2594
+ });
2595
+ function frameDisplay(env = process.env, platform = process.platform) {
2596
+ return platform === "linux" && !hostDisplayRequested(env) ? "virtual" : "real";
2597
+ }
2598
+ function foreignGpuProcesses(ownPid = process.pid, procRoot = "/proc", platform = process.platform) {
2599
+ if (platform !== "linux") return [];
2600
+ const read2 = (pid, file) => {
2601
+ try {
2602
+ return readFileSync(join(procRoot, pid, file), "utf8");
2603
+ } catch {
2604
+ return void 0;
2605
+ }
2606
+ };
2607
+ const parentOf = (pid) => {
2608
+ const stat4 = read2(String(pid), "stat");
2609
+ const ppid = stat4 === void 0 ? void 0 : Number(stat4.slice(stat4.lastIndexOf(")") + 2).split(" ")[1]);
2610
+ return ppid === void 0 || !Number.isSafeInteger(ppid) ? void 0 : ppid;
2611
+ };
2612
+ const ours = (pid) => {
2613
+ for (let current = pid, hops = 0; current !== void 0 && current > 1 && hops < 64; hops++) {
2614
+ if (current === ownPid) return true;
2615
+ current = parentOf(current);
2616
+ }
2617
+ return false;
2618
+ };
2619
+ return readdirSync(procRoot).filter((entry) => {
2620
+ const argv = /^\d+$/u.test(entry) ? (read2(entry, "cmdline") ?? "").split("\0") : [];
2621
+ return argv.includes("--type=gpu-process") && (argv[0] ?? "").includes("ms-playwright");
2622
+ }).map(Number).filter((pid) => !ours(pid)).sort((a, b) => a - b);
2623
+ }
2624
+ function gpuWindows(consoleLines) {
2625
+ const windows = [];
2626
+ let samples;
2627
+ for (const line of consoleLines) {
2628
+ if (typeof line !== "string") continue;
2629
+ const at = line.indexOf(FRAME_BUDGET);
2630
+ if (at === -1) continue;
2631
+ let report;
2632
+ try {
2633
+ report = JSON.parse(line.slice(at + FRAME_BUDGET.length));
2634
+ } catch {
2635
+ continue;
2636
+ }
2637
+ const p95 = report.gpu?.p95;
2638
+ if (typeof p95 === "number" && Number.isFinite(p95) && (typeof report.gpu?.samples !== "number" || report.gpu.samples > 0)) {
2639
+ windows.push(p95);
2640
+ samples = typeof report.gpu?.samples === "number" ? report.gpu.samples : void 0;
2641
+ }
2642
+ }
2643
+ return windows.length === 0 ? { windows } : { p95: windows[windows.length - 1], ...samples === void 0 ? {} : { samples }, windows };
2644
+ }
2645
+ var FRAME_BUDGET, MIN_GPU_SAMPLES;
2646
+ var init_frame_cost = __esm({
2647
+ "src/evaluators/frame-cost.ts"() {
2648
+ init_captureEnvironment();
2649
+ FRAME_BUDGET = "TN_FRAME_BUDGET:";
2650
+ MIN_GPU_SAMPLES = 3;
2651
+ }
2652
+ });
2276
2653
 
2277
2654
  // src/evaluators/render-evidence.ts
2278
2655
  function projectedPixelsForEntity(snapshot, entity, viewport) {
@@ -2291,7 +2668,7 @@ function countMatchingEntries(effectLog, tokens) {
2291
2668
  return tokens.every((token) => text.includes(token));
2292
2669
  }).length;
2293
2670
  }
2294
- function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2671
+ function evaluatePerformanceAssertion(assertion, series, sourcePath, lane) {
2295
2672
  const samples = series ?? [];
2296
2673
  const validSamples = samples.length > 0 && samples.every(isRuntimeDiagnosticsSample);
2297
2674
  const observed = validSamples ? samples : [];
@@ -2332,13 +2709,17 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2332
2709
  });
2333
2710
  };
2334
2711
  if (assertion.maxFrameMsP95 !== void 0) {
2335
- addBound(
2336
- "performance.maxFrameMsP95",
2337
- assertion.maxFrameMsP95,
2338
- frameMsP95,
2339
- "ms",
2340
- samplesPass && frameMsP95 !== void 0 && frameMsP95 <= assertion.maxFrameMsP95
2341
- );
2712
+ if (lane === void 0) {
2713
+ addBound(
2714
+ "performance.maxFrameMsP95",
2715
+ assertion.maxFrameMsP95,
2716
+ frameMsP95,
2717
+ "ms",
2718
+ samplesPass && frameMsP95 !== void 0 && frameMsP95 <= assertion.maxFrameMsP95
2719
+ );
2720
+ } else {
2721
+ emitFrameBound(assertion.maxFrameMsP95, frameMsP95, observed, samples.length, samplesPass, lane, results, diagnostics, path2, sourcePath);
2722
+ }
2342
2723
  }
2343
2724
  if (assertion.maxDrawCalls !== void 0) {
2344
2725
  addBound(
@@ -2350,17 +2731,26 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2350
2731
  );
2351
2732
  }
2352
2733
  if (assertion.minFps !== void 0) {
2353
- const exact = fpsFromFrameTimes(frameTimes);
2354
- const observed2 = exact === void 0 ? void 0 : Math.floor(exact * 100) / 100;
2734
+ const onXvfb = lane?.display === "virtual" && lane.target !== "android" && lane.target !== "ios";
2735
+ const costP95 = onXvfb ? frameCost(observed, samples.length, lane).costP95 : void 0;
2736
+ const virtual = costP95 !== void 0 && costP95 > 0;
2737
+ const exact = virtual ? 1e3 / costP95 : fpsFromFrameTimes(frameTimes);
2738
+ const observedFps = exact === void 0 ? void 0 : Math.floor(exact * 100) / 100;
2355
2739
  const pass = samplesPass && exact !== void 0 && exact >= assertion.minFps;
2356
2740
  results.push({
2357
- details: { actual: observed2 ?? null, expected: assertion.minFps, sampleCount: samples.length, unit: "fps" },
2741
+ details: {
2742
+ actual: observedFps ?? null,
2743
+ expected: assertion.minFps,
2744
+ sampleCount: samples.length,
2745
+ unit: "fps",
2746
+ ...virtual ? { basis: "frame-cost", interval: { gated: false, p95: frameMsP95 ?? null, reason: XVFB_CADENCE } } : {}
2747
+ },
2358
2748
  id: "performance.minFps",
2359
2749
  pass
2360
2750
  });
2361
2751
  if (!pass) diagnostics.push({
2362
2752
  code: "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
2363
- message: `performance.minFps expected at least ${assertion.minFps} fps, observed ${observed2 ?? "unavailable"}.`,
2753
+ message: `performance.minFps expected at least ${assertion.minFps} fps, observed ${observedFps ?? "unavailable"}${virtual ? " from frame cost on a virtual display" : ""}.`,
2364
2754
  observedRuntimePath: path2,
2365
2755
  severity: "error",
2366
2756
  sourcePath,
@@ -2425,6 +2815,56 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2425
2815
  addPassBound("triangles", kind, ceiling);
2426
2816
  return { assertions: results, diagnostics };
2427
2817
  }
2818
+ function frameCost(observed, sampleCount, lane) {
2819
+ const cpu = observed.flatMap(({ phases }) => phases === void 0 || typeof phases.update !== "number" || typeof phases.render !== "number" ? [] : [phases.update + phases.render]);
2820
+ const hitches = observed.filter(({ frameMs, phases }) => phases === void 0 && frameMs >= HITCH_MS).length;
2821
+ const cpuP95 = cpu.length > 0 && cpu.length + hitches === sampleCount ? nearestRank(cpu, 0.95) : void 0;
2822
+ const costP95 = cpuP95 === void 0 || lane.gpuP95 === void 0 ? void 0 : Math.max(cpuP95, lane.gpuP95);
2823
+ return { costP95, cpuP95, hitches };
2824
+ }
2825
+ function emitFrameBound(ceiling, intervalP95, observed, sampleCount, samplesPass, lane, results, diagnostics, path2, sourcePath) {
2826
+ const { costP95, cpuP95, hitches } = frameCost(observed, sampleCount, lane);
2827
+ const missing = [
2828
+ ...cpuP95 === void 0 ? ["the CPU frame split (phases.update and phases.render)"] : [],
2829
+ ...lane.gpuP95 === void 0 ? ["the GPU time (a TN_FRAME_BUDGET window with a gpu reading)"] : []
2830
+ ];
2831
+ const virtual = lane.display === "virtual";
2832
+ const costPass = costP95 !== void 0 && costP95 <= ceiling;
2833
+ const intervalPass = virtual || intervalP95 !== void 0 && intervalP95 <= ceiling;
2834
+ const thinGpu = lane.gpuP95 !== void 0 && !(lane.gpuSamples !== void 0 && lane.gpuSamples >= MIN_GPU_SAMPLES);
2835
+ const pass = samplesPass && costPass && intervalPass && !thinGpu;
2836
+ const round4 = (value) => value === void 0 ? null : Math.round(value * 100) / 100;
2837
+ results.push({
2838
+ details: {
2839
+ actual: round4(virtual || !costPass ? costP95 : intervalP95),
2840
+ cost: { cpuP95: round4(cpuP95), gpuP95: round4(lane.gpuP95), gpuSamples: lane.gpuSamples ?? null, hitchFrames: hitches, p95: round4(costP95) },
2841
+ display: lane.display,
2842
+ expected: ceiling,
2843
+ interval: virtual ? { gated: false, p95: round4(intervalP95), reason: XVFB_CADENCE } : { gated: true, p95: round4(intervalP95) },
2844
+ sampleCount,
2845
+ unit: "ms"
2846
+ },
2847
+ id: "performance.maxFrameMsP95",
2848
+ pass
2849
+ });
2850
+ if (pass) return;
2851
+ const foreign = lane.foreignGpu ?? [];
2852
+ const contended = missing.length === 0 && !costPass && foreign.length > 0;
2853
+ const detail = missing.length > 0 ? `cannot be judged: the run did not measure ${missing.join(" or ")}` : !costPass ? `cost p95 ${round4(costP95)} ms (CPU ${round4(cpuP95)}, GPU ${round4(lane.gpuP95)}) is over ${ceiling} ms${contended ? ` while ${foreign.length} other GPU process${foreign.length === 1 ? "" : "es"} ran (${foreign.join(", ")})` : ""}` : `rAF interval p95 ${round4(intervalP95)} ms on a real display is over ${ceiling} ms`;
2854
+ const fewSamples = missing.length === 0 && costPass && thinGpu;
2855
+ diagnostics.push({
2856
+ code: fewSamples ? "TN_PLAYTEST_PERF_FEW_GPU_SAMPLES" : "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
2857
+ message: `performance.maxFrameMsP95 ${fewSamples ? fewGpuSamples(lane.gpuSamples) : detail}.`,
2858
+ observedRuntimePath: path2,
2859
+ severity: "error",
2860
+ sourcePath,
2861
+ suggestion: fewSamples ? "Keep the scene moving through the judged window (hold a move input or loop a route): the engine skips static frames and takes no GPU sample on them." : contended ? "Other GPU work shared this measurement, so the cost holds its load too: rerun this scenario when they exit, before you change the game. A contended number is not the game's cost, so do not trade its look to pass it." : missing.length > 0 ? "Keep the engine frame budget installed and run on an adapter with timestamp queries: an unmeasured cost is not a zero." : "Read the TN_FRAME_BUDGET marker for this run: it names which frame phase or GPU pass owns the time."
2862
+ });
2863
+ }
2864
+ function fewGpuSamples(samples) {
2865
+ const held = samples === void 0 ? "reports no sample count" : `holds ${samples} GPU sample${samples === 1 ? "" : "s"}`;
2866
+ return `cannot be judged: the latest GPU window ${held}, under the minimum of ${MIN_GPU_SAMPLES}`;
2867
+ }
2428
2868
  function isRuntimeDiagnosticsSample(value) {
2429
2869
  if (!isRecord(value) || typeof value.frameMs !== "number" || !Number.isFinite(value.frameMs) || value.frameMs <= 0) {
2430
2870
  return false;
@@ -2617,11 +3057,15 @@ function minimumResolvedDistance(effectLog, effectLogSeries, entityId, target, b
2617
3057
  if (baseline !== void 0 && atStep === void 0) positions2.unshift(baseline);
2618
3058
  return positions2.length === 0 ? void 0 : Math.min(...positions2.map((position) => vectorDistance(position, target)));
2619
3059
  }
3060
+ var HITCH_MS, XVFB_CADENCE;
2620
3061
  var init_render_evidence = __esm({
2621
3062
  "src/evaluators/render-evidence.ts"() {
2622
3063
  init_protocol();
2623
3064
  init_measures();
3065
+ init_frame_cost();
2624
3066
  init_assertion_report();
3067
+ HITCH_MS = 2e3;
3068
+ XVFB_CADENCE = "display cadence, not gated: the runner's private Xvfb paces frames on its own timer, not the game's cost";
2625
3069
  }
2626
3070
  });
2627
3071
 
@@ -2759,6 +3203,17 @@ function emitEvidenceFamilies(ctx) {
2759
3203
  const pass = observed !== void 0 && observed.nonblankPixelRatio >= minimum;
2760
3204
  assertions.push({ id: `visual.${index}.region`, pass, details: { after: pass, expected: { equals: true }, minimum, observed: observed?.nonblankPixelRatio } });
2761
3205
  if (!pass) diagnostics.push({ code: "TN_PLAYTEST_REGION_BLANK", message: `Screenshot region at (${staticRegion.x}, ${staticRegion.y}) did not meet nonblank ratio ${minimum}.`, severity: "error", suggestion: "Check camera framing and whether expected geometry renders in the asserted region." });
3206
+ if (staticRegion.minSharpness !== void 0) {
3207
+ const sharpness = observed?.sharpness;
3208
+ const sharpPass = sharpness !== void 0 && sharpness >= staticRegion.minSharpness;
3209
+ assertions.push({ id: `visual.${index}.region.sharpness`, pass: sharpPass, details: { minimum: staticRegion.minSharpness, observed: sharpness ?? null } });
3210
+ if (!sharpPass) diagnostics.push({
3211
+ code: "TN_PLAYTEST_REGION_BLURRED",
3212
+ message: `Screenshot region at (${staticRegion.x}, ${staticRegion.y}) measured sharpness ${sharpness === void 0 ? "unavailable" : sharpness.toFixed(3)}, below the floor ${staticRegion.minSharpness} (luminance Laplacian variance at full resolution over half resolution).`,
3213
+ severity: "error",
3214
+ suggestion: "A post stage that smears the frame (motion blur at rest, a blur or low-resolution pass) or a surface with no detail drops this. Capture the frame and fix the stage; do not lower the floor to pass."
3215
+ });
3216
+ }
2762
3217
  if (staticRegion.minDarkPixelRatio !== void 0) {
2763
3218
  const darkPass = observed?.darkPixelRatio !== void 0 && observed.darkPixelRatio >= staticRegion.minDarkPixelRatio;
2764
3219
  assertions.push({
@@ -2827,12 +3282,14 @@ function emitMovementEvidence(ctx) {
2827
3282
  scenarioAssertions.diagnostics,
2828
3283
  input.report.target
2829
3284
  );
3285
+ const warningTexts = perfWarnings((input.report.observations?.console ?? []).map(({ text }) => text));
2830
3286
  const policyDiagnostics = evaluateDiagnosticsPolicy(input.report, diagnosticsPolicy);
2831
3287
  diagnostics.push(...policyDiagnostics);
2832
3288
  assertions.push({
2833
3289
  details: {
2834
3290
  consoleErrors: consoleErrors(input.report.observations?.console ?? []).length,
2835
3291
  networkErrors: input.report.observations?.network.length ?? 0,
3292
+ ...warningTexts.length === 0 ? {} : { perfWarnings: warningTexts },
2836
3293
  policy: diagnosticsPolicy,
2837
3294
  runtimeDiagnostics: runtimeDiagnostics(input.report.observations?.runtimeDiagnostics).length
2838
3295
  },
@@ -3243,7 +3700,8 @@ function emitMovementEvidence(ctx) {
3243
3700
  }
3244
3701
  for (const assertion of scenarioAssertions.animation ?? []) {
3245
3702
  const entity = assertion.entity ?? input.scenario.subject ?? input.report.entity;
3246
- const runtime = runtimeAnimationObservations(input.report.observations?.runtimeObservations);
3703
+ const stepAnimation = runtimeGameplayAtStep(input.report.observations?.runtimeObservations, assertion.atStep)?.animation;
3704
+ const runtime = assertion.atStep === void 0 ? runtimeAnimationObservations(input.report.observations?.runtimeObservations) : isRecord(stepAnimation) ? stepAnimation : void 0;
3247
3705
  if (runtime !== void 0) {
3248
3706
  const observed = isRecord(runtime[entity]) ? runtime[entity] : void 0;
3249
3707
  const clip = typeof observed?.clip === "string" ? observed.clip : void 0;
@@ -3349,6 +3807,7 @@ var init_movement_evidence = __esm({
3349
3807
  "src/evaluators/movement-evidence.ts"() {
3350
3808
  init_assertion_schema();
3351
3809
  init_assertion_report();
3810
+ init_perf_warnings();
3352
3811
  init_helpers();
3353
3812
  }
3354
3813
  });
@@ -3623,19 +4082,156 @@ var init_parity_evidence = __esm({
3623
4082
  }
3624
4083
  });
3625
4084
 
4085
+ // src/evaluators/adapter-class.ts
4086
+ function classifyAdapter(report) {
4087
+ const capture = report.capture;
4088
+ if (capture === void 0 || capture.rendererKind !== "webgpu") return {};
4089
+ if (adapterIdentity(capture.adapter) === void 0) return {};
4090
+ const software = softwareAdapterName(capture.adapter);
4091
+ if (software !== void 0) return { adapterClass: "software", softwareAdapter: software };
4092
+ const gpuFamily = gpuFamilyOf(capture.adapter);
4093
+ return gpuFamily === void 0 ? { adapterClass: "hardware" } : { adapterClass: "hardware", gpuFamily };
4094
+ }
4095
+ function adapterIdentity(adapter) {
4096
+ if (adapter === void 0) return void 0;
4097
+ for (const key of ADAPTER_IDENTITY_KEYS) {
4098
+ const value = adapter[key];
4099
+ if (typeof value === "string" && value.trim() !== "") return value;
4100
+ }
4101
+ return void 0;
4102
+ }
4103
+ function gpuFamilyOf(adapter) {
4104
+ if (adapter === void 0) return void 0;
4105
+ const field = (key) => {
4106
+ const value = adapter[key];
4107
+ return typeof value === "string" ? value : "";
4108
+ };
4109
+ const fields = {
4110
+ architecture: field("architecture"),
4111
+ description: field("description"),
4112
+ device: field("device"),
4113
+ vendor: field("vendor")
4114
+ };
4115
+ for (const rule of FAMILY_RULES) {
4116
+ const family = rule(fields);
4117
+ if (family !== void 0) return family;
4118
+ }
4119
+ return void 0;
4120
+ }
4121
+ function adapterFieldsFromIdentity(identity) {
4122
+ if (typeof identity !== "string") return void 0;
4123
+ const prefix = "webgpu:";
4124
+ if (!identity.startsWith(prefix)) return void 0;
4125
+ const fields = /* @__PURE__ */ Object.create(null);
4126
+ for (const pair of identity.slice(prefix.length).split("|")) {
4127
+ const separator = pair.indexOf("=");
4128
+ if (separator <= 0) return void 0;
4129
+ const key = pair.slice(0, separator);
4130
+ if (!ADAPTER_IDENTITY_KEYS.includes(key) || Object.hasOwn(fields, key)) {
4131
+ return void 0;
4132
+ }
4133
+ let value;
4134
+ try {
4135
+ value = decodeURIComponent(pair.slice(separator + 1));
4136
+ } catch {
4137
+ return void 0;
4138
+ }
4139
+ if (value.trim() === "") return void 0;
4140
+ fields[key] = value;
4141
+ }
4142
+ if (Object.keys(fields).length === 0) return void 0;
4143
+ return fields;
4144
+ }
4145
+ function nativeCaptureProvenance(census, target, viewport) {
4146
+ if (census === void 0 || census === null || typeof census !== "object" || Array.isArray(census)) return void 0;
4147
+ const adapterRecord = census.adapter;
4148
+ if (adapterRecord === void 0 || adapterRecord === null || typeof adapterRecord !== "object" || Array.isArray(adapterRecord)) return void 0;
4149
+ const adapter = adapterFieldsFromIdentity(adapterRecord.identity);
4150
+ if (adapter === void 0) return void 0;
4151
+ return {
4152
+ adapter,
4153
+ // A native launch carries no browser command line; there is no argument list to report and
4154
+ // inventing one would be a flag nobody can check.
4155
+ browserArgs: [],
4156
+ captureMethod: "device.screenshot",
4157
+ rendererKind: "webgpu",
4158
+ target,
4159
+ viewport
4160
+ };
4161
+ }
4162
+ var ADAPTER_IDENTITY_KEYS, MALI_MODEL, ADRENO_MODEL, AMD_INTEGRATED, INTEL_DISCRETE, FAMILY_RULES;
4163
+ var init_adapter_class = __esm({
4164
+ "src/evaluators/adapter-class.ts"() {
4165
+ init_browser();
4166
+ ADAPTER_IDENTITY_KEYS = ["architecture", "description", "device", "vendor"];
4167
+ MALI_MODEL = /\bmali[\s_-]*g?[\s-]*(\d{2,3})/i;
4168
+ ADRENO_MODEL = /\badreno\W*(?:tm\W*)?(\d)(\d\d|xx)/i;
4169
+ AMD_INTEGRATED = /radeon(?:\(tm\))?\s+(?:graphics|\d{3}m)\b/i;
4170
+ INTEL_DISCRETE = /\barc\b|xe2?-hpg|battlemage|alchemist/i;
4171
+ FAMILY_RULES = [
4172
+ ({ architecture, description, device }) => {
4173
+ const number = [description, device, architecture].map((value) => MALI_MODEL.exec(value)?.[1]).find((value) => value !== void 0);
4174
+ if (number === void 0) return void 0;
4175
+ const model = Number(number);
4176
+ if (model >= 710) return "mobile-high";
4177
+ return model < 57 || model === 71 || model === 72 ? "mobile-low" : "mobile-mid";
4178
+ },
4179
+ ({ architecture, vendor }) => {
4180
+ if (!/\barm\b/i.test(vendor)) return void 0;
4181
+ if (/midgard|bifrost/i.test(architecture)) return "mobile-low";
4182
+ if (/valhall/i.test(architecture)) return "mobile-mid";
4183
+ return /5th-?gen|immortalis/i.test(architecture) ? "mobile-high" : void 0;
4184
+ },
4185
+ ({ architecture, description, device }) => {
4186
+ const match = [description, device, architecture].map((value) => ADRENO_MODEL.exec(value)).find((value) => value !== null && value !== void 0);
4187
+ if (match === null || match === void 0) return void 0;
4188
+ const generation = Number(match[1]);
4189
+ if (generation <= 4) return "mobile-low";
4190
+ if (generation === 5) return "mobile-mid";
4191
+ if (generation === 6) return match[2] !== "xx" && Number(match[2]) >= 30 ? "mobile-high" : "mobile-mid";
4192
+ return "mobile-high";
4193
+ },
4194
+ ({ architecture, description, device, vendor }) => /nvidia/i.test(vendor) && ![architecture, description, device].some((value) => /tegra/i.test(value)) ? "discrete" : void 0,
4195
+ ({ architecture, description, device, vendor }) => {
4196
+ if (!/intel/i.test(vendor)) return void 0;
4197
+ return [architecture, description, device].some((value) => INTEL_DISCRETE.test(value)) ? "discrete" : "integrated";
4198
+ },
4199
+ // An APU and a card share an architecture name, so an AMD adapter that names no iGPU is `discrete`.
4200
+ ({ description, vendor }) => /\b(?:amd|ati)\b/i.test(vendor) ? AMD_INTEGRATED.test(description) ? "integrated" : "discrete" : void 0
4201
+ ];
4202
+ }
4203
+ });
4204
+
3626
4205
  // src/evaluators/perf-signals-world.ts
4206
+ function gpuLane(consoleTexts) {
4207
+ const { p95, samples } = gpuWindows(consoleTexts);
4208
+ return p95 === void 0 ? {} : { gpuP95: p95, ...samples === void 0 ? {} : { gpuSamples: samples } };
4209
+ }
3627
4210
  function emitPerfSignalsWorld(ctx) {
3628
4211
  const { assertions, diagnostics } = ctx;
3629
4212
  const { input, scenarioAssertions } = ctx;
3630
4213
  emitTerrainResidency(input.report.observations?.components?.terrain, assertions, diagnostics);
3631
4214
  if (scenarioAssertions.performance !== void 0) {
4215
+ const budget = frameBudget(scenarioAssertions.performance.maxFrameMsP95, classifyAdapter(input.report), scenarioAssertions.performance.maxFrameMsReason);
3632
4216
  const result = evaluatePerformanceAssertion(
3633
- scenarioAssertions.performance,
4217
+ budget.maxFrameMsP95 === void 0 ? scenarioAssertions.performance : { ...scenarioAssertions.performance, maxFrameMsP95: budget.maxFrameMsP95 },
3634
4218
  input.report.observations?.performanceSeries,
3635
- input.scenario.sourcePath
4219
+ input.scenario.sourcePath,
4220
+ { display: frameDisplay(), target: input.report.target, foreignGpu: foreignGpuProcesses(), ...gpuLane((input.report.observations?.console ?? []).map(({ text }) => text)) }
3636
4221
  );
3637
- assertions.push(...result.assertions);
4222
+ assertions.push(...result.assertions.map((row) => row.id === "performance.samples" || row.id === "performance.maxFrameMsP95" ? { ...row, details: { ...row.details, frameBudget: budget } } : row));
3638
4223
  diagnostics.push(...result.diagnostics);
4224
+ if (budget.unmeasurable === true) {
4225
+ assertions.push({ details: { frameBudget: budget }, id: "performance.maxFrameMsP95", pass: false });
4226
+ diagnostics.push({
4227
+ code: "TN_PLAYTEST_PERFORMANCE_UNMEASURABLE",
4228
+ message: `performance.maxFrameMsP95 cannot be judged: ${budget.reason}.`,
4229
+ observedRuntimePath: `${input.scenario.sourcePath ?? "playtest"}/observations.json/performanceSeries`,
4230
+ severity: "error",
4231
+ sourcePath: input.scenario.sourcePath,
4232
+ suggestion: "Run the scenario on a hardware GPU, or set maxFrameMsP95 with a maxFrameMsReason that names the adapter."
4233
+ });
4234
+ }
3639
4235
  }
3640
4236
  for (const assertion of scenarioAssertions.resources ?? []) {
3641
4237
  if (assertion.anyOf !== void 0) {
@@ -3679,7 +4275,7 @@ function emitPerfSignalsWorld(ctx) {
3679
4275
  const samples = assertion.atSteps.map((expected) => {
3680
4276
  const sample = (input.report.observations?.resourceSeries ?? []).find((candidate) => candidate.label === expected.label);
3681
4277
  const value = readPath(sample?.snapshots[assertion.id], assertion.path);
3682
- const pass2 = sample !== void 0 && (!Object.hasOwn(expected, "equals") || jsonEqual(value, expected.equals)) && (expected.textIncludes === void 0 || String(textValue(value)).includes(expected.textIncludes));
4278
+ const pass2 = sample !== void 0 && (!Object.hasOwn(expected, "equals") || jsonEqual(value, expected.equals)) && (expected.lte === void 0 || typeof value === "number" && value <= expected.lte) && (expected.textIncludes === void 0 || String(textValue(value)).includes(expected.textIncludes));
3683
4279
  return { expected, pass: pass2, value };
3684
4280
  });
3685
4281
  const pass = samples.every((sample) => sample.pass);
@@ -3764,10 +4360,27 @@ function emitTerrainResidency(component, assertions, diagnostics) {
3764
4360
  suggestion: "Expose TerrainTiles.debug() through the terrain entity and inspect the residency counters."
3765
4361
  });
3766
4362
  }
4363
+ function frameBudget(explicit, adapter, reason) {
4364
+ const identity = {
4365
+ ...adapter.adapterClass === void 0 ? {} : { adapterClass: adapter.adapterClass },
4366
+ ...adapter.gpuFamily === void 0 ? {} : { gpuFamily: adapter.gpuFamily }
4367
+ };
4368
+ if (explicit !== void 0) {
4369
+ return { ...identity, maxFrameMsP95: explicit, reason: `maxFrameMsP95 set in the scenario overrides ${FRAME_BUDGET_MS} ms${reason === void 0 ? "" : `: ${reason}`}`, source: "scenario" };
4370
+ }
4371
+ if (adapter.adapterClass === "software") {
4372
+ return { ...identity, reason: `software adapter ${adapter.softwareAdapter ?? ""} is unmeasurable: it cannot carry a frame rate`.replace(" ", " "), source: "adapter", unmeasurable: true };
4373
+ }
4374
+ return { ...identity, maxFrameMsP95: FRAME_BUDGET_MS, reason: `one 60 Hz frame (${FRAME_BUDGET_MS} ms) on every tier`, source: "adapter" };
4375
+ }
4376
+ var FRAME_BUDGET_MS;
3767
4377
  var init_perf_signals_world = __esm({
3768
4378
  "src/evaluators/perf-signals-world.ts"() {
3769
4379
  init_assertion_report();
4380
+ init_adapter_class();
4381
+ init_frame_cost();
3770
4382
  init_helpers();
4383
+ FRAME_BUDGET_MS = 16.7;
3771
4384
  }
3772
4385
  });
3773
4386
 
@@ -4272,153 +4885,33 @@ function emitWorldTopology(value, assertions, diagnostics) {
4272
4885
  fail2(error instanceof Error ? error.message : String(error));
4273
4886
  }
4274
4887
  }
4275
- var WORLD_TOPOLOGY_METRIC_FAILURES, WORLD_TOPOLOGY_MEASUREMENT_SIZE, DEFAULT_WORLD_TOPOLOGY_THRESHOLDS;
4276
- var init_world_gameplay = __esm({
4277
- "src/evaluators/world-gameplay.ts"() {
4278
- init_assertion_report();
4279
- init_helpers();
4280
- WORLD_TOPOLOGY_METRIC_FAILURES = {
4281
- directionalAnisotropy: "directional-anisotropy",
4282
- powerSpectrumSlope: "power-spectrum-slope",
4283
- reliefFieldEdge: "relief-field-edge",
4284
- median64mRelief: "median-64m-relief",
4285
- maxHortonStrahlerOrder: "horton-strahler-order",
4286
- profileCurvatureExcessKurtosis: "curvature-excess-kurtosis",
4287
- effectiveVertexDensityPerKm2: "effective-vertex-density",
4288
- slopeTailAbove30Degrees: "slope-tail-above-30-degrees"
4289
- };
4290
- WORLD_TOPOLOGY_MEASUREMENT_SIZE = 1024;
4291
- DEFAULT_WORLD_TOPOLOGY_THRESHOLDS = {
4292
- maxDirectionalAnisotropy: 0.1,
4293
- minPowerSpectrumSlope: 2.5,
4294
- maxPowerSpectrumSlope: 5,
4295
- minReliefFieldEdge: 0.1,
4296
- maxMedian64mRelief: 0.25,
4297
- minHortonStrahlerOrder: 5,
4298
- minProfileCurvatureExcessKurtosis: 5,
4299
- minEffectiveVertexDensityPerKm2: 5e5,
4300
- minSlopeTailAbove30Degrees: 0.1
4301
- };
4302
- }
4303
- });
4304
-
4305
- // src/evaluators/adapter-class.ts
4306
- function classifyAdapter(report) {
4307
- const capture = report.capture;
4308
- if (capture === void 0 || capture.rendererKind !== "webgpu") return {};
4309
- if (adapterIdentity(capture.adapter) === void 0) return {};
4310
- const software = softwareAdapterName(capture.adapter);
4311
- if (software !== void 0) return { adapterClass: "software", softwareAdapter: software };
4312
- const gpuFamily = gpuFamilyOf(capture.adapter);
4313
- return gpuFamily === void 0 ? { adapterClass: "hardware" } : { adapterClass: "hardware", gpuFamily };
4314
- }
4315
- function adapterIdentity(adapter) {
4316
- if (adapter === void 0) return void 0;
4317
- for (const key of ADAPTER_IDENTITY_KEYS) {
4318
- const value = adapter[key];
4319
- if (typeof value === "string" && value.trim() !== "") return value;
4320
- }
4321
- return void 0;
4322
- }
4323
- function gpuFamilyOf(adapter) {
4324
- if (adapter === void 0) return void 0;
4325
- const field = (key) => {
4326
- const value = adapter[key];
4327
- return typeof value === "string" ? value : "";
4328
- };
4329
- const fields = {
4330
- architecture: field("architecture"),
4331
- description: field("description"),
4332
- device: field("device"),
4333
- vendor: field("vendor")
4334
- };
4335
- for (const rule of FAMILY_RULES) {
4336
- const family = rule(fields);
4337
- if (family !== void 0) return family;
4338
- }
4339
- return void 0;
4340
- }
4341
- function adapterFieldsFromIdentity(identity) {
4342
- if (typeof identity !== "string") return void 0;
4343
- const prefix = "webgpu:";
4344
- if (!identity.startsWith(prefix)) return void 0;
4345
- const fields = /* @__PURE__ */ Object.create(null);
4346
- for (const pair of identity.slice(prefix.length).split("|")) {
4347
- const separator = pair.indexOf("=");
4348
- if (separator <= 0) return void 0;
4349
- const key = pair.slice(0, separator);
4350
- if (!ADAPTER_IDENTITY_KEYS.includes(key) || Object.hasOwn(fields, key)) {
4351
- return void 0;
4352
- }
4353
- let value;
4354
- try {
4355
- value = decodeURIComponent(pair.slice(separator + 1));
4356
- } catch {
4357
- return void 0;
4358
- }
4359
- if (value.trim() === "") return void 0;
4360
- fields[key] = value;
4361
- }
4362
- if (Object.keys(fields).length === 0) return void 0;
4363
- return fields;
4364
- }
4365
- function nativeCaptureProvenance(census, target, viewport) {
4366
- if (census === void 0 || census === null || typeof census !== "object" || Array.isArray(census)) return void 0;
4367
- const adapterRecord = census.adapter;
4368
- if (adapterRecord === void 0 || adapterRecord === null || typeof adapterRecord !== "object" || Array.isArray(adapterRecord)) return void 0;
4369
- const adapter = adapterFieldsFromIdentity(adapterRecord.identity);
4370
- if (adapter === void 0) return void 0;
4371
- return {
4372
- adapter,
4373
- // A native launch carries no browser command line; there is no argument list to report and
4374
- // inventing one would be a flag nobody can check.
4375
- browserArgs: [],
4376
- captureMethod: "device.screenshot",
4377
- rendererKind: "webgpu",
4378
- target,
4379
- viewport
4380
- };
4381
- }
4382
- var ADAPTER_IDENTITY_KEYS, MALI_MODEL, ADRENO_MODEL, AMD_INTEGRATED, INTEL_DISCRETE, FAMILY_RULES;
4383
- var init_adapter_class = __esm({
4384
- "src/evaluators/adapter-class.ts"() {
4385
- init_browser();
4386
- ADAPTER_IDENTITY_KEYS = ["architecture", "description", "device", "vendor"];
4387
- MALI_MODEL = /\bmali[\s_-]*g?[\s-]*(\d{2,3})/i;
4388
- ADRENO_MODEL = /\badreno\W*(?:tm\W*)?(\d)(\d\d|xx)/i;
4389
- AMD_INTEGRATED = /radeon(?:\(tm\))?\s+(?:graphics|\d{3}m)\b/i;
4390
- INTEL_DISCRETE = /\barc\b|xe2?-hpg|battlemage|alchemist/i;
4391
- FAMILY_RULES = [
4392
- ({ architecture, description, device }) => {
4393
- const number = [description, device, architecture].map((value) => MALI_MODEL.exec(value)?.[1]).find((value) => value !== void 0);
4394
- if (number === void 0) return void 0;
4395
- const model = Number(number);
4396
- if (model >= 710) return "mobile-high";
4397
- return model < 57 || model === 71 || model === 72 ? "mobile-low" : "mobile-mid";
4398
- },
4399
- ({ architecture, vendor }) => {
4400
- if (!/\barm\b/i.test(vendor)) return void 0;
4401
- if (/midgard|bifrost/i.test(architecture)) return "mobile-low";
4402
- if (/valhall/i.test(architecture)) return "mobile-mid";
4403
- return /5th-?gen|immortalis/i.test(architecture) ? "mobile-high" : void 0;
4404
- },
4405
- ({ architecture, description, device }) => {
4406
- const match = [description, device, architecture].map((value) => ADRENO_MODEL.exec(value)).find((value) => value !== null && value !== void 0);
4407
- if (match === null || match === void 0) return void 0;
4408
- const generation = Number(match[1]);
4409
- if (generation <= 4) return "mobile-low";
4410
- if (generation === 5) return "mobile-mid";
4411
- if (generation === 6) return match[2] !== "xx" && Number(match[2]) >= 30 ? "mobile-high" : "mobile-mid";
4412
- return "mobile-high";
4413
- },
4414
- ({ architecture, description, device, vendor }) => /nvidia/i.test(vendor) && ![architecture, description, device].some((value) => /tegra/i.test(value)) ? "discrete" : void 0,
4415
- ({ architecture, description, device, vendor }) => {
4416
- if (!/intel/i.test(vendor)) return void 0;
4417
- return [architecture, description, device].some((value) => INTEL_DISCRETE.test(value)) ? "discrete" : "integrated";
4418
- },
4419
- // An APU and a card share an architecture name, so an AMD adapter that names no iGPU is `discrete`.
4420
- ({ description, vendor }) => /\b(?:amd|ati)\b/i.test(vendor) ? AMD_INTEGRATED.test(description) ? "integrated" : "discrete" : void 0
4421
- ];
4888
+ var WORLD_TOPOLOGY_METRIC_FAILURES, WORLD_TOPOLOGY_MEASUREMENT_SIZE, DEFAULT_WORLD_TOPOLOGY_THRESHOLDS;
4889
+ var init_world_gameplay = __esm({
4890
+ "src/evaluators/world-gameplay.ts"() {
4891
+ init_assertion_report();
4892
+ init_helpers();
4893
+ WORLD_TOPOLOGY_METRIC_FAILURES = {
4894
+ directionalAnisotropy: "directional-anisotropy",
4895
+ powerSpectrumSlope: "power-spectrum-slope",
4896
+ reliefFieldEdge: "relief-field-edge",
4897
+ median64mRelief: "median-64m-relief",
4898
+ maxHortonStrahlerOrder: "horton-strahler-order",
4899
+ profileCurvatureExcessKurtosis: "curvature-excess-kurtosis",
4900
+ effectiveVertexDensityPerKm2: "effective-vertex-density",
4901
+ slopeTailAbove30Degrees: "slope-tail-above-30-degrees"
4902
+ };
4903
+ WORLD_TOPOLOGY_MEASUREMENT_SIZE = 1024;
4904
+ DEFAULT_WORLD_TOPOLOGY_THRESHOLDS = {
4905
+ maxDirectionalAnisotropy: 0.1,
4906
+ minPowerSpectrumSlope: 2.5,
4907
+ maxPowerSpectrumSlope: 5,
4908
+ minReliefFieldEdge: 0.1,
4909
+ maxMedian64mRelief: 0.25,
4910
+ minHortonStrahlerOrder: 5,
4911
+ minProfileCurvatureExcessKurtosis: 5,
4912
+ minEffectiveVertexDensityPerKm2: 5e5,
4913
+ minSlopeTailAbove30Degrees: 0.1
4914
+ };
4422
4915
  }
4423
4916
  });
4424
4917
 
@@ -4856,6 +5349,366 @@ var init_scene_nodes = __esm({
4856
5349
  }
4857
5350
  });
4858
5351
 
5352
+ // src/evaluators/foot-slip.ts
5353
+ function measureFootSlip(observation, stepSeconds = DEFAULT_STEP_SECONDS) {
5354
+ const { samples } = observation;
5355
+ let travel = 0;
5356
+ for (let index = 1; index < samples.length; index += 1) {
5357
+ const before = samples[index - 1].body;
5358
+ const after = samples[index].body;
5359
+ if (before !== null && after !== null) travel += Math.hypot(after[0] - before[0], after[2] - before[2]);
5360
+ }
5361
+ if (samples.length < 2 || samples.some(({ body }) => body === null))
5362
+ return { feet: [], travel, unobserved: `the subject '${observation.entity}' was not reported on every tick` };
5363
+ const missing = observation.feet.filter((_name, foot) => samples.some((sample) => sample.feet[foot] === null));
5364
+ if (missing.length > 0)
5365
+ return { feet: [], travel, unobserved: `no node named ${missing.map((name) => `'${name}'`).join(", ")} was found on every tick; name the sole nodes (Object3D.name) the scenario lists` };
5366
+ if (travel < FOOT_SLIP_MIN_TRAVEL_M)
5367
+ return { feet: [], travel, unobserved: `the subject moved ${travel.toFixed(2)} m during the step, under ${FOOT_SLIP_MIN_TRAVEL_M} m; drive it before bounding its feet` };
5368
+ const feet = observation.feet.map((name, foot) => {
5369
+ const heights = samples.map((sample) => sample.feet[foot][1] - sample.body[1]);
5370
+ const low = Math.min(...heights);
5371
+ const lift = Math.max(...heights) - low;
5372
+ const planted = heights.map((height) => height <= low + FOOT_SLIP_CONTACT_BAND * lift);
5373
+ let footTravel = 0;
5374
+ let bodyTravel = 0;
5375
+ let contactPairs = 0;
5376
+ for (let index = 1; index < samples.length; index += 1) {
5377
+ if (!planted[index - 1] || !planted[index]) continue;
5378
+ const [fx0, , fz0] = samples[index - 1].feet[foot];
5379
+ const [fx1, , fz1] = samples[index].feet[foot];
5380
+ const [bx0, , bz0] = samples[index - 1].body;
5381
+ const [bx1, , bz1] = samples[index].body;
5382
+ footTravel += Math.hypot(fx1 - fx0, fz1 - fz0);
5383
+ bodyTravel += Math.hypot(bx1 - bx0, bz1 - bz0);
5384
+ contactPairs += 1;
5385
+ }
5386
+ return {
5387
+ contactPairs,
5388
+ lift,
5389
+ name,
5390
+ ...contactPairs < MIN_CONTACT_PAIRS || bodyTravel <= 0 ? {} : { slip: footTravel / bodyTravel, speed: footTravel / (contactPairs * stepSeconds) }
5391
+ };
5392
+ });
5393
+ return { feet, travel };
5394
+ }
5395
+ function emitFootSlip(ctx) {
5396
+ const assertions = ctx.scenarioAssertions.footSlip;
5397
+ if (assertions === void 0 || assertions.length === 0) return;
5398
+ assertions.forEach((assertion, index) => {
5399
+ const id = `footSlip[${index}]`;
5400
+ const observation = ctx.input.report.observations?.footSlip?.find(({ label }) => label === assertion.atStep);
5401
+ const measure = observation === void 0 ? void 0 : measureFootSlip(observation, assertion.stepSeconds);
5402
+ const unmeasured = measure?.feet.find(({ slip }) => slip === void 0);
5403
+ const reason = observation === void 0 ? "the run recorded no per-tick foot samples for this step; footSlip runs only on the browser target" : measure.unobserved ?? (unmeasured === void 0 ? void 0 : `'${unmeasured.name}' was planted on fewer than ${MIN_CONTACT_PAIRS} consecutive ticks`);
5404
+ if (reason !== void 0) {
5405
+ ctx.assertions.push({ details: { atStep: assertion.atStep, reason, ...measure === void 0 ? {} : { travel: measure.travel } }, id: `${id}.observed`, pass: false });
5406
+ ctx.diagnostics.push({
5407
+ code: "TN_PLAYTEST_FOOT_SLIP_UNOBSERVED",
5408
+ message: `footSlip at '${assertion.atStep}' was not measured: ${reason}.`,
5409
+ observedRuntimePath: "observations.json/footSlip",
5410
+ severity: "error",
5411
+ suggestion: "Run on the browser target, name each sole node (Object3D.name, for example footL and footR), and make the step move the subject at a run."
5412
+ });
5413
+ return;
5414
+ }
5415
+ const animation = runtimeGameplaySamples(ctx.input.report.observations?.runtimeObservations).find(({ label }) => label === assertion.atStep)?.gameplay.animation;
5416
+ const stride = isRecord(animation) ? strideReading(animation[observation.entity]) : void 0;
5417
+ if (stride !== void 0 && strideHasNoFootPlant(stride)) {
5418
+ ctx.assertions.push({ details: { atStep: assertion.atStep, reason: NO_FOOT_PLANT_DETAIL, stride, travel: measure.travel }, id: `${id}.observed`, pass: false });
5419
+ ctx.diagnostics.push({
5420
+ code: "TN_PLAYTEST_STRIDE_NO_FOOT_PLANT",
5421
+ message: `footSlip at '${assertion.atStep}' failed closed: ${NO_FOOT_PLANT_DETAIL}.`,
5422
+ observedRuntimePath: "observations.json/runtimeObservations",
5423
+ severity: "error",
5424
+ suggestion: "The clip has no root motion and its feet never plant, so stride sync cannot match it to the ground: author a clip whose feet plant, or drive the stride from distance travelled."
5425
+ });
5426
+ return;
5427
+ }
5428
+ const worst = Math.max(...measure.feet.map(({ slip }) => slip));
5429
+ const worstSpeed = Math.max(...measure.feet.map(({ speed }) => speed));
5430
+ const slipPass = assertion.maxSlip === void 0 || worst <= assertion.maxSlip;
5431
+ const speedPass = assertion.maxSlideSpeed === void 0 || worstSpeed <= assertion.maxSlideSpeed;
5432
+ ctx.assertions.push({
5433
+ details: {
5434
+ atStep: assertion.atStep,
5435
+ expected: { maxSlideSpeed: assertion.maxSlideSpeed, maxSlip: assertion.maxSlip },
5436
+ feet: measure.feet,
5437
+ travel: measure.travel,
5438
+ worst,
5439
+ worstSpeed
5440
+ },
5441
+ id: `${id}.slip`,
5442
+ pass: slipPass && speedPass
5443
+ });
5444
+ if (!slipPass)
5445
+ ctx.diagnostics.push({
5446
+ code: "TN_PLAYTEST_FOOT_SLIP",
5447
+ message: `A planted foot travelled ${worst.toFixed(2)} m per metre of body travel at '${assertion.atStep}', ceiling ${assertion.maxSlip}.`,
5448
+ observedRuntimePath: "observations.json/footSlip",
5449
+ severity: "error",
5450
+ suggestion: "Drive the stride from distance travelled, not from time: the cycle phase should advance by ground speed over stride length, so a planted foot stays put."
5451
+ });
5452
+ if (!speedPass)
5453
+ ctx.diagnostics.push({
5454
+ code: "TN_PLAYTEST_FOOT_SLIP",
5455
+ message: `A planted foot slid at ${worstSpeed.toFixed(2)} m/s at '${assertion.atStep}', ceiling ${assertion.maxSlideSpeed} m/s.`,
5456
+ observedRuntimePath: "observations.json/footSlip",
5457
+ severity: "error",
5458
+ suggestion: "Drive the stride from distance travelled, not from time: the cycle phase should advance by ground speed over stride length, so a planted foot stays put."
5459
+ });
5460
+ });
5461
+ }
5462
+ var FOOT_SLIP_MIN_TRAVEL_M, FOOT_SLIP_CONTACT_BAND, MIN_CONTACT_PAIRS, DEFAULT_STEP_SECONDS;
5463
+ var init_foot_slip = __esm({
5464
+ "src/evaluators/foot-slip.ts"() {
5465
+ init_assertion_report();
5466
+ init_families_observation();
5467
+ FOOT_SLIP_MIN_TRAVEL_M = 0.5;
5468
+ FOOT_SLIP_CONTACT_BAND = 0.25;
5469
+ MIN_CONTACT_PAIRS = 4;
5470
+ DEFAULT_STEP_SECONDS = 1 / 60;
5471
+ }
5472
+ });
5473
+
5474
+ // src/evaluators/sight-line.ts
5475
+ function topBlockers(blockers) {
5476
+ const counts = /* @__PURE__ */ new Map();
5477
+ for (const name of blockers) counts.set(name, (counts.get(name) ?? 0) + 1);
5478
+ return [...counts.entries()].sort(([leftName, leftCount], [rightName, rightCount]) => rightCount - leftCount || leftName.localeCompare(rightName)).slice(0, MAX_BLOCKER_NAMES).map(([name]) => name);
5479
+ }
5480
+ function emitSightLine(ctx) {
5481
+ const assertion = ctx.scenarioAssertions.sightLine;
5482
+ if (assertion === void 0) return;
5483
+ const observation = ctx.input.report.observations?.sightLine;
5484
+ const samples = observation?.samples ?? [];
5485
+ if (samples.length === 0) {
5486
+ ctx.assertions.push({ details: { samples: 0 }, id: "sightLine.observed", pass: false });
5487
+ ctx.diagnostics.push({
5488
+ code: "TN_PLAYTEST_SIGHT_LINE_UNOBSERVED",
5489
+ message: "A sightLine assertion was evaluated against a run that sampled no camera-to-subject sight line.",
5490
+ observedRuntimePath: "observations.json/sightLine",
5491
+ severity: "error",
5492
+ suggestion: "Run on the browser target and make sure the scenario advances at least one step whose subject is registered with the bridge."
5493
+ });
5494
+ return;
5495
+ }
5496
+ const blockedCount = samples.filter(({ blocked }) => blocked).length;
5497
+ const ratio = blockedCount / samples.length;
5498
+ const pass = ratio <= assertion.maxBlockedRatio;
5499
+ const blockers = topBlockers(samples.flatMap((sample) => sample.blockers));
5500
+ ctx.assertions.push({
5501
+ details: { blocked: blockedCount, blockers, ratio, samples: samples.length },
5502
+ id: "sightLine",
5503
+ pass
5504
+ });
5505
+ if (!pass) {
5506
+ ctx.diagnostics.push({
5507
+ code: "TN_PLAYTEST_SIGHT_LINE_BLOCKED",
5508
+ message: `Solid geometry blocked the camera's view of '${observation.entity}' on ${blockedCount} of ${samples.length} samples (${(ratio * 100).toFixed(1)}%), ceiling ${assertion.maxBlockedRatio}.`,
5509
+ observedRuntimePath: "observations.json/sightLine",
5510
+ severity: "error",
5511
+ suggestion: "Move the camera along the cast or pull it in past the blocker, so a line from the lens to the subject stays clear."
5512
+ });
5513
+ }
5514
+ }
5515
+ var MAX_BLOCKER_NAMES;
5516
+ var init_sight_line = __esm({
5517
+ "src/evaluators/sight-line.ts"() {
5518
+ MAX_BLOCKER_NAMES = 5;
5519
+ }
5520
+ });
5521
+
5522
+ // src/evaluators/hud-audit.ts
5523
+ function channelLuminance(channel) {
5524
+ const value = channel / 255;
5525
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
5526
+ }
5527
+ function relativeLuminance([red, green, blue]) {
5528
+ return 0.2126 * channelLuminance(red) + 0.7152 * channelLuminance(green) + 0.0722 * channelLuminance(blue);
5529
+ }
5530
+ function contrastRatio(foreground, background) {
5531
+ const alpha = Math.min(Math.max(foreground[3], 0), 1);
5532
+ const composited = [
5533
+ foreground[0] * alpha + background[0] * (1 - alpha),
5534
+ foreground[1] * alpha + background[1] * (1 - alpha),
5535
+ foreground[2] * alpha + background[2] * (1 - alpha),
5536
+ 1
5537
+ ];
5538
+ const first = relativeLuminance(composited);
5539
+ const second = relativeLuminance(background);
5540
+ return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
5541
+ }
5542
+ function readsAsDeveloperText(text) {
5543
+ return DEVELOPER_TEXT.test(text) || UNRESOLVED_TEXT.test(text) || COERCED_OBJECT.test(text);
5544
+ }
5545
+ function offenders(items) {
5546
+ return items.slice(0, MAX_OFFENDERS).map(({ selector, text }) => ({ selector, text }));
5547
+ }
5548
+ function emitHudAudit(ctx) {
5549
+ const assertion = ctx.scenarioAssertions.hudAudit;
5550
+ if (assertion === void 0) return;
5551
+ const items = ctx.input.report.observations?.hudAudit?.items ?? [];
5552
+ if (items.length === 0) {
5553
+ ctx.assertions.push({ details: { items: 0 }, id: "hudAudit.observed", pass: false });
5554
+ ctx.diagnostics.push({
5555
+ code: "TN_PLAYTEST_HUD_AUDIT_UNOBSERVED",
5556
+ message: "A hudAudit assertion was evaluated against a run that reported no visible page text.",
5557
+ observedRuntimePath: "observations.json/hudAudit",
5558
+ severity: "error",
5559
+ suggestion: "Run on the browser target and make sure the page draws player-facing text in the DOM, outside a canvas."
5560
+ });
5561
+ return;
5562
+ }
5563
+ if (assertion.noDebugText === true) {
5564
+ const found = items.filter(({ text }) => readsAsDeveloperText(text));
5565
+ const pass = found.length === 0;
5566
+ ctx.assertions.push({
5567
+ details: { checked: items.length, offenders: offenders(found) },
5568
+ id: "hudAudit.debugText",
5569
+ pass
5570
+ });
5571
+ if (!pass) {
5572
+ ctx.diagnostics.push({
5573
+ code: "TN_PLAYTEST_HUD_DEBUG_TEXT",
5574
+ message: `Developer text reached the player's HUD in ${found.length} of ${items.length} text items: ${found.slice(0, MAX_OFFENDERS).map(({ text }) => JSON.stringify(text)).join(", ")}.`,
5575
+ observedRuntimePath: "observations.json/hudAudit/items",
5576
+ severity: "error",
5577
+ suggestion: "Replace debug, TODO, placeholder and unresolved values with the copy the player should read, then rerun the scenario."
5578
+ });
5579
+ }
5580
+ }
5581
+ if (assertion.minContrast !== void 0) {
5582
+ const judged = items.filter(({ background }) => background[3] >= JUDGED_BACKGROUND_ALPHA);
5583
+ const unjudged = items.length - judged.length;
5584
+ const worst = judged.map(({ selector, text, background, color }) => ({ ratio: contrastRatio(color, background), selector, text })).sort((left, right) => left.ratio - right.ratio).slice(0, MAX_OFFENDERS);
5585
+ const pass = worst.every(({ ratio }) => ratio >= assertion.minContrast);
5586
+ ctx.assertions.push({
5587
+ details: { judged: judged.length, minContrast: assertion.minContrast, unjudged, worst },
5588
+ id: "hudAudit.contrast",
5589
+ pass
5590
+ });
5591
+ if (!pass) {
5592
+ ctx.diagnostics.push({
5593
+ code: "TN_PLAYTEST_HUD_CONTRAST",
5594
+ message: `HUD text falls below the ${assertion.minContrast}:1 contrast floor: ${worst.filter(({ ratio }) => ratio < assertion.minContrast).map(({ ratio, text }) => `${JSON.stringify(text)} at ${ratio.toFixed(2)}:1`).join(", ")}.`,
5595
+ observedRuntimePath: "observations.json/hudAudit/items",
5596
+ severity: "error",
5597
+ suggestion: "Raise the text colour's contrast against its backing plate, or darken the plate, until every judged item reaches the floor."
5598
+ });
5599
+ }
5600
+ }
5601
+ }
5602
+ var MAX_OFFENDERS, JUDGED_BACKGROUND_ALPHA, DEVELOPER_TEXT, UNRESOLVED_TEXT, COERCED_OBJECT;
5603
+ var init_hud_audit = __esm({
5604
+ "src/evaluators/hud-audit.ts"() {
5605
+ MAX_OFFENDERS = 5;
5606
+ JUDGED_BACKGROUND_ALPHA = 0.5;
5607
+ DEVELOPER_TEXT = /\b(debug|todo|fixme|lorem ipsum|placeholder|probe|raycast|hitbox|wall ray)\b/iu;
5608
+ UNRESOLVED_TEXT = /\b(undefined|null|NaN)\b/u;
5609
+ COERCED_OBJECT = /\[object /u;
5610
+ }
5611
+ });
5612
+
5613
+ // src/evaluators/engine-cost.ts
5614
+ function engineCostWindows(lines) {
5615
+ const windows = [];
5616
+ let top;
5617
+ for (const line of lines) {
5618
+ if (typeof line !== "string") continue;
5619
+ const census = line.indexOf(BRIDGE_CENSUS_MARKER);
5620
+ if (census !== -1) {
5621
+ try {
5622
+ top = JSON.parse(line.slice(census + BRIDGE_CENSUS_MARKER.length)).top;
5623
+ } catch {
5624
+ top = void 0;
5625
+ }
5626
+ continue;
5627
+ }
5628
+ const at = line.indexOf(FRAME_BUDGET_MARKER);
5629
+ if (at === -1) continue;
5630
+ try {
5631
+ const report = JSON.parse(line.slice(at + FRAME_BUDGET_MARKER.length));
5632
+ const engine = report.counters?.engine;
5633
+ if (engine === void 0) continue;
5634
+ if (engine === null || typeof engine !== "object" || Array.isArray(engine)) throw new Error("invalid engine counters");
5635
+ const series = {
5636
+ ...engine,
5637
+ ...report.counters?.bridgeCrossings === void 0 ? {} : { bridgeCrossings: report.counters.bridgeCrossings }
5638
+ };
5639
+ for (const summary2 of Object.values(series)) {
5640
+ if (summary2 === null || typeof summary2 !== "object" || !Number.isFinite(summary2.mean) || summary2.mean < 0 || !Number.isFinite(summary2.max) || summary2.max < 0 || !Number.isSafeInteger(summary2.samples) || summary2.samples < 1) throw new Error("unmeasured engine counter");
5641
+ }
5642
+ const pick = (field) => Object.fromEntries(Object.entries(series).map(([name, summary2]) => [name, summary2[field]]));
5643
+ windows.push({ maxFrame: pick("max"), perFrame: pick("mean"), top, ...report.window === void 0 ? {} : { window: report.window } });
5644
+ } catch {
5645
+ windows.push(void 0);
5646
+ }
5647
+ }
5648
+ return windows;
5649
+ }
5650
+ function topCaller(window2) {
5651
+ const top = window2.top?.[0];
5652
+ return top === void 0 ? "no census before this window" : `${top.name ?? "?"} ${top.perFrame ?? "?"}/frame from ${top.caller ?? "unknown"}`;
5653
+ }
5654
+ function emitEngineCost(ctx) {
5655
+ const assertion = ctx.scenarioAssertions.engineCost;
5656
+ if (assertion === void 0) return;
5657
+ const windows = engineCostWindows((ctx.input.report.observations?.console ?? []).map(({ text }) => text));
5658
+ const stillWindows = assertion.still?.windows ?? 0;
5659
+ const skipped = assertion.skipWindows ?? 0;
5660
+ const needed = Math.max(assertion.minWindows ?? 1, skipped + stillWindows + (assertion.moving === void 0 ? 0 : 1));
5661
+ const readable = windows.filter((window2) => window2 !== void 0);
5662
+ const observed = readable.length >= needed && readable.length === windows.length;
5663
+ ctx.assertions.push({ details: { windows: windows.length, unreadable: windows.length - readable.length, needed }, id: "engineCost.observed", pass: observed });
5664
+ if (!observed) {
5665
+ ctx.diagnostics.push({
5666
+ code: "TN_PLAYTEST_ENGINE_COST_UNOBSERVED",
5667
+ message: `engineCost needs ${needed} readable TN_FRAME_BUDGET window(s) with counters.engine; the run printed ${windows.length}, ${windows.length - readable.length} unreadable.`,
5668
+ observedRuntimePath: "observations.json/console",
5669
+ severity: "error",
5670
+ suggestion: "Run with the playtest runner (it sets __THREENATIVE_ENGINE_COST__, which turns the counters on) on a fixed-step clock, long enough for each 300-tick TN_FRAME_BUDGET window the bounds need."
5671
+ });
5672
+ return;
5673
+ }
5674
+ const bounded = readable.slice(skipped);
5675
+ for (const [kind, table, scope, windows2] of [
5676
+ ["perFrame", assertion.maxPerFrame, "maxPerFrame", bounded],
5677
+ ["maxFrame", assertion.maxInFrame, "maxInFrame", bounded],
5678
+ ["perFrame", assertion.still?.maxPerFrame, "still.maxPerFrame", bounded.slice(0, stillWindows)],
5679
+ ["perFrame", assertion.moving?.maxPerFrame, "moving.maxPerFrame", bounded.slice(stillWindows)],
5680
+ ["maxFrame", assertion.moving?.maxInFrame, "moving.maxInFrame", bounded.slice(stillWindows)]
5681
+ ]) {
5682
+ for (const [name, bound] of Object.entries(table ?? {})) {
5683
+ const values = windows2.map((window2) => window2[kind]?.[name]);
5684
+ const missing = values.findIndex((value2) => typeof value2 !== "number" || !Number.isFinite(value2));
5685
+ const worst = windows2.reduce(
5686
+ (top, window2) => (window2[kind]?.[name] ?? -1) > (top?.[kind]?.[name] ?? -1) ? window2 : top,
5687
+ void 0
5688
+ );
5689
+ const value = worst?.[kind]?.[name] ?? Number.NaN;
5690
+ const pass = missing === -1 && value <= bound;
5691
+ const id = `engineCost.${scope}.${name}`;
5692
+ ctx.assertions.push({ details: { bound, value, window: worst?.window, source: assertion.source }, id, pass });
5693
+ if (pass) continue;
5694
+ ctx.diagnostics.push({
5695
+ code: "TN_PLAYTEST_ENGINE_COST_OVER_BOUND",
5696
+ message: missing !== -1 ? `engineCost: window ${windows2[missing]?.window ?? missing + 1} reports no '${name}' (${kind}); a bounded counter must be measured in every window.` : `engineCost: '${name}' ${kind === "perFrame" ? "per frame" : "in one frame"}${scope.startsWith("still") ? " while still" : scope.startsWith("moving") ? " in play" : ""} reached ${value} in window ${worst?.window ?? "?"}, over the bound ${bound} (${assertion.source}). Top crossing: ${topCaller(worst)}.`,
5697
+ observedRuntimePath: "observations.json/console",
5698
+ severity: "error",
5699
+ suggestion: "Read TN_FRAME_BUDGET.counters.engine and the TN_BRIDGE_CENSUS before it: the counter names the cost class, and the top caller names the code that pays it. Fix that code or the engine path under it; never raise the bound to pass."
5700
+ });
5701
+ }
5702
+ }
5703
+ }
5704
+ var FRAME_BUDGET_MARKER, BRIDGE_CENSUS_MARKER;
5705
+ var init_engine_cost = __esm({
5706
+ "src/evaluators/engine-cost.ts"() {
5707
+ FRAME_BUDGET_MARKER = "TN_FRAME_BUDGET:";
5708
+ BRIDGE_CENSUS_MARKER = "TN_BRIDGE_CENSUS:";
5709
+ }
5710
+ });
5711
+
4859
5712
  // src/runner/sceneRoom.ts
4860
5713
  function summariseRoom(scene) {
4861
5714
  const types = {};
@@ -5065,7 +5918,40 @@ var init_scene = __esm({
5065
5918
  });
5066
5919
 
5067
5920
  // src/evaluators/startup.ts
5921
+ function emitOffscreenBytes(ctx) {
5922
+ const ceiling = ctx.scenarioAssertions.startup?.maxOffscreenBytes;
5923
+ const observed = ctx.input.report.observations?.startup?.offscreenBytes;
5924
+ const unsized = observed !== void 0 && observed.awaitedBytes === 0 && observed.unsizedFiles > 0;
5925
+ if (ceiling !== void 0) {
5926
+ const measured = observed !== void 0 && !unsized;
5927
+ const pass = measured && observed.offscreenBytes <= ceiling;
5928
+ ctx.assertions.push({
5929
+ details: { expected: ceiling, observed: measured ? observed.offscreenBytes : void 0 },
5930
+ id: "startup.offscreenBytes",
5931
+ pass
5932
+ });
5933
+ if (!pass) {
5934
+ ctx.diagnostics.push({
5935
+ code: measured ? "TN_PLAYTEST_STARTUP_OFFSCREEN_BYTES" : "TN_PLAYTEST_STARTUP_UNOBSERVABLE",
5936
+ message: measured ? `The reveal waited for ${mb(observed.offscreenBytes)} the spawn camera does not show (${observed.top.map((file) => `${file.path} ${mb(file.bytes)} ${file.reason}`).join(", ")}), past the asserted ceiling of ${mb(ceiling)}.` : observed === void 0 ? "Off-screen startup bytes were not observed: the runtime reported no measurement." : `Off-screen startup bytes were not observable: the runtime awaited ${observed.unsizedFiles} file(s) and the asset manifest records no size for any of them.`,
5937
+ observedRuntimePath: "observations.json/startup/offscreenBytes",
5938
+ severity: "error",
5939
+ suggestion: measured ? observed.fix : "Build the game's assets with the asset pipeline so the manifest records each file's bytes, and keep the playtest bridge installed before startup."
5940
+ });
5941
+ return;
5942
+ }
5943
+ }
5944
+ if (observed?.warn !== true) return;
5945
+ ctx.diagnostics.push({
5946
+ code: "TN_PLAYTEST_STARTUP_OFFSCREEN_BYTES",
5947
+ message: `Most of the reveal's wait bought nothing on screen: ${mb(observed.offscreenBytes)} of ${mb(observed.awaitedBytes)} awaited is not shown by the spawn camera (${observed.top.map((file) => `${file.path} ${mb(file.bytes)} ${file.reason}`).join(", ")}).`,
5948
+ observedRuntimePath: "observations.json/startup/offscreenBytes",
5949
+ severity: "warning",
5950
+ suggestion: observed.fix
5951
+ });
5952
+ }
5068
5953
  function emitStartup(ctx) {
5954
+ emitOffscreenBytes(ctx);
5069
5955
  const assertion = ctx.scenarioAssertions.startup;
5070
5956
  if (assertion === void 0) return;
5071
5957
  const timeline = ctx.input.report.observations?.startup?.timeline;
@@ -5088,10 +5974,34 @@ function emitStartup(ctx) {
5088
5974
  suggestion: observed === void 0 ? "Keep the playtest bridge installed before startup and let the game reach that milestone inside the run; a runtime without a startup timeline cannot satisfy this assertion." : "Move work out of the critical startup path \u2014 load detail after enter(), share textures across models, keep first-use compilation inside its budget \u2014 or raise the ceiling with the measurement that justifies it."
5089
5975
  });
5090
5976
  }
5977
+ if (assertion.steadyCover === true) emitSteadyCover(ctx);
5978
+ }
5979
+ function emitSteadyCover(ctx) {
5980
+ const cover = ctx.input.report.observations?.startup?.cover;
5981
+ const observed = cover !== void 0 && cover.frames > 0 && cover.worldMs !== void 0;
5982
+ const uiOverCover = cover?.uiOverCover ?? [];
5983
+ const pass = observed && cover.differing.length === 0 && uiOverCover.length === 0;
5984
+ ctx.assertions.push({
5985
+ details: observed ? { differing: cover.differing.length, first: cover.differing.slice(0, 5), frames: cover.frames, reference: cover.reference, uiOverCover, worldMs: cover.worldMs } : { frames: cover?.frames ?? 0, worldMs: cover?.worldMs },
5986
+ id: "startup.steadyCover",
5987
+ pass
5988
+ });
5989
+ if (pass) return;
5990
+ const first = cover?.differing[0];
5991
+ const ui = uiOverCover[0];
5992
+ ctx.diagnostics.push({
5993
+ code: !observed ? "TN_PLAYTEST_STARTUP_COVER_UNOBSERVED" : first === void 0 && ui !== void 0 ? "TN_PLAYTEST_STARTUP_UI_OVER_COVER" : "TN_PLAYTEST_STARTUP_COVER_BROKEN",
5994
+ message: observed && first !== void 0 ? `${cover.differing.length} of ${cover.frames} frames before readiness differ from the loading cover (mean rgb ${cover.reference.join(",")}); the first at ${first.ms} ms has mean rgb ${first.mean.join(",")}.` : observed && ui !== void 0 ? `${uiOverCover.length} frames after readiness show the world's page UI over the loading cover before the world frame at ${cover.worldMs} ms; the first at ${ui.ms} ms (${(ui.share * 100).toFixed(1)}% of its pixels).` : cover !== void 0 && cover.frames > 0 ? "No world frame was recorded in the hand-off frames after readiness: the cover never gave way to the world." : "No frame presented before readiness was recorded: the browser runner records them only on the browser target, and only when the runtime stamps readyMs.",
5995
+ observedRuntimePath: "observations.json/startup/cover",
5996
+ severity: "error",
5997
+ suggestion: observed && first === void 0 && ui !== void 0 ? "Show page UI only once the world frame is on screen: core publishes state written on whenReady() after the uncovered world frame has left the GPU, so gate the HUD on that state, not on a timer or an earlier signal." : observed ? "Paint the cover on every frame the page presents before readiness: the page background in the cover's colour, and a repaint after any draw made outside the frame loop." : "Run the scenario on the browser target with the playtest bridge installed before startup."
5998
+ });
5091
5999
  }
5092
- var MILESTONES;
6000
+ var MB, mb, MILESTONES;
5093
6001
  var init_startup = __esm({
5094
6002
  "src/evaluators/startup.ts"() {
6003
+ MB = 1e6;
6004
+ mb = (bytes) => `${(bytes / MB).toFixed(1)} MB`;
5095
6005
  MILESTONES = {
5096
6006
  maxCompileSettledMs: "compileSettledMs",
5097
6007
  maxEnteredMs: "enteredMs",
@@ -6315,6 +7225,10 @@ function evaluateRichPlaytestAssertions(input) {
6315
7225
  emitPipelineCensus(ctx);
6316
7226
  emitScene(ctx);
6317
7227
  emitSceneNodes(ctx);
7228
+ emitFootSlip(ctx);
7229
+ emitSightLine(ctx);
7230
+ emitHudAudit(ctx);
7231
+ emitEngineCost(ctx);
6318
7232
  if (scenarioAssertions.geometry !== void 0) {
6319
7233
  const observed = input.report.observations?.geometry;
6320
7234
  const status = observed?.status;
@@ -6357,6 +7271,10 @@ var init_assertion_evaluators = __esm({
6357
7271
  init_render_chain();
6358
7272
  init_caused_by();
6359
7273
  init_scene_nodes();
7274
+ init_foot_slip();
7275
+ init_sight_line();
7276
+ init_hud_audit();
7277
+ init_engine_cost();
6360
7278
  init_scene();
6361
7279
  init_startup();
6362
7280
  init_pipeline_census();
@@ -6521,6 +7439,7 @@ var init_generated_assertion_validators = __esm({
6521
7439
  }),
6522
7440
  "performance": Object.freeze({
6523
7441
  "maxFrameMsP95": (value) => typeof value === "number" && Number.isFinite(value),
7442
+ "maxFrameMsReason": (value) => typeof value === "string" && value.trim() !== "",
6524
7443
  "minFps": (value) => typeof value === "number" && Number.isFinite(value),
6525
7444
  "maxPhaseMsP95": (value) => isRecord2(value),
6526
7445
  "maxDrawCalls": (value) => typeof value === "number" && Number.isFinite(value),
@@ -6578,6 +7497,7 @@ var init_generated_assertion_validators = __esm({
6578
7497
  "animation": Object.freeze({
6579
7498
  "entity": (value) => typeof value === "string" && value.trim() !== "",
6580
7499
  "clip": (value) => typeof value === "string" && value.trim() !== "",
7500
+ "atStep": (value) => typeof value === "string" && value.trim() !== "",
6581
7501
  "entered": (value) => typeof value === "boolean",
6582
7502
  "advancedFrames": (value) => typeof value === "number" && Number.isFinite(value),
6583
7503
  "finished": (value) => typeof value === "boolean",
@@ -6602,6 +7522,31 @@ var init_generated_assertion_validators = __esm({
6602
7522
  "maxCount": (value) => typeof value === "number" && Number.isFinite(value),
6603
7523
  "minTriangles": (value) => typeof value === "number" && Number.isFinite(value)
6604
7524
  }),
7525
+ "footSlip": Object.freeze({
7526
+ "atStep": (value) => typeof value === "string" && value.trim() !== "",
7527
+ "feet": (value) => Array.isArray(value),
7528
+ "maxSlip": (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
7529
+ "maxSlideSpeed": (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
7530
+ "stepSeconds": (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
7531
+ "entity": (value) => typeof value === "string" && value.trim() !== ""
7532
+ }),
7533
+ "sightLine": Object.freeze({
7534
+ "entity": (value) => typeof value === "string" && value.trim() !== "",
7535
+ "maxBlockedRatio": (value) => typeof value === "number" && Number.isFinite(value)
7536
+ }),
7537
+ "engineCost": Object.freeze({
7538
+ "maxPerFrame": (value) => isRecord2(value),
7539
+ "maxInFrame": (value) => isRecord2(value),
7540
+ "minWindows": (value) => typeof value === "number" && Number.isInteger(value) && value > 0,
7541
+ "skipWindows": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
7542
+ "still": (value) => isRecord2(value),
7543
+ "moving": (value) => isRecord2(value),
7544
+ "source": (value) => typeof value === "string" && value.trim() !== ""
7545
+ }),
7546
+ "hudAudit": Object.freeze({
7547
+ "minContrast": (value) => typeof value === "number" && Number.isFinite(value),
7548
+ "noDebugText": (value) => value === true
7549
+ }),
6605
7550
  "causedBy": Object.freeze({
6606
7551
  "cause": (value) => isRecord2(value),
6607
7552
  "effect": (value) => isRecord2(value),
@@ -6611,7 +7556,9 @@ var init_generated_assertion_validators = __esm({
6611
7556
  "startup": Object.freeze({
6612
7557
  "maxEnteredMs": (value) => typeof value === "number" && Number.isFinite(value),
6613
7558
  "maxCompileSettledMs": (value) => typeof value === "number" && Number.isFinite(value),
6614
- "maxReadyMs": (value) => typeof value === "number" && Number.isFinite(value)
7559
+ "maxReadyMs": (value) => typeof value === "number" && Number.isFinite(value),
7560
+ "maxOffscreenBytes": (value) => typeof value === "number" && Number.isFinite(value),
7561
+ "steadyCover": (value) => typeof value === "boolean"
6615
7562
  }),
6616
7563
  "pipelineCensus": Object.freeze({
6617
7564
  "maxNodeBuildsAfterWarmUpSettled": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
@@ -6645,6 +7592,9 @@ function validateVisualAssertion(value, scenarioPath, objectPath) {
6645
7592
  if (authoredEdge !== void 0) {
6646
7593
  throw invalidScenario(scenarioPath, `'${objectPath}.region.${authoredEdge}' cannot be combined with an element-bound region; the element supplies its bounds.`);
6647
7594
  }
7595
+ if (hasKey(regionRecord, "minSharpness")) {
7596
+ throw invalidScenario(scenarioPath, `'${objectPath}.region.minSharpness' measures the rendered frame; bound a static x/y/width/height region instead of an element.`);
7597
+ }
6648
7598
  region = {
6649
7599
  element,
6650
7600
  ...present("maxDarkPixelRatio", optionalRatio(regionRecord, "maxDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
@@ -6663,6 +7613,7 @@ function validateVisualAssertion(value, scenarioPath, objectPath) {
6663
7613
  }
6664
7614
  region = {
6665
7615
  ...edges,
7616
+ ...present("minSharpness", optionalPositiveNumber(regionRecord, "minSharpness", scenarioPath, `${objectPath}.region`)),
6666
7617
  ...present("maxDarkPixelRatio", optionalRatio(regionRecord, "maxDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
6667
7618
  ...present("maxLuminance", optionalRatio(regionRecord, "maxLuminance", scenarioPath, `${objectPath}.region`)),
6668
7619
  ...present("minDarkPixelRatio", optionalRatio(regionRecord, "minDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
@@ -6866,16 +7817,26 @@ function validateDeviceMetricsAssertion(value, scenarioPath, objectPath) {
6866
7817
  }
6867
7818
  function validatePerformanceAssertion(value, scenarioPath, objectPath) {
6868
7819
  const record4 = requireRecord(value, scenarioPath, objectPath);
6869
- rejectUnknownKeys(record4, ["maxDrawCalls", "maxFrameMsP95", "maxPassDrawCalls", "maxPassTriangles", "maxPhaseMsP95", "maxTriangles", "minFps"], scenarioPath, objectPath);
7820
+ rejectUnknownKeys(record4, ["maxDrawCalls", "maxFrameMsP95", "maxFrameMsReason", "maxPassDrawCalls", "maxPassTriangles", "maxPhaseMsP95", "maxTriangles", "minFps"], scenarioPath, objectPath);
6870
7821
  const assertion = {
6871
7822
  ...present("maxDrawCalls", optionalNonNegativeNumber(record4, "maxDrawCalls", scenarioPath, objectPath)),
6872
7823
  ...present("maxFrameMsP95", optionalNonNegativeNumber(record4, "maxFrameMsP95", scenarioPath, objectPath)),
7824
+ ...present("maxFrameMsReason", optionalString(record4, "maxFrameMsReason", scenarioPath, objectPath)),
6873
7825
  ...present("maxPassDrawCalls", validatePassBudget(record4.maxPassDrawCalls, scenarioPath, `${objectPath}.maxPassDrawCalls`)),
6874
7826
  ...present("maxPassTriangles", validatePassBudget(record4.maxPassTriangles, scenarioPath, `${objectPath}.maxPassTriangles`)),
6875
7827
  ...present("maxPhaseMsP95", validatePhaseBudget(record4.maxPhaseMsP95, scenarioPath, `${objectPath}.maxPhaseMsP95`)),
6876
7828
  ...present("maxTriangles", optionalNonNegativeNumber(record4, "maxTriangles", scenarioPath, objectPath)),
6877
7829
  ...present("minFps", optionalNonNegativeNumber(record4, "minFps", scenarioPath, objectPath))
6878
7830
  };
7831
+ if (assertion.maxFrameMsP95 === LEGACY_SCAFFOLD_FRAME_MS && record4.maxFrameMsReason === void 0) {
7832
+ return { ...assertion, maxFrameMsReason: LEGACY_SCAFFOLD_FRAME_REASON };
7833
+ }
7834
+ if (assertion.maxFrameMsP95 !== void 0 && assertion.maxFrameMsP95 > 16.7 && (assertion.maxFrameMsReason ?? "").trim() === "") {
7835
+ throw invalidScenario(
7836
+ scenarioPath,
7837
+ `'${objectPath}.maxFrameMsP95' is ${assertion.maxFrameMsP95} ms, looser than the 16.7 ms (60 fps) budget every tier gets: set 'maxFrameMsReason' to say why, or drop maxFrameMsP95.`
7838
+ );
7839
+ }
6879
7840
  if (Object.keys(assertion).length === 0) {
6880
7841
  throw invalidScenario(
6881
7842
  scenarioPath,
@@ -7036,8 +7997,21 @@ function validateStartupAssertion(value, scenarioPath, objectPath) {
7036
7997
  }
7037
7998
  result[key] = ceiling;
7038
7999
  }
8000
+ const bytes = record4.maxOffscreenBytes;
8001
+ if (bytes !== void 0) {
8002
+ if (typeof bytes !== "number" || !Number.isInteger(bytes) || bytes < 0) {
8003
+ throw invalidScenario(scenarioPath, `'${objectPath}.maxOffscreenBytes' must be a non-negative integer number of bytes, received ${describeValue(bytes)}.`);
8004
+ }
8005
+ result.maxOffscreenBytes = bytes;
8006
+ }
8007
+ if (record4.steadyCover !== void 0) {
8008
+ if (record4.steadyCover !== true) {
8009
+ throw invalidScenario(scenarioPath, `'${objectPath}.steadyCover' must be true, received ${describeValue(record4.steadyCover)}; leave it out to skip the check.`);
8010
+ }
8011
+ result.steadyCover = true;
8012
+ }
7039
8013
  if (Object.keys(result).length === 0) {
7040
- throw invalidScenario(scenarioPath, `'${objectPath}' must set at least one of ${STARTUP_CEILINGS.join(", ")}; an empty startup assertion observes nothing.`);
8014
+ throw invalidScenario(scenarioPath, `'${objectPath}' must set at least one of ${[...STARTUP_CEILINGS, "maxOffscreenBytes", "steadyCover"].join(", ")}; an empty startup assertion observes nothing.`);
7041
8015
  }
7042
8016
  return result;
7043
8017
  }
@@ -7337,12 +8311,116 @@ function validateSceneNodesAssertion(value, scenarioPath, objectPath) {
7337
8311
  );
7338
8312
  return result;
7339
8313
  }
8314
+ function validateFootSlipAssertion(value, scenarioPath, objectPath) {
8315
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8316
+ rejectUnknownKeys(record4, ["atStep", "entity", "feet", "maxSlideSpeed", "maxSlip", "stepSeconds"], scenarioPath, objectPath);
8317
+ const feet = record4.feet;
8318
+ if (!Array.isArray(feet) || feet.length === 0 || feet.some((foot) => typeof foot !== "string" || foot.trim() === "") || new Set(feet).size !== feet.length)
8319
+ throw invalidScenario(scenarioPath, `${objectPath}.feet must be a non-empty array of unique node names; got ${describeValue(feet)}.`);
8320
+ const maxSlip = optionalPositiveNumber(record4, "maxSlip", scenarioPath, objectPath);
8321
+ const maxSlideSpeed = optionalPositiveNumber(record4, "maxSlideSpeed", scenarioPath, objectPath);
8322
+ if (maxSlip === void 0 && maxSlideSpeed === void 0)
8323
+ throw invalidScenario(scenarioPath, `${objectPath}.maxSlip or ${objectPath}.maxSlideSpeed is required; a slip measure with no ceiling bounds nothing.`);
8324
+ return {
8325
+ atStep: requireString(record4, "atStep", scenarioPath, objectPath),
8326
+ ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
8327
+ feet,
8328
+ ...present("maxSlideSpeed", maxSlideSpeed),
8329
+ ...present("maxSlip", maxSlip),
8330
+ ...present("stepSeconds", optionalPositiveNumber(record4, "stepSeconds", scenarioPath, objectPath))
8331
+ };
8332
+ }
8333
+ function validateSightLineAssertion(value, scenarioPath, objectPath) {
8334
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8335
+ rejectUnknownKeys(record4, ["entity", "maxBlockedRatio"], scenarioPath, objectPath);
8336
+ const maxBlockedRatio = optionalRatio(record4, "maxBlockedRatio", scenarioPath, objectPath);
8337
+ if (maxBlockedRatio === void 0) throw invalidScenario(scenarioPath, `${objectPath}.maxBlockedRatio is required; a sight line with no allowed blocked share bounds nothing.`);
8338
+ return {
8339
+ ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
8340
+ maxBlockedRatio
8341
+ };
8342
+ }
8343
+ function validateEngineCostAssertion(value, scenarioPath, objectPath) {
8344
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8345
+ rejectUnknownKeys(record4, ["maxInFrame", "maxPerFrame", "minWindows", "moving", "skipWindows", "source", "still"], scenarioPath, objectPath);
8346
+ const bounds = (key, owner = record4, at = objectPath) => {
8347
+ if (!hasKey(owner, key)) return void 0;
8348
+ const table = requireRecord(owner[key], scenarioPath, `${at}.${key}`);
8349
+ const names = Object.keys(table);
8350
+ if (names.length === 0) throw invalidScenario(scenarioPath, `'${at}.${key}' names no counter.`);
8351
+ for (const name of names) {
8352
+ const bound = table[name];
8353
+ if (typeof bound !== "number" || !Number.isFinite(bound) || bound < 0)
8354
+ throw invalidScenario(scenarioPath, `'${at}.${key}.${name}' must be a non-negative number, received ${describeValue(bound)}.`);
8355
+ }
8356
+ return table;
8357
+ };
8358
+ const maxPerFrame = bounds("maxPerFrame");
8359
+ const maxInFrame = bounds("maxInFrame");
8360
+ let still;
8361
+ if (hasKey(record4, "still")) {
8362
+ const at = `${objectPath}.still`;
8363
+ const stillRecord = requireRecord(record4.still, scenarioPath, at);
8364
+ rejectUnknownKeys(stillRecord, ["maxPerFrame", "windows"], scenarioPath, at);
8365
+ const windows = optionalPositiveInteger(stillRecord, "windows", scenarioPath, at);
8366
+ const stillBounds = bounds("maxPerFrame", stillRecord, at);
8367
+ if (windows === void 0 || stillBounds === void 0)
8368
+ throw invalidScenario(scenarioPath, `${at} needs 'windows' and 'maxPerFrame'.`);
8369
+ still = { maxPerFrame: stillBounds, windows };
8370
+ }
8371
+ let moving;
8372
+ if (hasKey(record4, "moving")) {
8373
+ const at = `${objectPath}.moving`;
8374
+ const movingRecord = requireRecord(record4.moving, scenarioPath, at);
8375
+ rejectUnknownKeys(movingRecord, ["maxInFrame", "maxPerFrame"], scenarioPath, at);
8376
+ if (still === void 0) throw invalidScenario(scenarioPath, `${at} needs 'still': the moving windows are the ones after it.`);
8377
+ const movingPerFrame = bounds("maxPerFrame", movingRecord, at);
8378
+ const movingInFrame = bounds("maxInFrame", movingRecord, at);
8379
+ if (movingPerFrame === void 0 && movingInFrame === void 0)
8380
+ throw invalidScenario(scenarioPath, `${at} must bound at least one counter.`);
8381
+ moving = { ...present("maxPerFrame", movingPerFrame), ...present("maxInFrame", movingInFrame) };
8382
+ }
8383
+ if (maxPerFrame === void 0 && maxInFrame === void 0 && still === void 0 && moving === void 0)
8384
+ throw invalidScenario(scenarioPath, `${objectPath} must bound at least one counter in 'maxPerFrame', 'maxInFrame', 'still' or 'moving'.`);
8385
+ const source = requireString(record4, "source", scenarioPath, objectPath);
8386
+ if (source.trim().length < 12)
8387
+ throw invalidScenario(scenarioPath, `'${objectPath}.source' must say where the bounds came from.`);
8388
+ return {
8389
+ ...present("maxPerFrame", maxPerFrame),
8390
+ ...present("maxInFrame", maxInFrame),
8391
+ ...present("minWindows", optionalPositiveInteger(record4, "minWindows", scenarioPath, objectPath)),
8392
+ ...present("skipWindows", optionalNonNegativeInteger(record4, "skipWindows", scenarioPath, objectPath)),
8393
+ source,
8394
+ ...present("still", still),
8395
+ ...present("moving", moving)
8396
+ };
8397
+ }
8398
+ function validateHudAuditAssertion(value, scenarioPath, objectPath) {
8399
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8400
+ rejectUnknownKeys(record4, ["minContrast", "noDebugText"], scenarioPath, objectPath);
8401
+ const noDebugText = optionalBoolean(record4, "noDebugText", scenarioPath, objectPath);
8402
+ if (noDebugText === false) {
8403
+ throw invalidScenario(scenarioPath, `'${objectPath}.noDebugText' may only be true; remove the key to stop scanning for developer text.`);
8404
+ }
8405
+ const minContrast = optionalNumber2(record4, "minContrast", scenarioPath, objectPath);
8406
+ if (minContrast !== void 0 && (minContrast < 1 || minContrast > 21)) {
8407
+ throw invalidScenario(scenarioPath, `'${objectPath}.minContrast' must be between 1 and 21, received ${describeValue(minContrast)}.`);
8408
+ }
8409
+ if (noDebugText === void 0 && minContrast === void 0) {
8410
+ throw invalidScenario(scenarioPath, `${objectPath} must declare at least one of 'minContrast' or 'noDebugText'.`);
8411
+ }
8412
+ return {
8413
+ ...present("minContrast", minContrast),
8414
+ ...noDebugText === void 0 ? {} : { noDebugText: true }
8415
+ };
8416
+ }
7340
8417
  function validateAnimationAssertion(value, scenarioPath, objectPath) {
7341
8418
  const record4 = requireRecord(value, scenarioPath, objectPath);
7342
- rejectUnknownKeys(record4, ["advancedFrames", "allowTrivial", "clip", "entered", "entity", "finished", "maxFootSlide", "strideSynced"], scenarioPath, objectPath);
8419
+ rejectUnknownKeys(record4, ["advancedFrames", "allowTrivial", "atStep", "clip", "entered", "entity", "finished", "maxFootSlide", "strideSynced"], scenarioPath, objectPath);
7343
8420
  return {
7344
8421
  ...present("advancedFrames", optionalNumber2(record4, "advancedFrames", scenarioPath, objectPath)),
7345
8422
  ...present("allowTrivial", optionalTrivialityReason(record4, "allowTrivial", scenarioPath, objectPath)),
8423
+ ...present("atStep", optionalString(record4, "atStep", scenarioPath, objectPath)),
7346
8424
  ...present("clip", optionalString(record4, "clip", scenarioPath, objectPath)),
7347
8425
  ...present("entered", optionalBoolean(record4, "entered", scenarioPath, objectPath)),
7348
8426
  ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
@@ -7372,12 +8450,14 @@ function validatePathAssertion(value, scenarioPath, objectPath) {
7372
8450
  const atSteps = Array.isArray(record4.atSteps) ? record4.atSteps.map((step, index) => {
7373
8451
  const stepPath = `${objectPath}.atSteps[${index}]`;
7374
8452
  const entry = requireRecord(step, scenarioPath, stepPath);
7375
- if (!hasKey(entry, "equals") && entry.textIncludes === void 0) {
7376
- throw invalidScenario(scenarioPath, `'${stepPath}' must set equals or textIncludes; a labeled step with no expectation passes on any value.`);
8453
+ const stepLte = optionalNumber2(entry, "lte", scenarioPath, stepPath);
8454
+ if (!hasKey(entry, "equals") && entry.textIncludes === void 0 && stepLte === void 0) {
8455
+ throw invalidScenario(scenarioPath, `'${stepPath}' must set equals, lte or textIncludes; a labeled step with no expectation passes on any value.`);
7377
8456
  }
7378
8457
  return {
7379
8458
  ...hasKey(entry, "equals") ? { equals: entry.equals } : {},
7380
8459
  label: requireString(entry, "label", scenarioPath, stepPath),
8460
+ ...present("lte", stepLte),
7381
8461
  ...present("textIncludes", optionalString(entry, "textIncludes", scenarioPath, stepPath))
7382
8462
  };
7383
8463
  }) : void 0;
@@ -7534,7 +8614,7 @@ function validateNestedAssertionKeys(kind, value, scenarioPath, suffix) {
7534
8614
  if (Array.isArray(value.atSteps)) {
7535
8615
  value.atSteps.forEach((step, index) => {
7536
8616
  if (isRecord3(step)) {
7537
- rejectUnknownKeys(step, kind === "components" ? ["equals", "label"] : ["equals", "label", "textIncludes"], scenarioPath, `assert.${kind}${suffix}.atSteps[${index}]`);
8617
+ rejectUnknownKeys(step, kind === "components" ? ["equals", "label"] : ["equals", "label", "lte", "textIncludes"], scenarioPath, `assert.${kind}${suffix}.atSteps[${index}]`);
7538
8618
  }
7539
8619
  });
7540
8620
  }
@@ -7543,7 +8623,7 @@ function validateNestedAssertionKeys(kind, value, scenarioPath, suffix) {
7543
8623
  const fields = {
7544
8624
  entityVisible: ["entity", "minProjectedPixels", "throughoutFrames"],
7545
8625
  frameDiff: ["baselineImage", "maxChangedPixelRatio", "minChangedPixelRatio"],
7546
- region: ["element", "height", "maxDarkPixelRatio", "maxLuminance", "minDarkPixelRatio", "minNonblankPixelRatio", "width", "x", "y"]
8626
+ region: ["element", "height", "maxDarkPixelRatio", "maxLuminance", "minDarkPixelRatio", "minNonblankPixelRatio", "minSharpness", "width", "x", "y"]
7547
8627
  };
7548
8628
  for (const [field, keys] of Object.entries(fields)) {
7549
8629
  if (isRecord3(value[field])) {
@@ -7599,7 +8679,7 @@ function rejectRenderChainExpectationKeys(value, scenarioPath, objectPath) {
7599
8679
  }
7600
8680
  }
7601
8681
  }
7602
- var STARTUP_CEILINGS, PIPELINE_CENSUS_CEILINGS, SCENE_FLAGS, SCENE_NODE_SELECTOR_KEYS, SCENE_NODE_BOUNDS, RENDER_CHAIN_NESTED_KEYS;
8682
+ var LEGACY_SCAFFOLD_FRAME_MS, LEGACY_SCAFFOLD_FRAME_REASON, STARTUP_CEILINGS, PIPELINE_CENSUS_CEILINGS, SCENE_FLAGS, SCENE_NODE_SELECTOR_KEYS, SCENE_NODE_BOUNDS, RENDER_CHAIN_NESTED_KEYS;
7603
8683
  var init_schema_accessors = __esm({
7604
8684
  "src/scenario/schema-accessors.ts"() {
7605
8685
  init_assertions();
@@ -7607,6 +8687,8 @@ var init_schema_accessors = __esm({
7607
8687
  init_errors();
7608
8688
  init_schema_base();
7609
8689
  init_generated_assertion_validators();
8690
+ LEGACY_SCAFFOLD_FRAME_MS = 33;
8691
+ LEGACY_SCAFFOLD_FRAME_REASON = "Scaffolded before 0.3.7 with a 33 ms pin, which passes at 30 fps. Drop maxFrameMsP95 to hold this game to 16.7 ms.";
7610
8692
  STARTUP_CEILINGS = ["maxEnteredMs", "maxCompileSettledMs", "maxReadyMs"];
7611
8693
  PIPELINE_CENSUS_CEILINGS = [
7612
8694
  "maxNodeBuildsAfterWarmUpSettled",
@@ -7657,12 +8739,25 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7657
8739
  if (value.bootFailure !== void 0 && target !== "web") {
7658
8740
  throw invalidScenario(scenarioPath, "Scenario bootFailure is browser-only and requires target 'web'.");
7659
8741
  }
8742
+ if (value.clock !== void 0 && value.clock !== "wall-clock") {
8743
+ throw invalidScenario(scenarioPath, "Scenario clock must be 'wall-clock' when present.");
8744
+ }
8745
+ if (value.clock !== void 0 && target !== "web") {
8746
+ throw invalidScenario(scenarioPath, "Scenario clock is browser-only and requires target 'web'.");
8747
+ }
7660
8748
  if (value.reducedMotion !== void 0 && value.reducedMotion !== "reduce") {
7661
8749
  throw invalidScenario(scenarioPath, "Scenario reducedMotion must be 'reduce' when present.");
7662
8750
  }
7663
8751
  if (value.reducedMotion !== void 0 && target !== "web") {
7664
8752
  throw invalidScenario(scenarioPath, "Scenario reducedMotion is browser-only and requires target 'web'.");
7665
8753
  }
8754
+ if (value.network !== void 0 && !isRecord3(value.network)) {
8755
+ throw invalidScenario(scenarioPath, "Scenario network must be an object with downloadKbps and latencyMs.");
8756
+ }
8757
+ const network = value.network === void 0 ? void 0 : validateNetworkProfile(value.network, scenarioPath);
8758
+ if (network !== void 0 && target !== "web") {
8759
+ throw invalidScenario(scenarioPath, "Scenario network is browser-only and requires target 'web'.");
8760
+ }
7666
8761
  const inputDelivery = value.inputDelivery ?? "deterministic";
7667
8762
  if (inputDelivery !== "deterministic" && inputDelivery !== "focused-dom") {
7668
8763
  throw invalidScenario(scenarioPath, "Scenario inputDelivery must be deterministic or focused-dom.");
@@ -7677,7 +8772,7 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7677
8772
  throw invalidScenario(scenarioPath, "Scenario subject must be a non-empty entity id when present.");
7678
8773
  }
7679
8774
  const subject = typeof value.subject === "string" ? value.subject : void 0;
7680
- const steps = value.steps.map((step, index) => validateStep(step, scenarioPath, index));
8775
+ const steps = value.steps.flatMap((step, index) => isRecord3(step) && step.kind === "explore" ? expandExploreStep(step, scenarioPath, index) : [step]).map((step, index) => validateStep(step, scenarioPath, index));
7681
8776
  if (steps.some(({ kind }) => kind === "aimAt") && subject === void 0) {
7682
8777
  throw invalidScenario(scenarioPath, "A step with kind 'aimAt' aims the subject player start; declare scenario.subject or replace the step.");
7683
8778
  }
@@ -7689,8 +8784,10 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7689
8784
  ...assertions === void 0 ? {} : { assert: assertions },
7690
8785
  ...typeof value.awaitStartup === "boolean" ? { awaitStartup: value.awaitStartup } : {},
7691
8786
  ...value.bootFailure === "renderer-no-adapter" ? { bootFailure: value.bootFailure } : {},
8787
+ ...value.clock === "wall-clock" ? { clock: value.clock } : {},
7692
8788
  inputDelivery,
7693
8789
  name,
8790
+ ...network === void 0 ? {} : { network },
7694
8791
  ...value.parity === void 0 ? {} : { parity: validateParityConfig(requireRecord(value.parity, scenarioPath, "parity"), scenarioPath) },
7695
8792
  ...value.reducedMotion === "reduce" ? { reducedMotion: value.reducedMotion } : {},
7696
8793
  schemaVersion: 1,
@@ -7704,6 +8801,55 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7704
8801
  warmupFrames: optionalNonNegativeInteger(value, "warmupFrames", scenarioPath, "scenario") ?? 0
7705
8802
  };
7706
8803
  }
8804
+ function expandExploreStep(value, scenarioPath, index) {
8805
+ rejectUnknownKeys(value, ["actions", "kind", "label", "move", "pointer", "seed", "ticks"], scenarioPath, `steps[${index}]`);
8806
+ const keys = (field) => {
8807
+ const list = value[field];
8808
+ if (list === void 0 && field === "actions") return [];
8809
+ if (!Array.isArray(list) || list.length === 0 || list.some((key) => typeof key !== "string" || key.trim() === "") || new Set(list).size !== list.length) {
8810
+ throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' must define ${field} as a non-empty array of unique key names.`);
8811
+ }
8812
+ return list;
8813
+ };
8814
+ if (!Number.isSafeInteger(value.seed)) throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' must define seed as an integer.`);
8815
+ const ticks = positiveInteger2(value.ticks);
8816
+ if (ticks === void 0) throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' must define ticks as a positive integer.`);
8817
+ if (value.pointer !== void 0 && typeof value.pointer !== "boolean") throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' pointer must be a boolean.`);
8818
+ if (value.label !== void 0 && (typeof value.label !== "string" || value.label.trim() === "")) throw invalidStep(scenarioPath, `Scenario step ${index} label must be a non-empty string.`);
8819
+ const move = keys("move");
8820
+ const actions = keys("actions");
8821
+ let state = value.seed >>> 0;
8822
+ const random = () => {
8823
+ state = state + 1831565813 >>> 0;
8824
+ let t = state;
8825
+ t = Math.imul(t ^ t >>> 15, t | 1);
8826
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
8827
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
8828
+ };
8829
+ const pick = (list) => list[Math.floor(random() * list.length)];
8830
+ const steps = [];
8831
+ let heading = pick(move);
8832
+ for (let left = ticks; left > 0; ) {
8833
+ const holdTicks = Math.min(left, 10 + Math.floor(random() * 50));
8834
+ if (random() < 0.2) heading = pick(move);
8835
+ const press = /* @__PURE__ */ new Set([heading]);
8836
+ if (move.length > 1 && random() < 0.35) press.add(pick(move));
8837
+ if (actions.length > 0 && random() < 0.5) {
8838
+ press.add(pick(actions));
8839
+ if (random() < 0.25) press.add(pick(actions));
8840
+ }
8841
+ steps.push({
8842
+ holdTicks,
8843
+ kind: "input",
8844
+ press: [...press],
8845
+ ...value.pointer === true ? { pointerPosition: { x: random(), y: random() } } : {},
8846
+ release: true
8847
+ });
8848
+ left -= holdTicks;
8849
+ }
8850
+ if (typeof value.label === "string") steps[steps.length - 1].label = value.label;
8851
+ return steps;
8852
+ }
7707
8853
  function validateArtifacts(value, scenarioPath) {
7708
8854
  rejectUnknownKeys(value, ["console", "contactSheet", "effectLog", "network", "runtimeTrace", "screenshots"], scenarioPath, "artifacts");
7709
8855
  for (const key of ["console", "contactSheet", "network", "runtimeTrace"]) {
@@ -7786,6 +8932,21 @@ function validateParityTargets(value, scenarioPath, objectPath) {
7786
8932
  return target;
7787
8933
  });
7788
8934
  }
8935
+ function validateNetworkProfile(value, scenarioPath) {
8936
+ rejectUnknownKeys(value, ["downloadKbps", "latencyMs"], scenarioPath, "network");
8937
+ const downloadKbps = value.downloadKbps;
8938
+ if (typeof downloadKbps !== "number" || !Number.isFinite(downloadKbps) || downloadKbps <= 0) {
8939
+ throw invalidScenario(
8940
+ scenarioPath,
8941
+ "Scenario network.downloadKbps must be a positive number of kilobits per second."
8942
+ );
8943
+ }
8944
+ const latencyMs = value.latencyMs;
8945
+ if (typeof latencyMs !== "number" || !Number.isFinite(latencyMs) || latencyMs < 0) {
8946
+ throw invalidScenario(scenarioPath, "Scenario network.latencyMs must be a non-negative number.");
8947
+ }
8948
+ return { downloadKbps, latencyMs };
8949
+ }
7789
8950
  function validateSetup(value, scenarioPath, subject) {
7790
8951
  rejectUnknownKeys(value, ["aim", "entities", "place", "resources", "spawn"], scenarioPath, "setup");
7791
8952
  const spawn10 = validateSpawnRequest(value.spawn, scenarioPath);
@@ -8000,7 +9161,7 @@ function validateStep(value, scenarioPath, index) {
8000
9161
  const waitTicks = positiveInteger2(value.waitTicks);
8001
9162
  const kind = value.kind === "aimAt" ? "aimAt" : value.kind === "click" ? "click" : value.kind === "lifecycle" ? "lifecycle" : value.kind === "wait" ? "wait" : value.kind === "input" ? "input" : void 0;
8002
9163
  if (value.kind !== void 0 && kind === void 0) {
8003
- throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'input', 'lifecycle', or 'wait'.`);
9164
+ throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'explore', 'input', 'lifecycle', or 'wait'.`);
8004
9165
  }
8005
9166
  const at = validateClickTarget(value.at, scenarioPath, index);
8006
9167
  const target = validateAimTarget(value.target, scenarioPath, index);
@@ -8328,6 +9489,14 @@ function validateStepLabels(steps, assertions, scenarioPath) {
8328
9489
  for (const [index, assertion] of (assertions.tone ?? []).entries()) {
8329
9490
  requireLabel(assertion.atStep, `assert.tone[${index}].atStep`);
8330
9491
  }
9492
+ for (const [index, assertion] of (assertions.animation ?? []).entries()) {
9493
+ requireLabel(assertion.atStep, `assert.animation[${index}].atStep`);
9494
+ }
9495
+ for (const [index, assertion] of (assertions.footSlip ?? []).entries()) {
9496
+ requireLabel(assertion.atStep, `assert.footSlip[${index}].atStep`);
9497
+ if (assertions.footSlip.findIndex(({ atStep }) => atStep === assertion.atStep) !== index)
9498
+ throw invalidScenario(scenarioPath, `Assertion 'assert.footSlip[${index}]' repeats atStep '${assertion.atStep}'; list every foot in one assertion.`);
9499
+ }
8331
9500
  for (const [index, assertion] of (assertions.signals ?? []).entries()) {
8332
9501
  requireLabel(assertion.atStep, `assert.signals[${index}].atStep`);
8333
9502
  }
@@ -8368,6 +9537,9 @@ function validateAssertions(value, scenarioPath) {
8368
9537
  if (Array.isArray(value.signals) && value.signals.length === 0) {
8369
9538
  throw invalidScenario(scenarioPath, "Assertion 'assert.signals' must contain at least one signal assertion.");
8370
9539
  }
9540
+ if (Array.isArray(value.footSlip) && value.footSlip.length === 0) {
9541
+ throw invalidScenario(scenarioPath, "Assertion 'assert.footSlip' must contain at least one foot-slip assertion.");
9542
+ }
8371
9543
  if (Array.isArray(value.tone) && value.tone.length === 0) {
8372
9544
  throw invalidScenario(scenarioPath, "Assertion 'assert.tone' must contain at least one tone assertion.");
8373
9545
  }
@@ -8383,7 +9555,7 @@ function validateAssertions(value, scenarioPath) {
8383
9555
  );
8384
9556
  }
8385
9557
  const diagnostics = isRecord3(value.diagnostics) ? value.diagnostics : void 0;
8386
- const performance = isRecord3(value.performance) ? validatePerformanceAssertion(value.performance, scenarioPath, "assert.performance") : void 0;
9558
+ const performance2 = isRecord3(value.performance) ? validatePerformanceAssertion(value.performance, scenarioPath, "assert.performance") : void 0;
8387
9559
  const deviceMetrics = value.deviceMetrics === void 0 ? void 0 : validateDeviceMetricsAssertion(value.deviceMetrics, scenarioPath, "assert.deviceMetrics");
8388
9560
  const parity = value.parity === void 0 ? void 0 : validateParityAssertion(value.parity, scenarioPath, "assert.parity");
8389
9561
  const framebufferCoverage = isRecord3(value.framebufferCoverage) ? validateFramebufferCoverageAssertion(
@@ -8442,7 +9614,7 @@ function validateAssertions(value, scenarioPath) {
8442
9614
  ...Array.isArray(value.hud) ? {
8443
9615
  hud: value.hud.map((entry, index) => validatePathAssertion(entry, scenarioPath, `assert.hud[${index}]`))
8444
9616
  } : {},
8445
- ...performance === void 0 ? {} : { performance },
9617
+ ...performance2 === void 0 ? {} : { performance: performance2 },
8446
9618
  ...renderChain === void 0 ? {} : { renderChain },
8447
9619
  ...startup === void 0 ? {} : { startup },
8448
9620
  ...pipelineCensus === void 0 ? {} : { pipelineCensus },
@@ -8451,6 +9623,12 @@ function validateAssertions(value, scenarioPath) {
8451
9623
  ...hasKey(value, "causedBy") ? {
8452
9624
  causedBy: requireArray(value, "causedBy", scenarioPath, "assert.causedBy").map((entry, index) => validateCausedByAssertion(entry, scenarioPath, `assert.causedBy[${index}]`))
8453
9625
  } : {},
9626
+ ...hasKey(value, "footSlip") ? {
9627
+ footSlip: requireArray(value, "footSlip", scenarioPath, "assert.footSlip").map((entry, index) => validateFootSlipAssertion(entry, scenarioPath, `assert.footSlip[${index}]`))
9628
+ } : {},
9629
+ ...hasKey(value, "sightLine") ? { sightLine: validateSightLineAssertion(value.sightLine, scenarioPath, "assert.sightLine") } : {},
9630
+ ...hasKey(value, "hudAudit") ? { hudAudit: validateHudAuditAssertion(value.hudAudit, scenarioPath, "assert.hudAudit") } : {},
9631
+ ...hasKey(value, "engineCost") ? { engineCost: validateEngineCostAssertion(value.engineCost, scenarioPath, "assert.engineCost") } : {},
8454
9632
  ...hasKey(value, "sceneNodes") ? {
8455
9633
  sceneNodes: requireArray(value, "sceneNodes", scenarioPath, "assert.sceneNodes").map((entry, index) => validateSceneNodesAssertion(entry, scenarioPath, `assert.sceneNodes[${index}]`))
8456
9634
  } : {},
@@ -8807,8 +9985,10 @@ var init_schema_validate = __esm({
8807
9985
  "assert",
8808
9986
  "awaitStartup",
8809
9987
  "bootFailure",
9988
+ "clock",
8810
9989
  "inputDelivery",
8811
9990
  "name",
9991
+ "network",
8812
9992
  "parity",
8813
9993
  "reducedMotion",
8814
9994
  "schemaVersion",
@@ -8843,7 +10023,7 @@ var init_schema_validate = __esm({
8843
10023
  "wheel",
8844
10024
  "window"
8845
10025
  ];
8846
- MAX_RESOURCE_WAIT_TIMEOUT_MS = 12e4;
10026
+ MAX_RESOURCE_WAIT_TIMEOUT_MS = 3e5;
8847
10027
  }
8848
10028
  });
8849
10029
 
@@ -9408,7 +10588,7 @@ var init_observationFields = __esm({
9408
10588
  "startup",
9409
10589
  "visual"
9410
10590
  ];
9411
- HOST_PLAYTEST_OBSERVATION_FIELDS = ["deviceLifecycle", "deviceMetrics", "tone"];
10591
+ HOST_PLAYTEST_OBSERVATION_FIELDS = ["deviceLifecycle", "deviceMetrics", "footSlip", "hudAudit", "sightLine", "tone"];
9412
10592
  }
9413
10593
  });
9414
10594
 
@@ -9696,6 +10876,7 @@ var init_setup_request = __esm({
9696
10876
  // src/runner/bridgeClient.ts
9697
10877
  var bridgeClient_exports = {};
9698
10878
  __export(bridgeClient_exports, {
10879
+ PENDING_BRIDGE_OPERATIONS_GLOBAL: () => PENDING_BRIDGE_OPERATIONS_GLOBAL,
9699
10880
  PlaytestBridgeError: () => PlaytestBridgeError,
9700
10881
  PlaywrightTransport: () => PlaywrightTransport,
9701
10882
  advanceTimeoutMs: () => advanceTimeoutMs,
@@ -9781,7 +10962,8 @@ async function connectPlaytestBridgeTransport(transport, scenario, timeoutMs = b
9781
10962
  }
9782
10963
  return {
9783
10964
  advance: async (ticks, options) => {
9784
- await transport.call("advance", ticks, advanceTimeoutMs(ticks), options);
10965
+ const result = await transport.call("advance", ticks, advanceTimeoutMs(ticks), options);
10966
+ return typeof result?.ticks === "number" ? result.ticks : void 0;
9785
10967
  },
9786
10968
  applySetup: async (request) => {
9787
10969
  assertBoundedPayload(request);
@@ -9893,15 +11075,30 @@ async function bridgeCall(page, method, argument, timeoutMs = PLAYTEST_PROTOCOL_
9893
11075
  try {
9894
11076
  return await Promise.race([
9895
11077
  page.evaluate(
9896
- async ({ argument: argument2, globalName, method: method2, options: options2 }) => {
11078
+ ({ argument: argument2, globalName, method: method2, options: options2, pendingOperationsGlobal }) => {
9897
11079
  const bridge = globalThis[globalName];
9898
11080
  const operation = bridge?.[method2];
9899
11081
  if (typeof operation !== "function") {
9900
11082
  throw new Error(`Bridge operation '${method2}' is unavailable.`);
9901
11083
  }
9902
- return operation.call(bridge, argument2, options2);
11084
+ const result = operation.call(bridge, argument2, options2);
11085
+ if (result === null || typeof result !== "object" && typeof result !== "function") return result;
11086
+ if (typeof result.then !== "function") return result;
11087
+ const host = globalThis;
11088
+ const pending = host[pendingOperationsGlobal] ?? /* @__PURE__ */ new Set();
11089
+ host[pendingOperationsGlobal] = pending;
11090
+ pending.add(result);
11091
+ const forget = () => pending.delete(result);
11092
+ void result.then(forget, forget);
11093
+ return result;
9903
11094
  },
9904
- { argument, globalName: PLAYTEST_BRIDGE_GLOBAL, method, options }
11095
+ {
11096
+ argument,
11097
+ globalName: PLAYTEST_BRIDGE_GLOBAL,
11098
+ method,
11099
+ options,
11100
+ pendingOperationsGlobal: PENDING_BRIDGE_OPERATIONS_GLOBAL
11101
+ }
9905
11102
  ),
9906
11103
  new Promise((_resolve, reject) => {
9907
11104
  timeout = setTimeout(() => reject(new PlaytestBridgeError(playtestDiagnostic(
@@ -9915,7 +11112,7 @@ async function bridgeCall(page, method, argument, timeoutMs = PLAYTEST_PROTOCOL_
9915
11112
  if (timeout !== void 0) clearTimeout(timeout);
9916
11113
  }
9917
11114
  }
9918
- var STANDALONE_OBSERVATION_FIELD_SET, HOST_OBSERVATION_FIELD_SET, BROWSER_CAPABILITIES, PlaytestBridgeError, PlaywrightTransport;
11115
+ var STANDALONE_OBSERVATION_FIELD_SET, HOST_OBSERVATION_FIELD_SET, BROWSER_CAPABILITIES, PlaytestBridgeError, PlaywrightTransport, PENDING_BRIDGE_OPERATIONS_GLOBAL;
9919
11116
  var init_bridgeClient = __esm({
9920
11117
  "src/runner/bridgeClient.ts"() {
9921
11118
  init_index();
@@ -9962,6 +11159,7 @@ var init_bridgeClient = __esm({
9962
11159
  }).then(() => true).catch(() => false);
9963
11160
  }
9964
11161
  };
11162
+ PENDING_BRIDGE_OPERATIONS_GLOBAL = "__THREENATIVE_PLAYTEST_PENDING_OPERATIONS__";
9965
11163
  }
9966
11164
  });
9967
11165
 
@@ -10019,6 +11217,9 @@ var PlaytestCliUsageError = class extends Error {
10019
11217
  this.name = "PlaytestCliUsageError";
10020
11218
  }
10021
11219
  };
11220
+ function withScenarioClock(config, scenario) {
11221
+ return scenario.clock === "wall-clock" && config.liveClock !== true ? { ...config, liveClock: true } : config;
11222
+ }
10022
11223
  function formatUsage() {
10023
11224
  const flags = Object.entries(PLAYTEST_FLAGS).map(
10024
11225
  ([name, details]) => ` ${name.padEnd(20)} ${details.summary} (default: ${details.default})`
@@ -10254,7 +11455,7 @@ function parseStandalonePlaytestArgs(argv, cwd = process.cwd()) {
10254
11455
  ...flags.get("--xcrun")?.[0] === void 0 ? {} : { xcrunPath: flags.get("--xcrun")[0] }
10255
11456
  };
10256
11457
  }
10257
- var SCENARIO_GLOB = /[*?[]/u;
11458
+ var SCENARIO_GLOB = /[*?[{]/u;
10258
11459
  function expandScenarioPattern(projectPath, pattern) {
10259
11460
  if (!SCENARIO_GLOB.test(pattern)) return [pattern];
10260
11461
  const normalizedPattern = pattern.replaceAll("\\", "/");
@@ -10291,14 +11492,21 @@ function matchGlobParts(pattern, file) {
10291
11492
  return file.length > 0 && segmentMatches(head ?? "", file[0]) && matchGlobParts(tail, file.slice(1));
10292
11493
  }
10293
11494
  function segmentMatches(pattern, value) {
10294
- let expression = "^";
11495
+ return new RegExp(`^${segmentExpression(pattern)}$`, "u").test(value);
11496
+ }
11497
+ function segmentExpression(pattern) {
11498
+ let expression = "";
10295
11499
  for (let index = 0; index < pattern.length; index += 1) {
10296
11500
  const character = pattern[index];
10297
- if (character === "*") expression += "[^/]*";
11501
+ const close = character === "{" ? pattern.indexOf("}", index) : -1;
11502
+ if (close > index) {
11503
+ expression += `(?:${pattern.slice(index + 1, close).split(",").map(segmentExpression).join("|")})`;
11504
+ index = close;
11505
+ } else if (character === "*") expression += "[^/]*";
10298
11506
  else if (character === "?") expression += "[^/]";
10299
11507
  else expression += escapeRegExp(character);
10300
11508
  }
10301
- return new RegExp(`${expression}$`, "u").test(value);
11509
+ return expression;
10302
11510
  }
10303
11511
  function escapeRegExp(value) {
10304
11512
  return value.replace(/[|\\{}()[\]^$+?.]/gu, "\\$&");
@@ -10527,12 +11735,12 @@ function withPerformanceBudget(scenario, budget) {
10527
11735
  maxPassTriangles: { ...budget.maxPassTriangles, ...declared?.maxPassTriangles },
10528
11736
  maxPhaseMsP95: { ...budget.maxPhaseMsP95, ...declared?.maxPhaseMsP95 }
10529
11737
  };
10530
- const performance = {
11738
+ const performance2 = {
10531
11739
  ...budget,
10532
11740
  ...declared,
10533
11741
  ...Object.fromEntries(Object.entries(maps).filter(([, value]) => Object.keys(value).length > 0))
10534
11742
  };
10535
- return { ...scenario, assert: { ...scenario.assert, performance } };
11743
+ return { ...scenario, assert: { ...scenario.assert, performance: performance2 } };
10536
11744
  }
10537
11745
  async function resolveBuildReport(config) {
10538
11746
  if (config.buildReportPath === void 0) return config;
@@ -10986,6 +12194,7 @@ var AdbAndroidDriver = class _AdbAndroidDriver {
10986
12194
  lastError = error.message;
10987
12195
  if (isAdbRefusal(lastError) || attempt === LOGCAT_ATTEMPTS) break;
10988
12196
  await this.adb(["wait-for-device"]).catch(() => void 0);
12197
+ await delay(LOGCAT_RETRY_MS);
10989
12198
  }
10990
12199
  }
10991
12200
  if (output === void 0) throw failedLogcat(args.join(" "), lastError);
@@ -11215,9 +12424,8 @@ ${excerpt}`
11215
12424
  return stdout;
11216
12425
  } catch (error) {
11217
12426
  const detail = error;
11218
- throw new Error(
11219
- `adb ${args.join(" ")} failed: ${detail.stderr || detail.stdout || detail.message}`
11220
- );
12427
+ const silent = `${detail.message.trim()} (exit ${String(detail.code)}, signal ${String(detail.signal)})`;
12428
+ throw new Error(`adb ${args.join(" ")} failed: ${detail.stderr || detail.stdout || silent}`);
11221
12429
  }
11222
12430
  }
11223
12431
  async waitForScreenRecorder() {
@@ -11282,7 +12490,9 @@ function parseAndroidConsoleEntries(output, app) {
11282
12490
  `(?:^|[^\\w.])${app.packageName.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}(?=[:/\\s,})]|$)`,
11283
12491
  "u"
11284
12492
  );
11285
- return output.split(/\r?\n/u).filter((line) => !/^[VDIWEF]\/(?:SurfaceSyncGroup|TransitionController)\(/u.test(line)).filter((line) => {
12493
+ return output.split(/\r?\n/u).filter(
12494
+ (line) => !/^[VDIWEF]\/(?:SurfaceSyncGroup|TransitionController|AppHibernationService)\(/u.test(line)
12495
+ ).filter((line) => {
11286
12496
  if (app === void 0) return /Mystral|THREENATIVE|chromium/u.test(line);
11287
12497
  if (app.pids.size === 0) return line.trim().length > 0;
11288
12498
  const pid = /^[VDIWEF]\/[^\n(]+\(\s*(\d+)\)/u.exec(line)?.[1];
@@ -11297,7 +12507,8 @@ function isPlatformWebViewNoise(text) {
11297
12507
  return !/:CONSOLE\(|Mystral|THREENATIVE/u.test(text);
11298
12508
  }
11299
12509
  var TOUCH_AXIS_MAX = 32767;
11300
- var LOGCAT_ATTEMPTS = 2;
12510
+ var LOGCAT_ATTEMPTS = 4;
12511
+ var LOGCAT_RETRY_MS = 1e3;
11301
12512
  var LOGCAT_ERROR_LIMIT = 2e3;
11302
12513
  function parseAndroidTouchViewport(output) {
11303
12514
  const match = /Viewport\s+INTERNAL:\s*displayId=0,[\s\S]*?(?:orientation=(\d+),\s*)?logicalFrame=\[\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*(-?\d+)\s*\],\s*physicalFrame=\[\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*(-?\d+)\s*\],\s*deviceSize=\[\s*(\d+),\s*(\d+)\s*\]/u.exec(output);
@@ -11904,6 +13115,24 @@ function startupLine(overview) {
11904
13115
  if (overview.page?.adapter !== void 0) parts.push(`adapter ${overview.page.adapter}`);
11905
13116
  return overview.startupMs === void 0 && overview.page === void 0 && overview.startup === void 0 ? void 0 : ` startup ${parts.join(" \xB7 ")}`;
11906
13117
  }
13118
+ var REVEAL_ESTIMATE_LINK_MBIT = 20;
13119
+ function revealLine(overview) {
13120
+ const offscreen = overview.startup?.offscreenBytes;
13121
+ if (offscreen === void 0) return void 0;
13122
+ const mb2 = (bytes) => `${(bytes / 1e6).toFixed(1)} MB`;
13123
+ const seconds = offscreen.awaitedBytes * 8 / (REVEAL_ESTIMATE_LINK_MBIT * 1e6);
13124
+ const parts = [
13125
+ `awaited ${mb2(offscreen.awaitedBytes)}`,
13126
+ `off-screen ${mb2(offscreen.offscreenBytes)}`,
13127
+ `est. reveal download ${seconds.toFixed(1)} s at ${REVEAL_ESTIMATE_LINK_MBIT} Mbit/s`
13128
+ ];
13129
+ if (offscreen.unsizedFiles > 0) parts.push(`${offscreen.unsizedFiles} file(s) with no manifest size`);
13130
+ const worst = offscreen.top[0];
13131
+ const tail = offscreen.offscreenBytes > 0 && worst !== void 0 ? `
13132
+ largest off-screen: ${offscreen.top.map((file) => `${file.path} ${mb2(file.bytes)} (${file.reason})`).join(", ")}${offscreen.warn ? `
13133
+ warning: ${offscreen.fix}` : ""}` : "";
13134
+ return ` reveal ${parts.join(" \xB7 ")}${tail}`;
13135
+ }
11907
13136
  function screenLine(overview) {
11908
13137
  const { screen } = overview;
11909
13138
  if (screen === void 0) return void 0;
@@ -11946,6 +13175,7 @@ function formatSceneOverview(overview) {
11946
13175
  const lines = [
11947
13176
  `scene overview \u2014 ${overview.url}`,
11948
13177
  startupLine(overview),
13178
+ revealLine(overview),
11949
13179
  screenLine(overview),
11950
13180
  ` runtime core ${runtime.core ?? "?"} \xB7 rapier ${runtime.rapier ?? "none"} \xB7 seed ${runtime.seed ?? "none"} \xB7 clock ${runtime.clock}${runtime.tick === void 0 ? "" : ` at tick ${runtime.tick}`}`,
11951
13181
  entities.observed === 0 ? " entities no entities observed \u2014 the game may register none, or the bridge sampled before startup" : ` entities ${entities.observed} registered with the bridge, ${entities.visible} visible, ${entities.hidden} hidden`,
@@ -12030,273 +13260,96 @@ async function observeScene(url, options = {}) {
12030
13260
  };
12031
13261
  } finally {
12032
13262
  await browser.close();
12033
- }
12034
- }
12035
- async function pageProbe(page, consoleErrors4) {
12036
- const probe = await page.evaluate(async () => {
12037
- const canvas = document.querySelector("canvas");
12038
- const gpu = navigator.gpu;
12039
- let adapter;
12040
- let adapterInfo;
12041
- if (gpu !== void 0) {
12042
- const found = await gpu.requestAdapter();
12043
- const info = found?.info;
12044
- if (info !== void 0) {
12045
- adapterInfo = Object.fromEntries(
12046
- Object.entries(info).filter(([, value]) => typeof value === "string" && value.length > 0)
12047
- );
12048
- adapter = [info.vendor, info.architecture, info.device, info.description].filter(Boolean).join(" ").trim();
12049
- }
12050
- }
12051
- return {
12052
- ...adapter === void 0 || adapter.length === 0 ? {} : { adapter },
12053
- ...adapterInfo === void 0 ? {} : { adapterInfo },
12054
- ...canvas === null ? {} : {
12055
- canvas: {
12056
- dpr: globalThis.devicePixelRatio,
12057
- height: canvas.height,
12058
- width: canvas.width
12059
- }
12060
- }
12061
- };
12062
- }).catch(() => ({}));
12063
- return { ...probe, consoleErrors: [...consoleErrors4] };
12064
- }
12065
- async function screenshotStats(page, inspectFrame2) {
12066
- try {
12067
- return inspectFrame2(await page.screenshot({ type: "png" }));
12068
- } catch {
12069
- return void 0;
12070
- }
12071
- }
12072
- async function initStandalonePlaytest(projectPath = process.cwd()) {
12073
- const files = {
12074
- "playtest.adapter.example.ts": `import { installThreePlaytestBridge } from "@threenative/playtest/three";
12075
-
12076
- installThreePlaytestBridge({
12077
- camera,
12078
- entities: [{ id: "player", object: player }],
12079
- renderer,
12080
- scene,
12081
- });
12082
- `,
12083
- "playtest.config.json": `${JSON.stringify({
12084
- artifactDirectory: "artifacts/playtest",
12085
- scenario: "playtests/smoke.playtest.json",
12086
- url: "http://127.0.0.1:5173"
12087
- }, null, 2)}
12088
- `,
12089
- "playtests/smoke.playtest.json": `${JSON.stringify({
12090
- assert: { movement: { entity: "player", minDistance: 0.1 } },
12091
- name: "smoke",
12092
- schemaVersion: 1,
12093
- steps: [{ holdTicks: 8, press: "KeyW", release: true }],
12094
- subject: "player",
12095
- target: "web",
12096
- viewport: { height: 720, width: 1280 },
12097
- warmupFrames: 2
12098
- }, null, 2)}
12099
- `
12100
- };
12101
- const created = [];
12102
- for (const relativePath of Object.keys(files)) {
12103
- try {
12104
- await access(resolve(projectPath, relativePath));
12105
- throw new Error(`Refusing to overwrite existing '${relativePath}'. Move it or choose a clean project directory.`);
12106
- } catch (error) {
12107
- if (error instanceof Error && "code" in error && error.code === "ENOENT") continue;
12108
- throw error;
12109
- }
12110
- }
12111
- for (const [relativePath, content] of Object.entries(files)) {
12112
- const absolutePath = resolve(projectPath, relativePath);
12113
- await mkdir(resolve(absolutePath, ".."), { recursive: true });
12114
- await writeFile(absolutePath, content, { encoding: "utf8", flag: "wx" });
12115
- created.push(relativePath);
12116
- }
12117
- return { created };
12118
- }
12119
- var DEFAULT_XVFB_SCREEN = "1600x900x24";
12120
- var HOST_DISPLAY_ENV = "TN_PLAYTEST_HOST_DISPLAY";
12121
- var STRIPPED_WAYLAND_VARS = ["WAYLAND_DISPLAY", "WAYLAND_SOCKET", "XDG_SESSION_TYPE"];
12122
- function decideDisplayStrategy(input) {
12123
- if (input.platform !== "linux") return { kind: "host" };
12124
- const privateXvfb = {
12125
- kind: "private-xvfb",
12126
- screen: input.env.TN_XVFB_SCREEN ?? DEFAULT_XVFB_SCREEN
12127
- };
12128
- if (!hostDisplayRequested(input.env)) return privateXvfb;
12129
- const display = input.env.DISPLAY;
12130
- if (display === void 0 || display.length === 0) {
12131
- throw new Error("TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: the requested host display requires DISPLAY.");
12132
- }
12133
- const available = input.displaySocketExists?.(display) ?? x11DisplayIsUsable(display, input.env);
12134
- if (!available) {
12135
- throw new Error(`TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: cannot connect to requested DISPLAY=${display}. Refusing to substitute a private Xvfb.`);
12136
- }
12137
- return { display, kind: "existing" };
12138
- }
12139
- function hostDisplayRequested(env) {
12140
- const value = env[HOST_DISPLAY_ENV];
12141
- return value === "1" || value?.toLowerCase() === "true";
12142
- }
12143
- function x11DisplayIsUsable(display, env) {
12144
- const probe = spawnSync("xdpyinfo", ["-display", display], { env, stdio: "ignore", timeout: 2e3 });
12145
- if (probe.error) {
12146
- throw new Error(`TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: cannot verify DISPLAY=${display}: xdpyinfo ${probe.error.message}.`);
12147
- }
12148
- return probe.status === 0;
12149
- }
12150
- function childEnvForDisplay(env, display) {
12151
- const child = { ...env };
12152
- for (const name of STRIPPED_WAYLAND_VARS) delete child[name];
12153
- child.DISPLAY = display;
12154
- return child;
12155
- }
12156
- function runNeedsPixels(config, scenario) {
12157
- if (config.headless !== true) return true;
12158
- const takesScreenshot = scenario.artifacts?.screenshots !== false || scenario.steps.some(({ screenshot }) => screenshot !== void 0);
12159
- const evaluatesVisual = (scenario.assert?.visual?.length ?? 0) > 0 || (scenario.assert?.tone?.length ?? 0) > 0;
12160
- return takesScreenshot || evaluatesVisual || scenario.assert?.framebufferCoverage !== void 0;
12161
- }
12162
- async function provideDisplay(options = {}) {
12163
- const env = options.env ?? process.env;
12164
- const platform = options.platform ?? process.platform;
12165
- const strategy = decideDisplayStrategy({
12166
- displaySocketExists: options.displaySocketExists,
12167
- env,
12168
- platform
12169
- });
12170
- if (strategy.kind === "host") {
12171
- return {
12172
- compositor: void 0,
12173
- display: void 0,
12174
- env: { ...env },
12175
- release: async () => void 0,
12176
- strategy
12177
- };
12178
- }
12179
- if (strategy.kind === "existing") {
12180
- return {
12181
- compositor: void 0,
12182
- display: strategy.display,
12183
- env: childEnvForDisplay(env, strategy.display),
12184
- release: async () => void 0,
12185
- strategy
12186
- };
12187
- }
12188
- const commandExists2 = options.commandExists ?? defaultCommandExists;
12189
- if (!commandExists2("Xvfb")) {
12190
- throw new Error(
12191
- "No usable X display is available and Xvfb is not installed, so this pixel-producing run cannot start (Debian/Ubuntu 'xvfb', Arch 'xorg-server-xvfb', Fedora 'xorg-x11-server-Xvfb'). Refusing to render blind."
12192
- );
12193
- }
12194
- const spawnProcess = options.spawnProcess ?? spawn;
12195
- const xvfb = spawnProcess("Xvfb", [
12196
- "-displayfd",
12197
- "3",
12198
- "-nolisten",
12199
- "tcp",
12200
- // COMPOSITE and SHAPE are what a compositing manager needs before it can blend anything, and
12201
- // the native desktop runtime refuses to attach its UI overlay to a display without one. Xvfb
12202
- // does not enable them by default, so every native UI run on a private display reported
12203
- // `TN_UI_OVERLAY:{"attached":false,"reason":"no compositing manager is running"}` — including
12204
- // the starter template's own shipped native-playtests/react-hud scenario, which failed out of
12205
- // the box on a freshly scaffolded project. A browser run does not care either way.
12206
- "+extension",
12207
- "COMPOSITE",
12208
- "+extension",
12209
- "SHAPE",
12210
- "-screen",
12211
- "0",
12212
- strategy.screen
12213
- ], { stdio: ["ignore", "ignore", "pipe", "pipe"] });
12214
- xvfb.on?.("error", () => void 0);
12215
- try {
12216
- const number = await readXvfbDisplayNumber(xvfb);
12217
- const display = `:${number}`;
12218
- const compositor = await startCompositor(display, { commandExists: commandExists2, env, spawnProcess });
12219
- return {
12220
- compositor: compositor?.name,
12221
- display,
12222
- env: childEnvForDisplay(env, display),
12223
- release: async () => {
12224
- if (compositor !== void 0) await stopChild(compositor.child);
12225
- await stopChild(xvfb);
12226
- },
12227
- strategy
12228
- };
12229
- } catch (error) {
12230
- await stopChild(xvfb);
12231
- throw error;
12232
- }
12233
- }
12234
- var COMPOSITORS = [
12235
- { args: ["-n"], name: "xcompmgr" },
12236
- { args: [], name: "picom" },
12237
- { args: [], name: "compton" }
12238
- ];
12239
- var COMPOSITOR_SETTLE_MS = 250;
12240
- async function startCompositor(display, options) {
12241
- const choice = COMPOSITORS.find(({ name }) => options.commandExists(name));
12242
- if (choice === void 0) return void 0;
12243
- const child = options.spawnProcess(choice.name, [...choice.args], {
12244
- env: { ...options.env, DISPLAY: display },
12245
- stdio: "ignore"
12246
- });
12247
- let spawnFailed = false;
12248
- child.on?.("error", () => {
12249
- spawnFailed = true;
12250
- });
12251
- await new Promise((settle) => setTimeout(settle, COMPOSITOR_SETTLE_MS));
12252
- if (spawnFailed) return void 0;
12253
- if ((child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null) return void 0;
12254
- return { child, name: choice.name };
12255
- }
12256
- var XVFB_DISPLAY_TIMEOUT_MS = 3e4;
12257
- async function readXvfbDisplayNumber(xvfb) {
12258
- const report = xvfb.stdio[3];
12259
- if (report === null || report === void 0 || typeof report.on !== "function") {
12260
- throw new Error("Xvfb was spawned without a display-report descriptor to read.");
12261
- }
12262
- const stream = report;
12263
- return new Promise((resolveDisplay, rejectDisplay) => {
12264
- let settled = false;
12265
- const finish = (settle) => {
12266
- if (settled) return;
12267
- settled = true;
12268
- clearTimeout(timer);
12269
- stream.removeListener("data", onData);
12270
- stream.removeListener("close", onClose);
12271
- settle();
12272
- };
12273
- const onData = (chunk) => {
12274
- const number = Number.parseInt(String(chunk).trim(), 10);
12275
- if (Number.isInteger(number) && number >= 0) finish(() => resolveDisplay(number));
13263
+ }
13264
+ }
13265
+ async function pageProbe(page, consoleErrors4) {
13266
+ const probe = await page.evaluate(async () => {
13267
+ const canvas = document.querySelector("canvas");
13268
+ const gpu = navigator.gpu;
13269
+ let adapter;
13270
+ let adapterInfo;
13271
+ if (gpu !== void 0) {
13272
+ const found = await gpu.requestAdapter();
13273
+ const info = found?.info;
13274
+ if (info !== void 0) {
13275
+ adapterInfo = Object.fromEntries(
13276
+ Object.entries(info).filter(([, value]) => typeof value === "string" && value.length > 0)
13277
+ );
13278
+ adapter = [info.vendor, info.architecture, info.device, info.description].filter(Boolean).join(" ").trim();
13279
+ }
13280
+ }
13281
+ return {
13282
+ ...adapter === void 0 || adapter.length === 0 ? {} : { adapter },
13283
+ ...adapterInfo === void 0 ? {} : { adapterInfo },
13284
+ ...canvas === null ? {} : {
13285
+ canvas: {
13286
+ dpr: globalThis.devicePixelRatio,
13287
+ height: canvas.height,
13288
+ width: canvas.width
13289
+ }
13290
+ }
12276
13291
  };
12277
- const onClose = () => finish(() => rejectDisplay(new Error("Xvfb exited before it reported a display.")));
12278
- const timer = setTimeout(() => finish(() => {
12279
- rejectDisplay(new Error(`Xvfb did not report a display within ${XVFB_DISPLAY_TIMEOUT_MS}ms.`));
12280
- }), XVFB_DISPLAY_TIMEOUT_MS);
12281
- stream.on("data", onData);
12282
- stream.on("close", onClose);
12283
- });
13292
+ }).catch(() => ({}));
13293
+ return { ...probe, consoleErrors: [...consoleErrors4] };
12284
13294
  }
12285
- async function stopChild(child) {
12286
- const exitedAlready = () => (child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null;
12287
- if (exitedAlready()) return;
12288
- child.kill("SIGTERM");
12289
- const started = Date.now();
12290
- while (Date.now() - started < 1e3 && !exitedAlready()) {
12291
- await new Promise((resolveWait) => setTimeout(resolveWait, 25));
13295
+ async function screenshotStats(page, inspectFrame2) {
13296
+ try {
13297
+ return inspectFrame2(await page.screenshot({ type: "png" }));
13298
+ } catch {
13299
+ return void 0;
12292
13300
  }
12293
- if (!exitedAlready()) child.kill("SIGKILL");
12294
13301
  }
12295
- function defaultCommandExists(command) {
12296
- const paths = (process.env.PATH ?? "").split(":").filter((segment) => segment.length > 0);
12297
- return paths.some((directory) => existsSync(join(directory, command)));
13302
+ async function initStandalonePlaytest(projectPath = process.cwd()) {
13303
+ const files = {
13304
+ "playtest.adapter.example.ts": `import { installThreePlaytestBridge } from "@threenative/playtest/three";
13305
+
13306
+ installThreePlaytestBridge({
13307
+ camera,
13308
+ entities: [{ id: "player", object: player }],
13309
+ renderer,
13310
+ scene,
13311
+ });
13312
+ `,
13313
+ "playtest.config.json": `${JSON.stringify({
13314
+ artifactDirectory: "artifacts/playtest",
13315
+ scenario: "playtests/smoke.playtest.json",
13316
+ url: "http://127.0.0.1:5173"
13317
+ }, null, 2)}
13318
+ `,
13319
+ "playtests/smoke.playtest.json": `${JSON.stringify({
13320
+ assert: { movement: { entity: "player", minDistance: 0.1 } },
13321
+ name: "smoke",
13322
+ schemaVersion: 1,
13323
+ steps: [{ holdTicks: 8, press: "KeyW", release: true }],
13324
+ subject: "player",
13325
+ target: "web",
13326
+ viewport: { height: 720, width: 1280 },
13327
+ warmupFrames: 2
13328
+ }, null, 2)}
13329
+ `
13330
+ };
13331
+ const created = [];
13332
+ for (const relativePath of Object.keys(files)) {
13333
+ try {
13334
+ await access(resolve(projectPath, relativePath));
13335
+ throw new Error(`Refusing to overwrite existing '${relativePath}'. Move it or choose a clean project directory.`);
13336
+ } catch (error) {
13337
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") continue;
13338
+ throw error;
13339
+ }
13340
+ }
13341
+ for (const [relativePath, content] of Object.entries(files)) {
13342
+ const absolutePath = resolve(projectPath, relativePath);
13343
+ await mkdir(resolve(absolutePath, ".."), { recursive: true });
13344
+ await writeFile(absolutePath, content, { encoding: "utf8", flag: "wx" });
13345
+ created.push(relativePath);
13346
+ }
13347
+ return { created };
12298
13348
  }
12299
13349
 
13350
+ // src/runner/perf.ts
13351
+ init_captureEnvironment();
13352
+
12300
13353
  // src/runner/pipeline-cache-observations.ts
12301
13354
  var marker = "TN_PIPELINE_CACHE:";
12302
13355
  var malformed2 = () => {
@@ -12818,9 +13871,10 @@ async function measureCpuWindow(label, resolveOwner, bridge, advance, options =
12818
13871
  }
12819
13872
 
12820
13873
  // src/runner/perf.ts
12821
- var FRAME_BUDGET_MARKER = "TN_FRAME_BUDGET:";
13874
+ var FRAME_BUDGET_MARKER2 = "TN_FRAME_BUDGET:";
12822
13875
  var PROJECTION_MARKER = "TN_PROJECTION:";
12823
13876
  var HOST_GAP_MARKER = "TN_HOST_GAP:";
13877
+ var PLAYER_FRAME_MARKER = "TN_PLAYER_FRAME:";
12824
13878
  var HITCH_MARKER = "TN_FRAME_HITCH:";
12825
13879
  var SLOW_PHASE_MARKER = "TN_SLOW_PHASE:";
12826
13880
  var PRESENTS_TICK_MARKER = "TN_PRESENTS_TICK:";
@@ -12988,6 +14042,42 @@ function requireSoakFrames(frames) {
12988
14042
  }
12989
14043
  return frames;
12990
14044
  }
14045
+ var RECORD_CAUSES = ["order", "offset", "count", "other"];
14046
+ function summarizePassRecording(frames) {
14047
+ const recorded = frames.filter((frame) => frame.recordCause !== void 0);
14048
+ if (recorded.length === 0) return void 0;
14049
+ const mean = (read2) => recorded.reduce((sum, frame) => {
14050
+ const value = read2(frame);
14051
+ if (value === void 0 || !Number.isFinite(value)) {
14052
+ throw new Error(`TN_PERF_MARKER_MALFORMED: a ${PLAYER_FRAME_MARKER.slice(0, -1)} line with recordCause lacks a stage field`);
14053
+ }
14054
+ return sum + value;
14055
+ }, 0) / recorded.length;
14056
+ const rebuilds = { order: 0, offset: 0, count: 0, other: 0 };
14057
+ for (const frame of recorded) {
14058
+ const cause = frame.recordCause ?? 0;
14059
+ if (!Number.isInteger(cause) || cause < 0 || cause > RECORD_CAUSES.length) {
14060
+ throw new Error(`TN_PERF_MARKER_MALFORMED: recordCause ${cause} is not a Renderer::RecordCause`);
14061
+ }
14062
+ if (cause > 0) rebuilds[RECORD_CAUSES[cause - 1]] += 1;
14063
+ }
14064
+ const cpuFrameMs = mean((frame) => frame.cpuFrameMs);
14065
+ const gameJs = mean((frame) => frame.gameJsMs);
14066
+ const renderPrepare = mean((frame) => frame.renderPrepareMs);
14067
+ const renderEncode = mean((frame) => frame.renderEncodeMs);
14068
+ return {
14069
+ frames: recorded.length,
14070
+ cpuFrameMs,
14071
+ stagesMs: { gameJs, renderPrepare, renderEncode, other: cpuFrameMs - gameJs - renderPrepare - renderEncode },
14072
+ rebuilds,
14073
+ mainRecordedDraws: recorded.reduce((sum, frame) => sum + (frame.mainRecorded ?? 0), 0),
14074
+ auxRecordedDraws: recorded.reduce((sum, frame) => sum + (frame.auxRecorded ?? 0), 0),
14075
+ shadowRecordedDraws: recorded.reduce((sum, frame) => sum + (frame.shadowRecorded ?? 0), 0),
14076
+ shadowDraws: mean((frame) => frame.shadowDraws),
14077
+ recordMs: mean((frame) => frame.recordMs),
14078
+ shadowEncodeMs: mean((frame) => frame.shadowEncodeMs)
14079
+ };
14080
+ }
12991
14081
  var PRESENTS_REACHED_DISPLAY_RATIO = 0.95;
12992
14082
  function rankExactReasons(exact) {
12993
14083
  return Object.entries(exact).filter(([, count]) => typeof count === "number" && count > 0).map(([reason, count]) => ({ count, reason })).sort((left, right) => right.count - left.count || (left.reason < right.reason ? -1 : 1));
@@ -13009,9 +14099,12 @@ function parsePerformanceMarkers(text) {
13009
14099
  const projections = [];
13010
14100
  const projectionPayloads = /* @__PURE__ */ new Set();
13011
14101
  let presentMode;
14102
+ const playerFrames = [];
13012
14103
  const pipelineEvents = parsePipelineEventMarkers(text);
13013
14104
  for (const line of text.split("\n")) {
13014
- const budget = parseMarkerLine(line, FRAME_BUDGET_MARKER);
14105
+ const playerFrame = parseMarkerLine(line, PLAYER_FRAME_MARKER);
14106
+ if (playerFrame !== void 0) playerFrames.push(playerFrame);
14107
+ const budget = parseMarkerLine(line, FRAME_BUDGET_MARKER2);
13015
14108
  if (budget !== void 0) {
13016
14109
  const payload = JSON.stringify(budget);
13017
14110
  if (!budgetPayloads.has(payload)) {
@@ -13054,10 +14147,12 @@ function parsePerformanceMarkers(text) {
13054
14147
  const mode = PRESENT_MODE_PATTERN.exec(line);
13055
14148
  if (mode?.[1] !== void 0) presentMode = mode[1];
13056
14149
  }
14150
+ const passRecording = summarizePassRecording(playerFrames);
13057
14151
  return {
13058
14152
  budgets,
13059
14153
  hitches,
13060
14154
  hostGaps,
14155
+ ...passRecording === void 0 ? {} : { passRecording },
13061
14156
  pipelineEvents,
13062
14157
  pipelineCaches: parsePipelineCacheObservations(text),
13063
14158
  presentGaps,
@@ -13173,6 +14268,7 @@ function assessPerfMarkers(parse, bounds, source, display) {
13173
14268
  presentMode: parse.presentMode,
13174
14269
  slowPhases: parse.slowPhases,
13175
14270
  projections: parse.projections,
14271
+ ...parse.passRecording === void 0 ? {} : { passRecording: parse.passRecording },
13176
14272
  source,
13177
14273
  violations
13178
14274
  };
@@ -13313,7 +14409,7 @@ async function runExecutableOn(args, executable, display) {
13313
14409
  const cpuSnapshots = [];
13314
14410
  const cpuWindows = [];
13315
14411
  let cpuUnavailable = process.platform === "linux" ? void 0 : `on-CPU time needs Linux schedstat accounting; this host is ${process.platform}`;
13316
- const enoughWindows = () => collected.split(FRAME_BUDGET_MARKER).length - 1 >= args.requireWindows + 1;
14412
+ const enoughWindows = () => collected.split(FRAME_BUDGET_MARKER2).length - 1 >= args.requireWindows + 1;
13317
14413
  const readMemory = () => {
13318
14414
  try {
13319
14415
  return readProcStatusMemory(child.pid);
@@ -13406,7 +14502,7 @@ async function runExecutableOn(args, executable, display) {
13406
14502
  function framesReported(text) {
13407
14503
  let total = 0;
13408
14504
  for (const line of text.split("\n")) {
13409
- const window2 = parseMarkerLine(line, FRAME_BUDGET_MARKER);
14505
+ const window2 = parseMarkerLine(line, FRAME_BUDGET_MARKER2);
13410
14506
  if (window2 !== void 0) total += window2.frames;
13411
14507
  }
13412
14508
  return total;
@@ -13416,7 +14512,7 @@ function completeFrameWindows(text) {
13416
14512
  if (end === -1) return [];
13417
14513
  const windows = [];
13418
14514
  for (const line of text.slice(0, end).split("\n")) {
13419
- const window2 = parseMarkerLine(line, FRAME_BUDGET_MARKER);
14515
+ const window2 = parseMarkerLine(line, FRAME_BUDGET_MARKER2);
13420
14516
  if (window2 !== void 0) windows.push(window2);
13421
14517
  }
13422
14518
  return windows;
@@ -13463,7 +14559,7 @@ function newestProcessLines(text) {
13463
14559
  return lines.filter((line) => logcatPid(line) === void 0 || logcatPid(line) === pid).join("\n");
13464
14560
  }
13465
14561
  function newestPid(text) {
13466
- const newest = [...text.split("\n")].reverse().find((line) => line.includes(FRAME_BUDGET_MARKER));
14562
+ const newest = [...text.split("\n")].reverse().find((line) => line.includes(FRAME_BUDGET_MARKER2));
13467
14563
  return newest === void 0 ? void 0 : logcatPid(newest);
13468
14564
  }
13469
14565
  function logcatPid(line) {
@@ -13613,6 +14709,7 @@ function formatPerfReport(report) {
13613
14709
  }
13614
14710
  lines.push(...formatDrawSources(report.budgets));
13615
14711
  lines.push(...formatProjection(report.projections));
14712
+ if (report.passRecording !== void 0) lines.push(...formatPassRecording(report.passRecording));
13616
14713
  const lastGap = report.hostGaps.at(-1);
13617
14714
  if (lastGap !== void 0) {
13618
14715
  lines.push(`host gap segments (${lastGap.frames}-frame window, p50 ms):`);
@@ -13694,6 +14791,15 @@ function formatDrawSources(windows) {
13694
14791
  `main-pass draws by source, window ${String(last.window)} p50: ` + ranked.map(([source, sourceSummary]) => `${source} ${sourceSummary.p50.toFixed(0)}`).join(", ") + (draws === void 0 ? "" : ` \u2014 ${draws.toFixed(0)} draws in the pass`)
13695
14792
  ];
13696
14793
  }
14794
+ function formatPassRecording(summary2) {
14795
+ const { stagesMs: stages, rebuilds } = summary2;
14796
+ const covered = stages.gameJs + stages.renderPrepare + stages.renderEncode;
14797
+ return [
14798
+ `pass recording (${summary2.frames} frames, mean ms per frame): frame CPU ${summary2.cpuFrameMs.toFixed(3)} = game JS ${stages.gameJs.toFixed(3)} + render prepare ${stages.renderPrepare.toFixed(3)} + render encode ${stages.renderEncode.toFixed(3)} + other ${stages.other.toFixed(3)} (the three stages cover ${summary2.cpuFrameMs > 0 ? (100 * covered / summary2.cpuFrameMs).toFixed(1) : "0.0"}%)`,
14799
+ ` main bundle rebuilds: ${rebuilds.order} order, ${rebuilds.offset} uniform offset, ${rebuilds.count} visible count, ${rebuilds.other} other; ${summary2.mainRecordedDraws} main, ${summary2.auxRecordedDraws} aux/velocity and ${summary2.shadowRecordedDraws} shadow draws recorded`,
14800
+ ` recording ${summary2.recordMs.toFixed(3)} ms, shadow direct encode ${summary2.shadowEncodeMs.toFixed(3)} ms (${summary2.shadowDraws.toFixed(1)} shadow draws)`
14801
+ ];
14802
+ }
13697
14803
  function formatProjection(windows) {
13698
14804
  const last = windows.at(-1);
13699
14805
  if (last === void 0) {
@@ -14440,6 +15546,82 @@ function containsPaintedPixels(screenshot) {
14440
15546
  }
14441
15547
  return false;
14442
15548
  }
15549
+ async function sampleHudAudit(page) {
15550
+ return page.evaluate(() => {
15551
+ const MAX_ITEMS = 400;
15552
+ const MAX_TEXT = 120;
15553
+ const parseColour = (value) => {
15554
+ const match = /^rgba?\((.+)\)$/u.exec(value.trim());
15555
+ if (match !== null) {
15556
+ const parts = match[1].split(/[\s,/]+/u).filter((part) => part !== "");
15557
+ const channels = parts.slice(0, 3).map((part) => Number.parseFloat(part));
15558
+ const alphaText = parts[3];
15559
+ const alpha = alphaText === void 0 ? 1 : Number.parseFloat(alphaText);
15560
+ const normalizedAlpha = alpha > 1 ? alpha / 255 : alpha;
15561
+ if (channels.length === 3 && channels.every((channel) => Number.isFinite(channel)) && Number.isFinite(normalizedAlpha)) {
15562
+ return [channels[0], channels[1], channels[2], Math.min(Math.max(normalizedAlpha, 0), 1)];
15563
+ }
15564
+ }
15565
+ const canvas = document.createElement("canvas");
15566
+ canvas.width = 1;
15567
+ canvas.height = 1;
15568
+ const context = canvas.getContext("2d", { willReadFrequently: true });
15569
+ if (context === null) return [0, 0, 0, 1];
15570
+ context.clearRect(0, 0, 1, 1);
15571
+ context.fillStyle = value;
15572
+ context.fillRect(0, 0, 1, 1);
15573
+ const data = context.getImageData(0, 0, 1, 1).data;
15574
+ return [data[0], data[1], data[2], data[3] / 255];
15575
+ };
15576
+ const backing = (element) => {
15577
+ let accumulated = [0, 0, 0, 0];
15578
+ for (let current = element; current !== null; current = current.parentElement) {
15579
+ const [r, g, b, a] = parseColour(window.getComputedStyle(current).backgroundColor);
15580
+ if (a > 0 && accumulated[3] < 0.99) {
15581
+ const near = accumulated[3];
15582
+ const total = near + a * (1 - near);
15583
+ if (total > 0) {
15584
+ accumulated = [
15585
+ (accumulated[0] * near + r * a * (1 - near)) / total,
15586
+ (accumulated[1] * near + g * a * (1 - near)) / total,
15587
+ (accumulated[2] * near + b * a * (1 - near)) / total,
15588
+ total
15589
+ ];
15590
+ }
15591
+ }
15592
+ if (accumulated[3] >= 0.99 || current === document.documentElement) break;
15593
+ }
15594
+ return accumulated;
15595
+ };
15596
+ const items = [];
15597
+ for (const element of document.body.querySelectorAll("*")) {
15598
+ if (items.length === MAX_ITEMS) break;
15599
+ if (element.closest("script, style, canvas, noscript") !== null) continue;
15600
+ let ownText = "";
15601
+ for (const node of element.childNodes) {
15602
+ if (node.nodeType === 3) ownText += node.textContent ?? "";
15603
+ }
15604
+ const text = ownText.replace(/\s+/gu, " ").trim();
15605
+ if (text === "") continue;
15606
+ const style = window.getComputedStyle(element);
15607
+ if (style.display === "none" || style.visibility !== "visible") continue;
15608
+ const opacity = Number.parseFloat(style.opacity);
15609
+ if (!Number.isFinite(opacity) || opacity <= 0) continue;
15610
+ const rect = element.getBoundingClientRect();
15611
+ if (rect.width <= 0 || rect.height <= 0) continue;
15612
+ if (rect.right <= 0 || rect.bottom <= 0 || rect.left >= window.innerWidth || rect.top >= window.innerHeight) continue;
15613
+ const classes = Array.from(element.classList).slice(0, 2).map((name) => `.${name}`).join("");
15614
+ items.push({
15615
+ background: backing(element),
15616
+ color: parseColour(style.color),
15617
+ fontSizePx: Number.parseFloat(style.fontSize),
15618
+ selector: `${element.tagName.toLowerCase()}${element.id === "" ? "" : `#${element.id}`}${classes}`,
15619
+ text: text.slice(0, MAX_TEXT)
15620
+ });
15621
+ }
15622
+ return { items };
15623
+ });
15624
+ }
14443
15625
  async function sampleHud(page, assertions) {
14444
15626
  if (assertions.length === 0) return {};
14445
15627
  const snapshots = await page.evaluate((requestedAssertions) => Object.fromEntries(requestedAssertions.flatMap(({ id, path: path2 }) => {
@@ -14826,9 +16008,50 @@ function regionMetrics(png, region) {
14826
16008
  if (luminance <= maximumLuminance) dark += 1;
14827
16009
  }
14828
16010
  }
14829
- return { darkPixelRatio: dark / pixels, nonblankPixelRatio: nonblank / pixels };
16011
+ return {
16012
+ darkPixelRatio: dark / pixels,
16013
+ nonblankPixelRatio: nonblank / pixels,
16014
+ ...region.minSharpness === void 0 ? {} : { sharpness: regionSharpness(png, x0, y0, x1, y1) }
16015
+ };
16016
+ }
16017
+ function regionSharpness(png, x0, y0, x1, y1) {
16018
+ const width = x1 - x0;
16019
+ const height = y1 - y0;
16020
+ const luma = new Float64Array(width * height);
16021
+ for (let y = 0; y < height; y += 1) {
16022
+ for (let x = 0; x < width; x += 1) {
16023
+ const offset = ((y0 + y) * png.width + x0 + x) * 4;
16024
+ luma[y * width + x] = 0.2126 * png.data[offset] + 0.7152 * png.data[offset + 1] + 0.0722 * png.data[offset + 2];
16025
+ }
16026
+ }
16027
+ const halfWidth = Math.floor(width / 2);
16028
+ const halfHeight = Math.floor(height / 2);
16029
+ const half = new Float64Array(halfWidth * halfHeight);
16030
+ for (let y = 0; y < halfHeight; y += 1) {
16031
+ for (let x = 0; x < halfWidth; x += 1) {
16032
+ const at = 2 * y * width + 2 * x;
16033
+ half[y * halfWidth + x] = (luma[at] + luma[at + 1] + luma[at + width] + luma[at + width + 1]) / 4;
16034
+ }
16035
+ }
16036
+ const coarse = laplacianVariance(half, halfWidth, halfHeight);
16037
+ return coarse === 0 ? 0 : laplacianVariance(luma, width, height) / coarse;
14830
16038
  }
14831
- async function runStep(page, bridge, step, viewport, pathEntity, pathPositions, inputState, movementSampleRequest, finalStep, subject, liveClock = false, cpuWindow, completionWindow) {
16039
+ function laplacianVariance(luma, width, height) {
16040
+ let sum = 0;
16041
+ let squares = 0;
16042
+ let count = 0;
16043
+ for (let y = 1; y < height - 1; y += 1) {
16044
+ for (let x = 1; x < width - 1; x += 1) {
16045
+ const at = y * width + x;
16046
+ const value = luma[at - 1] + luma[at + 1] + luma[at - width] + luma[at + width] - 4 * luma[at];
16047
+ sum += value;
16048
+ squares += value * value;
16049
+ count += 1;
16050
+ }
16051
+ }
16052
+ return count === 0 ? 0 : squares / count - (sum / count) ** 2;
16053
+ }
16054
+ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions, inputState, movementSampleRequest, finalStep, subject, liveClock = false, cpuWindow, stepWindow, sightLine) {
14832
16055
  if (step.waitForResource !== void 0) {
14833
16056
  if (bridge === void 0 || movementSampleRequest === void 0) {
14834
16057
  throw new PlaytestBridgeError(playtestDiagnostic(
@@ -14844,7 +16067,7 @@ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions,
14844
16067
  throw new PlaytestBridgeError(playtestDiagnostic(
14845
16068
  "TN_PLAYTEST_OBSERVATION_UNAVAILABLE",
14846
16069
  `Resource wait for '${wait.id}.${wait.path}' has no timeout.`,
14847
- "Validate the scenario with timeoutMs as a positive integer no greater than 120000."
16070
+ "Validate the scenario with timeoutMs as a positive integer no greater than 300000."
14848
16071
  ));
14849
16072
  }
14850
16073
  const after = await waitForResource({
@@ -14924,8 +16147,8 @@ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions,
14924
16147
  "Advertise runtime.fixedStep from the bridge so ticks are deterministic, or author the step in waitFrames/holdFrames, which are display frames and say so."
14925
16148
  ));
14926
16149
  }
14927
- if (completionWindow !== void 0) {
14928
- await completionWindow();
16150
+ if (stepWindow !== void 0) {
16151
+ await stepWindow(ticks);
14929
16152
  } else if (cpuWindow !== void 0) {
14930
16153
  if (step.kind !== "wait" || step.waitTicks !== 1e3 || ticks < 1e3 || !fixedStep || bridge === void 0 || liveClock) {
14931
16154
  throw new Error("TN_PLAYTEST_CPU_WINDOW_FAILED: measurement requires a fixed-step 1000-tick WAIT");
@@ -14934,16 +16157,19 @@ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions,
14934
16157
  await cpuWindow(() => advanceFixedStep(page, bridge, 1e3, true));
14935
16158
  await waitFrames(page, 1);
14936
16159
  await samplePathPosition(bridge, pathEntity, pathPositions);
16160
+ await sampleSightLine(bridge, sightLine);
14937
16161
  } else if (ticks > 0 && fixedStep) {
14938
16162
  const sampleTicks = 10;
14939
16163
  for (let index = 0; index < ticks; index += sampleTicks) {
14940
16164
  const batch = Math.min(sampleTicks, ticks - index);
14941
16165
  await advanceFixedStep(page, bridge, batch);
14942
16166
  await samplePathPosition(bridge, pathEntity, pathPositions);
16167
+ await sampleSightLine(bridge, sightLine);
14943
16168
  }
14944
16169
  } else {
14945
16170
  await waitFrames(page, Math.max(frames, ticks, 1));
14946
16171
  await samplePathPosition(bridge, pathEntity, pathPositions);
16172
+ await sampleSightLine(bridge, sightLine);
14947
16173
  }
14948
16174
  const afterInput = bridge === void 0 || movementSampleRequest === void 0 ? void 0 : await bridge.sample(movementSampleRequest);
14949
16175
  let afterStep = afterInput;
@@ -15092,11 +16318,11 @@ async function executeAimAtStep(bridge, step, subject) {
15092
16318
  async function advanceFixedStep(page, bridge, ticks, render = false) {
15093
16319
  if (!Number.isInteger(ticks) || ticks <= 0)
15094
16320
  throw new Error("advance ticks must be a positive integer.");
15095
- for (let tick = 0; tick < ticks; tick += 1) {
16321
+ for (let tick = 0; tick < ticks; ) {
15096
16322
  for (let attempt = 0; ; attempt += 1) {
15097
16323
  try {
15098
- if (render) await bridge.advance(1, { render: true });
15099
- else await bridge.advance(1);
16324
+ const advanced = render ? await bridge.advance(1, { render: true }) : await bridge.advance(1);
16325
+ tick += typeof advanced === "number" && advanced > 1 ? advanced : 1;
15100
16326
  break;
15101
16327
  } catch (error) {
15102
16328
  if (!(error instanceof Error) || !error.message.includes(STOPPED_LOOP_ERROR) || attempt >= MAX_FIXED_STEP_STARTUP_RETRIES)
@@ -15104,7 +16330,7 @@ async function advanceFixedStep(page, bridge, ticks, render = false) {
15104
16330
  await waitFrames(page, 1);
15105
16331
  }
15106
16332
  }
15107
- if (render && tick + 1 < ticks) await waitFrames(page, 1);
16333
+ if (render && tick < ticks) await waitFrames(page, 1);
15108
16334
  }
15109
16335
  }
15110
16336
  function playtestStepDrivesMovement(step, hasHeldInput) {
@@ -15174,6 +16400,23 @@ async function setPointerButtons(page, inputState, buttons) {
15174
16400
  }
15175
16401
  inputState.pointerButtons = buttons;
15176
16402
  }
16403
+ async function sampleFootSlip(page, bridge, ticks, label, entity, feet) {
16404
+ const samples = [];
16405
+ for (let tick = 0; tick < ticks; tick += 1) {
16406
+ await advanceFixedStep(page, bridge, 1);
16407
+ const snapshot = await bridge.sample({ entities: [entity], include: ["entities"], sceneNodes: feet.map((name) => ({ limit: 1, name })) });
16408
+ samples.push({
16409
+ body: entityPosition(snapshot, entity) ?? null,
16410
+ feet: feet.map((_name, index) => snapshot.sceneNodes?.[index]?.nodes[0]?.position ?? null)
16411
+ });
16412
+ }
16413
+ return { entity, feet, label, samples };
16414
+ }
16415
+ async function sampleSightLine(bridge, sightLine) {
16416
+ if (bridge === void 0 || sightLine === void 0) return;
16417
+ const snapshot = await bridge.sample({ sightLine: { entity: sightLine.entity } });
16418
+ if (snapshot.sightLine !== void 0) sightLine.samples.push(snapshot.sightLine);
16419
+ }
15177
16420
  async function samplePathPosition(bridge, entity, positions2) {
15178
16421
  if (bridge === void 0 || entity === void 0) return;
15179
16422
  const snapshot = await bridge.sample({ entities: [entity] });
@@ -15185,18 +16428,49 @@ async function sampleAfterTransition(page, bridge, request) {
15185
16428
  await waitFrames(page, 1);
15186
16429
  return bridge.sample(request);
15187
16430
  }
15188
- async function waitFrames(page, frames) {
16431
+ async function waitFrames(page, frames, timeoutMs) {
15189
16432
  if (frames <= 0) return;
15190
- await page.evaluate((count) => new Promise((resolveFrame) => {
15191
- const schedule = globalThis.requestAnimationFrame;
15192
- let remaining = count;
15193
- const next = () => {
15194
- remaining -= 1;
15195
- if (remaining <= 0) resolveFrame();
15196
- else schedule(next);
15197
- };
15198
- schedule(next);
15199
- }), frames);
16433
+ let budgetMs;
16434
+ if (timeoutMs === void 0) {
16435
+ budgetMs = advanceTimeoutMs(frames);
16436
+ } else if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
16437
+ throw new PlaytestBridgeError(playtestDiagnostic(
16438
+ "TN_PLAYTEST_OPERATION_TIMEOUT",
16439
+ `waitFrames requested ${frames} frame(s) but the supplied remaining budget of ${String(timeoutMs)}ms is not a positive, finite value.`,
16440
+ "Check that the page is producing requestAnimationFrame callbacks; the wait cannot complete while rendering is stalled."
16441
+ ));
16442
+ } else {
16443
+ budgetMs = timeoutMs;
16444
+ }
16445
+ let timeout;
16446
+ try {
16447
+ await Promise.race([
16448
+ page.evaluate((count) => new Promise((resolveFrame) => {
16449
+ const schedule = globalThis.requestAnimationFrame;
16450
+ let remaining = count;
16451
+ const next = () => {
16452
+ remaining -= 1;
16453
+ if (remaining <= 0) resolveFrame();
16454
+ else schedule(next);
16455
+ };
16456
+ schedule(next);
16457
+ }), frames),
16458
+ new Promise((_resolve, reject) => {
16459
+ timeout = setTimeout(() => reject(new PlaytestBridgeError(playtestDiagnostic(
16460
+ "TN_PLAYTEST_OPERATION_TIMEOUT",
16461
+ `waitFrames requested ${frames} frame(s) exceeded ${budgetMs}ms.`,
16462
+ "Check that the page is producing requestAnimationFrame callbacks; the wait cannot complete while rendering is stalled."
16463
+ ))), budgetMs);
16464
+ })
16465
+ ]);
16466
+ } finally {
16467
+ if (timeout !== void 0) clearTimeout(timeout);
16468
+ }
16469
+ }
16470
+ var WARMUP_FIRST_FRAME_BUDGET_MS = 15e3;
16471
+ var WARMUP_FRAME_BUDGET_MS = 2e4;
16472
+ async function waitWarmupFrames(page, frames) {
16473
+ await waitFrames(page, frames, WARMUP_FIRST_FRAME_BUDGET_MS + frames * WARMUP_FRAME_BUDGET_MS);
15200
16474
  }
15201
16475
  function completionWindowLabel(scenario, target, live, raw = process.env.TN_PLAYTEST_COMPLETION_WINDOW_LABEL) {
15202
16476
  if (raw === void 0) return void 0;
@@ -15214,16 +16488,20 @@ async function measureCompletionWindow(label, mode, poll, release) {
15214
16488
  const fail2 = (reason) => {
15215
16489
  throw new Error(`TN_PLAYTEST_COMPLETION_WINDOW_FAILED: ${reason}`);
15216
16490
  };
15217
- const bounded = async (operation, timeoutMs = 5e3) => {
16491
+ const bounded = async (operation, timeoutMs2 = 5e3) => {
15218
16492
  let timer;
15219
16493
  try {
15220
16494
  return await Promise.race([operation(), new Promise((_resolve, reject) => {
15221
- timer = setTimeout(() => reject(new Error("TN_PLAYTEST_COMPLETION_WINDOW_FAILED: operation timeout")), timeoutMs);
16495
+ timer = setTimeout(() => reject(new Error("TN_PLAYTEST_COMPLETION_WINDOW_FAILED: operation timeout")), timeoutMs2);
15222
16496
  })]);
15223
16497
  } finally {
15224
16498
  clearTimeout(timer);
15225
16499
  }
15226
16500
  };
16501
+ const minimumFrames = Number(process.env.TN_PLAYTEST_COMPLETION_WINDOW_MIN_FRAMES ?? 101);
16502
+ const timeoutMs = Number(process.env.TN_PLAYTEST_COMPLETION_WINDOW_TIMEOUT_MS ?? 1e4);
16503
+ if (!Number.isSafeInteger(minimumFrames) || minimumFrames < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1)
16504
+ fail2("invalid completion frame count or timeout");
15227
16505
  const samples = [];
15228
16506
  let previous;
15229
16507
  let failure;
@@ -15239,7 +16517,7 @@ async function measureCompletionWindow(label, mode, poll, release) {
15239
16517
  const negotiated = await bounded(() => mode("wall-clock"));
15240
16518
  if (negotiated?.mode !== "wall-clock" || !Number.isSafeInteger(negotiated.tick) || !Number.isSafeInteger(negotiated.epoch) || negotiated.epoch < 0) fail2("clock negotiation unavailable");
15241
16519
  epoch = negotiated.epoch;
15242
- const deadline = Date.now() + 1e4;
16520
+ const deadline = Date.now() + timeoutMs;
15243
16521
  measurement: while (Date.now() <= deadline) {
15244
16522
  const value = await bounded(poll, Math.max(1, deadline - Date.now()));
15245
16523
  if (!value || value.clock?.mode !== "wall-clock" || value.valid !== true || !Number.isSafeInteger(value.dropped) || value.dropped < 0 || !Number.isSafeInteger(value.epoch) || value.epoch < 0 || !Array.isArray(value.samples) || !["present-return", "render-callback-return"].includes(value.source ?? "") || value.timebase !== (value.source === "present-return" ? "steady-clock-ms" : "performance-now-ms"))
@@ -15268,6 +16546,7 @@ async function measureCompletionWindow(label, mode, poll, release) {
15268
16546
  samples.push({ sequence: sample.sequence, completedAtMs: sample.completedAtMs });
15269
16547
  if (sample.completedAtMs - samples[0].completedAtMs >= 5e3) {
15270
16548
  if (samples.length < 101) fail2("fewer than 100 complete intervals");
16549
+ if (samples.length < minimumFrames) continue;
15271
16550
  const intervals = samples.slice(1).map((entry, index) => entry.completedAtMs - samples[index].completedAtMs).sort((a, b) => a - b);
15272
16551
  result = {
15273
16552
  label,
@@ -15322,6 +16601,7 @@ init_shared();
15322
16601
  init_index();
15323
16602
  init_bridgeClient();
15324
16603
  init_browser();
16604
+ init_captureEnvironment();
15325
16605
 
15326
16606
  // src/runner/observationSampling.ts
15327
16607
  init_index();
@@ -15631,11 +16911,11 @@ function isJudgeMarkerRequestFailure(method, url, judgeMarkerUrl) {
15631
16911
  function addPreflightDiagnostic(report, diagnostic2) {
15632
16912
  return diagnostic2 === void 0 ? report : { ...report, diagnostics: [diagnostic2, ...report.diagnostics] };
15633
16913
  }
15634
- var SOFTWARE_DEVICE_LOSS = /TN_DEVICE_LOST|WebGPU Device Lost|A valid external Instance reference no longer exists|Instance dropped (?:in popErrorScope|error in getCompilationInfo)/iu;
16914
+ var SOFTWARE_DEVICE_LOSS = /TN_DEVICE_LOST|TN_WASM_DEVICE_LOST|WebGPU Device Lost|A valid external Instance reference no longer exists|Instance dropped (?:in popErrorScope|error in getCompilationInfo)/iu;
15635
16915
  function isSoftwareDeviceLossEntry(entry) {
15636
16916
  return (entry.type === "error" || entry.type === "assert" || entry.type === "pageerror") && SOFTWARE_DEVICE_LOSS.test(entry.text);
15637
16917
  }
15638
- function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEntries, networkEntries, pathLength = void 0, hud = {}, runtimeReady = true, visual = void 0, labeledSamples = [], framebufferCoverage = void 0, capture = void 0, captureFailure = void 0, movementSamples = [], setup = void 0, deviceMetrics = void 0, movementBaselineSnapshot = void 0, startup = void 0, deviceLifecycle = void 0, tone = void 0) {
16918
+ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEntries, networkEntries, pathLength = void 0, hud = {}, runtimeReady = true, visual = void 0, labeledSamples = [], framebufferCoverage = void 0, capture = void 0, captureFailure = void 0, movementSamples = [], setup = void 0, deviceMetrics = void 0, movementBaselineSnapshot = void 0, startup = void 0, deviceLifecycle = void 0, tone = void 0, footSlip = void 0, sightLine = void 0, hudAudit = void 0) {
15639
16919
  const movementSample = isAnonymousMovementScenario(scenario) ? observedMovementSample(movementSamples) : void 0;
15640
16920
  const entity = scenario.assert?.movement?.entity ?? scenario.subject ?? movementSample?.entity ?? "";
15641
16921
  const wholeRunObserved = isAnonymousMovementScenario(scenario) ? false : entityPosition(beforeSnapshot, entity) !== void 0 && entityPosition(afterSnapshot, entity) !== void 0;
@@ -15725,6 +17005,9 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
15725
17005
  // room does. Never merged with the first: a node that has since been removed is gone, and
15726
17006
  // reporting it from the earlier sample would assert against a scene that no longer exists.
15727
17007
  ...afterSnapshot?.sceneNodes === void 0 && beforeSnapshot?.sceneNodes === void 0 ? {} : { sceneNodes: afterSnapshot?.sceneNodes ?? beforeSnapshot?.sceneNodes },
17008
+ ...footSlip === void 0 ? {} : { footSlip },
17009
+ ...sightLine === void 0 ? {} : { sightLine },
17010
+ ...hudAudit === void 0 ? {} : { hudAudit },
15728
17011
  ...startup === void 0 ? {} : { startup },
15729
17012
  ...beforeSnapshot?.gameplay === void 0 && afterSnapshot?.gameplay === void 0 && labeledSamples.every(({ snapshot }) => snapshot.gameplay === void 0) ? {} : {
15730
17013
  runtimeObservations: {
@@ -15817,43 +17100,74 @@ init_index();
15817
17100
  init_bridgeClient();
15818
17101
  async function waitForStartupReady(options) {
15819
17102
  const { bridge, pump } = options;
15820
- if (!bridge.description.capabilities.includes("runtime.startup")) return void 0;
17103
+ if (!bridge.description.capabilities.includes("runtime.startup")) {
17104
+ await options.warmup?.();
17105
+ return void 0;
17106
+ }
15821
17107
  const now = options.now ?? (() => Date.now());
15822
17108
  const timeoutMs = options.timeoutMs ?? PLAYTEST_STARTUP_READY_TIMEOUT_MS;
15823
17109
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
15824
17110
  throw new Error(`TN_PLAYTEST_STARTUP_TIMEOUT_INVALID: ${String(options.timeoutMs)}`);
17111
+ await options.warmup?.();
15825
17112
  const deadline = now() + timeoutMs;
15826
17113
  const aborted = options.aborted ?? (() => false);
15827
17114
  if (aborted()) throw abortedDuringStartup();
15828
17115
  const hostAlive = options.hostAlive ?? (async () => void 0);
15829
- let observed = await pollStartup(bridge);
15830
- while (observed === BUSY || observed.phase !== "ready") {
15831
- if (aborted()) throw abortedDuringStartup();
15832
- if (observed === BUSY && await hostAlive() === false) throw hostExitedDuringStartup();
15833
- if (now() >= deadline) {
15834
- throw new PlaytestBridgeError(playtestDiagnostic(
15835
- "TN_PLAYTEST_STARTUP_NOT_READY",
15836
- `Application startup stayed '${observed === BUSY ? "unreadable, the bridge kept timing out" : observed.phase}' for ${timeoutMs}ms; the run would have observed a game that has not finished loading.`,
15837
- "Let the application reach startup readiness \u2014 check that its loading gate can complete headlessly \u2014 or remove the runtime.startup capability if it has no startup phase."
15838
- ));
15839
- }
15840
- try {
15841
- await pump();
15842
- } catch (error) {
15843
- if (error instanceof PlaytestBridgeError && error.diagnostic.code === "TN_PLAYTEST_OPERATION_TIMEOUT") {
15844
- observed = BUSY;
15845
- continue;
17116
+ let observed = BUSY;
17117
+ const timeoutError = () => new PlaytestBridgeError(playtestDiagnostic(
17118
+ "TN_PLAYTEST_STARTUP_NOT_READY",
17119
+ `Application startup stayed '${observed === BUSY ? "unreadable, the bridge kept timing out" : observed.phase}' for ${timeoutMs}ms; the run would have observed a game that has not finished loading.`,
17120
+ "Let the application reach startup readiness \u2014 check that its loading gate can complete headlessly \u2014 or remove the runtime.startup capability if it has no startup phase."
17121
+ ));
17122
+ let settled = false;
17123
+ let timeout;
17124
+ const expired = new Promise((_resolve, reject) => {
17125
+ timeout = setTimeout(() => {
17126
+ settled = true;
17127
+ reject(timeoutError());
17128
+ }, timeoutMs);
17129
+ });
17130
+ try {
17131
+ return await Promise.race([expired, (async () => {
17132
+ if (settled) throw timeoutError();
17133
+ if (aborted()) throw abortedDuringStartup();
17134
+ if (settled || now() >= deadline) throw timeoutError();
17135
+ observed = await pollStartup(bridge);
17136
+ while (observed === BUSY || observed.phase !== "ready" || observed.revealed === false) {
17137
+ if (settled) throw timeoutError();
17138
+ if (aborted()) throw abortedDuringStartup();
17139
+ if (observed === BUSY) {
17140
+ const alive = await hostAlive();
17141
+ if (settled) throw timeoutError();
17142
+ if (alive === false) throw hostExitedDuringStartup();
17143
+ }
17144
+ if (settled || now() >= deadline) {
17145
+ throw timeoutError();
17146
+ }
17147
+ try {
17148
+ await pump(deadline - now());
17149
+ } catch (error) {
17150
+ if (error instanceof PlaytestBridgeError && error.diagnostic.code === "TN_PLAYTEST_OPERATION_TIMEOUT") {
17151
+ observed = BUSY;
17152
+ continue;
17153
+ }
17154
+ throw error;
17155
+ }
17156
+ if (settled || now() >= deadline) throw timeoutError();
17157
+ observed = await pollStartup(bridge);
15846
17158
  }
15847
- throw error;
15848
- }
15849
- observed = await pollStartup(bridge);
17159
+ if (settled || now() >= deadline) throw timeoutError();
17160
+ return {
17161
+ // A declared software lane reaches `ready` on the bounded window rather than on sustained
17162
+ // in-budget frames, so it is labelled for what it is: not a smoothness measurement.
17163
+ rule: options.declaredSoftware === true ? "compile-settled" : "sustained-frames",
17164
+ startup: observed
17165
+ };
17166
+ })()]);
17167
+ } finally {
17168
+ settled = true;
17169
+ if (timeout !== void 0) clearTimeout(timeout);
15850
17170
  }
15851
- return {
15852
- // A declared software lane reaches `ready` on the bounded window rather than on sustained
15853
- // in-budget frames, so it is labelled for what it is: not a smoothness measurement.
15854
- rule: options.declaredSoftware === true ? "compile-settled" : "sustained-frames",
15855
- startup: observed
15856
- };
15857
17171
  }
15858
17172
  function abortedDuringStartup() {
15859
17173
  return new PlaytestBridgeError(playtestDiagnostic(
@@ -16253,6 +17567,23 @@ function createOwnedRunResourceRelease(display, lease) {
16253
17567
  // src/runner/server.ts
16254
17568
  init_index();
16255
17569
  init_bridgeClient();
17570
+
17571
+ // src/runner/network.ts
17572
+ function networkBytesPerSecond(downloadKbps) {
17573
+ return downloadKbps * 1e3 / 8;
17574
+ }
17575
+ function networkEmulation(profile) {
17576
+ const bytesPerSecond = networkBytesPerSecond(profile.downloadKbps);
17577
+ return {
17578
+ connectionType: "cellular3g",
17579
+ downloadThroughput: bytesPerSecond,
17580
+ latency: profile.latencyMs,
17581
+ offline: false,
17582
+ uploadThroughput: bytesPerSecond
17583
+ };
17584
+ }
17585
+
17586
+ // src/runner/server.ts
16256
17587
  init_shared();
16257
17588
  function startManagedServer(config, dynamicPort) {
16258
17589
  const port = dynamicPort ?? managedPort(config);
@@ -16376,7 +17707,17 @@ function pageLifecycleDiagnostic(error, lifecycle, url) {
16376
17707
  "Something moved the document after the run started, so the observations after that point are from a different page. Remove the navigation from the game, or point --url at a server that does not reload itself mid-run."
16377
17708
  );
16378
17709
  }
17710
+ var throttledPages = /* @__PURE__ */ new WeakMap();
17711
+ async function applyNetworkProfile(page, scenario) {
17712
+ const profile = scenario.network;
17713
+ if (profile === void 0) return;
17714
+ const session = await page.context().newCDPSession(page);
17715
+ await session.send("Network.enable");
17716
+ await session.send("Network.emulateNetworkConditions", networkEmulation(profile));
17717
+ throttledPages.set(page, session);
17718
+ }
16379
17719
  async function openPageAndConnectBridge(page, config, scenario) {
17720
+ await applyNetworkProfile(page, scenario);
16380
17721
  const attempts = 3;
16381
17722
  let lastError;
16382
17723
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
@@ -16486,7 +17827,103 @@ async function retakeWhileBlank(retake, grace, boundMs, now = Date.now) {
16486
17827
 
16487
17828
  // src/runner/runner.ts
16488
17829
  init_bridgeClient();
17830
+ var CHANNEL_TOLERANCE = 48;
17831
+ var DIFFERING_SHARE = 0.25;
17832
+ var UI_OVER_COVER_SHARE = 5e-3;
17833
+ var FIRST_PAINT_SLACK_MS = 8;
17834
+ var HANDOFF_FRAMES = 30;
17835
+ function meanColour(frame) {
17836
+ const sum = [0, 0, 0];
17837
+ const pixels = frame.width * frame.height;
17838
+ for (let i = 0; i < pixels; i += 1) {
17839
+ sum[0] += frame.data[i * 4] ?? 0;
17840
+ sum[1] += frame.data[i * 4 + 1] ?? 0;
17841
+ sum[2] += frame.data[i * 4 + 2] ?? 0;
17842
+ }
17843
+ return sum.map((value) => Math.round(value / Math.max(1, pixels)));
17844
+ }
17845
+ function differingShare(frame, reference) {
17846
+ if (frame.width !== reference.width || frame.height !== reference.height) return 1;
17847
+ const pixels = frame.width * frame.height;
17848
+ let moved = 0;
17849
+ for (let i = 0; i < pixels; i += 1) {
17850
+ for (let channel = 0; channel < 3; channel += 1) {
17851
+ if (Math.abs((frame.data[i * 4 + channel] ?? 0) - (reference.data[i * 4 + channel] ?? 0)) > CHANNEL_TOLERANCE) {
17852
+ moved += 1;
17853
+ break;
17854
+ }
17855
+ }
17856
+ }
17857
+ return moved / Math.max(1, pixels);
17858
+ }
17859
+ function uiShare(frame, cover, world) {
17860
+ if (frame.width !== cover.width || frame.width !== world.width || frame.height !== cover.height || frame.height !== world.height) return 0;
17861
+ const pixels = frame.width * frame.height;
17862
+ let ui = 0;
17863
+ for (let i = 0; i < pixels; i += 1) {
17864
+ let offCover = false;
17865
+ let onWorld = true;
17866
+ for (let channel = 0; channel < 3; channel += 1) {
17867
+ const value = frame.data[i * 4 + channel] ?? 0;
17868
+ if (Math.abs(value - (cover.data[i * 4 + channel] ?? 0)) > CHANNEL_TOLERANCE) offCover = true;
17869
+ if (Math.abs(value - (world.data[i * 4 + channel] ?? 0)) > CHANNEL_TOLERANCE) onWorld = false;
17870
+ }
17871
+ if (offCover && onWorld) ui += 1;
17872
+ }
17873
+ return ui / Math.max(1, pixels);
17874
+ }
17875
+ function compareStartupFrames(frames, readyMs = Number.POSITIVE_INFINITY, firstPaintMs = 0) {
17876
+ const startup = frames.filter((frame) => frame.ms >= firstPaintMs - FIRST_PAINT_SLACK_MS && frame.ms < readyMs);
17877
+ const handOff = frames.filter((frame) => frame.ms >= readyMs);
17878
+ const reference = startup.at(-1);
17879
+ if (reference === void 0) return { differing: [], frames: 0, reference: [0, 0, 0], uiOverCover: [] };
17880
+ const differing = [];
17881
+ for (const frame of startup) {
17882
+ const share = differingShare(frame, reference);
17883
+ if (share > DIFFERING_SHARE) differing.push({ mean: meanColour(frame), ms: Math.round(frame.ms), share: Number(share.toFixed(3)) });
17884
+ }
17885
+ const observation = { differing, frames: startup.length, reference: meanColour(reference), uiOverCover: [] };
17886
+ if (!Number.isFinite(readyMs)) return observation;
17887
+ const worldIndex = handOff.findIndex((frame) => differingShare(frame, reference) > DIFFERING_SHARE);
17888
+ const world = handOff[worldIndex];
17889
+ if (world === void 0) return observation;
17890
+ observation.worldMs = Math.round(world.ms);
17891
+ for (const frame of handOff.slice(0, worldIndex)) {
17892
+ const share = uiShare(frame, reference, world);
17893
+ if (share > UI_OVER_COVER_SHARE) observation.uiOverCover.push({ ms: Math.round(frame.ms), share: Number(share.toFixed(4)) });
17894
+ }
17895
+ return observation;
17896
+ }
17897
+ async function recordStartupCover(page) {
17898
+ const cdp = await page.context().newCDPSession(page);
17899
+ const frames = [];
17900
+ cdp.on("Page.screencastFrame", ({ data, metadata, sessionId }) => {
17901
+ frames.push({ epochMs: (metadata.timestamp ?? Date.now() / 1e3) * 1e3, png: Buffer.from(data, "base64") });
17902
+ void cdp.send("Page.screencastFrameAck", { sessionId }).catch(() => void 0);
17903
+ });
17904
+ await cdp.send("Page.startScreencast", { everyNthFrame: 1, format: "png", maxHeight: 72, maxWidth: 128 });
17905
+ return {
17906
+ async finish(readyMs) {
17907
+ await waitFrames(page, HANDOFF_FRAMES).catch(() => void 0);
17908
+ await cdp.send("Page.stopScreencast").catch(() => void 0);
17909
+ await cdp.detach().catch(() => void 0);
17910
+ const [origin, firstPaint] = await page.evaluate(() => [
17911
+ performance.timeOrigin,
17912
+ performance.getEntriesByName("first-paint")[0]?.startTime ?? 0
17913
+ ]);
17914
+ const startup = frames.filter(({ epochMs }) => epochMs >= origin).map(({ epochMs, png }) => {
17915
+ const image = PNG.sync.read(png);
17916
+ return { data: image.data, height: image.height, ms: epochMs - origin, width: image.width };
17917
+ });
17918
+ return compareStartupFrames(startup, readyMs, firstPaint);
17919
+ }
17920
+ };
17921
+ }
17922
+
17923
+ // src/runner/runner.ts
16489
17924
  init_browser();
17925
+ init_frame_cost();
17926
+ init_captureEnvironment();
16490
17927
  var REMOTE_BROWSER_SESSIONS = /* @__PURE__ */ new WeakMap();
16491
17928
  function remoteBrowserFor(config) {
16492
17929
  return REMOTE_BROWSER_SESSIONS.get(config);
@@ -16662,6 +18099,14 @@ async function writeObservationArtifacts(artifactDirectory, requested, observati
16662
18099
  }
16663
18100
  return written;
16664
18101
  }
18102
+ var WorkerGameRelaunch = class extends Error {
18103
+ };
18104
+ async function runsGameInWorker(page) {
18105
+ for (const worker of page.workers()) {
18106
+ if (await worker.evaluate("typeof globalThis.__tnGamePlatform").catch(() => void 0) === "object") return true;
18107
+ }
18108
+ return false;
18109
+ }
16665
18110
  async function runStandalonePlaytest(config, options = {}) {
16666
18111
  return runStandalonePlaytestInternal(config, {
16667
18112
  ...options,
@@ -16669,12 +18114,25 @@ async function runStandalonePlaytest(config, options = {}) {
16669
18114
  });
16670
18115
  }
16671
18116
  async function runStandalonePlaytestInternal(config, options = {}) {
18117
+ try {
18118
+ return await runStandalonePlaytestOnce(config, options);
18119
+ } catch (error) {
18120
+ if (!(error instanceof WorkerGameRelaunch)) throw error;
18121
+ return runStandalonePlaytestOnce(config, { ...options, gameThread: "worker" });
18122
+ }
18123
+ }
18124
+ async function runStandalonePlaytestOnce(config, options) {
16672
18125
  const usesFreePort = config.server !== void 0 && config.port === 0;
16673
- const activeConfig = usesFreePort ? await resolveManagedServerConfig(config) : config;
18126
+ const resolvedConfig = usesFreePort ? await resolveManagedServerConfig(config) : config;
16674
18127
  const scenario = withPerformanceBudget(
16675
- await loadPlaytestScenario(activeConfig.projectPath, activeConfig.scenarioPath),
16676
- activeConfig.performanceBudget
18128
+ await loadPlaytestScenario(resolvedConfig.projectPath, resolvedConfig.scenarioPath),
18129
+ resolvedConfig.performanceBudget
16677
18130
  );
18131
+ let activeConfig = withScenarioClock(resolvedConfig, scenario);
18132
+ const performance2 = scenario.assert?.performance;
18133
+ if ((activeConfig.target ?? "browser") === "browser" && activeConfig.liveClock === void 0 && (performance2?.maxFrameMsP95 !== void 0 || performance2?.minFps !== void 0)) {
18134
+ activeConfig = { ...activeConfig, liveClock: true };
18135
+ }
16678
18136
  const cpuLabels = cpuWindowLabels(scenario, "browser", activeConfig.liveClock === true);
16679
18137
  if (cpuLabels.length > 0 && options.remoteBrowser !== void 0) {
16680
18138
  throw new Error("TN_PLAYTEST_CPU_WINDOW_FAILED: remote browser has no local owned process tree");
@@ -16684,11 +18142,12 @@ async function runStandalonePlaytestInternal(config, options = {}) {
16684
18142
  let completionWindow;
16685
18143
  const completionDisplay = completionLabel === void 0 ? void 0 : completionWindowEnvironment("browser", activeConfig.headless);
16686
18144
  if (completionLabel !== void 0 && options.remoteBrowser !== void 0) throw new Error("TN_PLAYTEST_COMPLETION_WINDOW_FAILED: requires a fresh local browser process");
16687
- const browserConfig = scenario.assert?.performance === void 0 && completionLabel === void 0 ? activeConfig : {
18145
+ const measurementArgs = measurementBrowserArgs(scenario.assert?.performance !== void 0, completionLabel !== void 0, frameDisplay(), options.gameThread);
18146
+ const browserConfig = measurementArgs.length === 0 ? activeConfig : {
16688
18147
  ...activeConfig,
16689
18148
  browserArgs: [
16690
18149
  ...activeConfig.browserArgs ?? [],
16691
- ...PERFORMANCE_BROWSER_ARGS.filter((argument) => !activeConfig.browserArgs?.includes(argument))
18150
+ ...measurementArgs.filter((argument) => !activeConfig.browserArgs?.includes(argument))
16692
18151
  ]
16693
18152
  };
16694
18153
  await mkdir(activeConfig.artifactDirectory, { recursive: true });
@@ -16838,6 +18297,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
16838
18297
  await page.addInitScript((liveClock) => {
16839
18298
  globalThis.__THREENATIVE_PLAYTEST_RUNNER_EXPECTED__ = true;
16840
18299
  if (liveClock) globalThis.__THREENATIVE_PLAYTEST_CLOCK__ = "wall-clock";
18300
+ globalThis.__THREENATIVE_ENGINE_COST__ = true;
16841
18301
  window.addEventListener("unhandledrejection", (event) => {
16842
18302
  const reason = event.reason instanceof Error ? event.reason.stack || event.reason.message : String(event.reason);
16843
18303
  console.error(`__THREENATIVE_PLAYTEST_UNHANDLED_REJECTION__:${reason}`);
@@ -16874,7 +18334,9 @@ async function runStandalonePlaytestInternal(config, options = {}) {
16874
18334
  pageLifecycle.closed = true;
16875
18335
  });
16876
18336
  const activePage = page;
18337
+ const coverRecorder = scenario.assert?.startup?.steadyCover === true ? await recordStartupCover(page) : void 0;
16877
18338
  const bridge = await openRunnerPage(page, browserConfig, scenario, options.remoteBrowser);
18339
+ if (options.gameThread === void 0 && measurementArgs.includes("--disable-frame-rate-limit") && await runsGameInWorker(page)) throw new WorkerGameRelaunch();
16878
18340
  pageLifecycle.settled = true;
16879
18341
  const setupApplication2 = bridge?.setupApplication;
16880
18342
  if (scenario.setup !== void 0) {
@@ -16886,13 +18348,16 @@ async function runStandalonePlaytestInternal(config, options = {}) {
16886
18348
  ));
16887
18349
  }
16888
18350
  }
16889
- await waitFrames(page, scenario.warmupFrames);
18351
+ if (bridge === void 0 || scenario.awaitStartup === false) await waitFrames(page, scenario.warmupFrames);
16890
18352
  const startupOutcome = bridge === void 0 || scenario.awaitStartup === false ? void 0 : await waitForStartupReady({
16891
18353
  aborted: () => tearingDown,
16892
18354
  bridge,
16893
18355
  declaredSoftware: activeConfig.allowSoftwareAdapter === true,
16894
- pump: () => waitFrames(activePage, 1)
18356
+ warmup: () => waitWarmupFrames(activePage, scenario.warmupFrames),
18357
+ pump: (remainingMs) => waitFrames(activePage, 1, remainingMs)
16895
18358
  });
18359
+ const readyMs = startupOutcome?.startup.timeline?.readyMs;
18360
+ const startupCover = coverRecorder === void 0 || readyMs === void 0 ? void 0 : await coverRecorder.finish(readyMs);
16896
18361
  await alignScenarioStartTick(bridge, scenario.startTick, activeConfig.liveClock === true);
16897
18362
  const runtimeReady = await page.evaluate(
16898
18363
  () => document.readyState !== "loading" && document.querySelector("canvas") !== null
@@ -17081,6 +18546,16 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17081
18546
  if (activeConfig.cpuProfilePath !== void 0) {
17082
18547
  cpuProfile = await startBrowserCpuProfile(activePage, activeConfig.cpuProfilePath);
17083
18548
  }
18549
+ const footSlip = [];
18550
+ const footSlipAt = (label) => label === void 0 ? void 0 : scenario.assert?.footSlip?.find(({ atStep }) => atStep === label);
18551
+ const sightLineAssertion = scenario.assert?.sightLine;
18552
+ const sightLineEntity = sightLineAssertion?.entity ?? scenario.subject;
18553
+ const sightLine = sightLineAssertion === void 0 || sightLineEntity === void 0 ? void 0 : { entity: sightLineEntity, samples: [] };
18554
+ const drawnTicks = scenario.assert?.engineCost === void 0 || bridge === void 0 || activeConfig.liveClock === true || !bridge.description.capabilities.includes("runtime.fixedStep") ? void 0 : async (ticks) => {
18555
+ await advanceFixedStep(activePage, bridge, ticks, true);
18556
+ await samplePathPosition(bridge, pathEntity, pathPositions);
18557
+ await sampleSightLine(bridge, sightLine);
18558
+ };
17084
18559
  for (const [index, step] of scenario.steps.entries()) {
17085
18560
  const framebufferAssertion = scenario.assert?.framebufferCoverage;
17086
18561
  if (framebufferAssertion !== void 0 && step.label === framebufferAssertion.window.startStep) {
@@ -17133,7 +18608,17 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17133
18608
  }
17134
18609
  );
17135
18610
  completionWindow.setupSnapshot = setupSnapshot;
17136
- } : void 0
18611
+ } : footSlipAt(step.label) === void 0 ? drawnTicks : async (ticks) => {
18612
+ const assertion = footSlipAt(step.label);
18613
+ const entity = assertion.entity ?? scenario.subject;
18614
+ if (bridge === void 0 || entity === void 0 || activeConfig.liveClock === true || !bridge.description.capabilities.includes("runtime.fixedStep")) {
18615
+ throw new Error("TN_PLAYTEST_FOOT_SLIP_UNOBSERVED: footSlip needs a fixed-step bridge and a subject entity");
18616
+ }
18617
+ footSlip.push(await sampleFootSlip(activePage, bridge, ticks, step.label, entity, assertion.feet));
18618
+ await samplePathPosition(bridge, pathEntity, pathPositions);
18619
+ await sampleSightLine(bridge, sightLine);
18620
+ },
18621
+ sightLine
17137
18622
  );
17138
18623
  if (movementBaselineSnapshot === void 0 && movementNeedsBaseline && movementEntity !== void 0) {
17139
18624
  const candidate = stepSamples.afterStep ?? stepSamples.afterInput;
@@ -17177,6 +18662,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17177
18662
  if (position !== void 0) pathPositions.push(position);
17178
18663
  }
17179
18664
  const afterHud = await sampleHud(page, hudAssertions);
18665
+ const hudAudit = scenario.assert?.hudAudit === void 0 ? void 0 : await sampleHudAudit(page);
17180
18666
  const afterScreenshot = scenario.artifacts?.screenshots !== false && artifactFrames || wantsVisual || wantsFinalTone ? wantsVisual || wantsFinalTone ? await captureVisualPage(
17181
18667
  "after.png",
17182
18668
  scenario.artifacts?.screenshots === false ? void 0 : join(activeConfig.artifactDirectory, "after.png")
@@ -17211,9 +18697,16 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17211
18697
  setupApplication2,
17212
18698
  deviceMetrics,
17213
18699
  movementBaselineSnapshot,
17214
- startupOutcome === void 0 ? void 0 : { ...startupOutcome.startup, rule: startupOutcome.rule },
18700
+ startupOutcome === void 0 ? void 0 : {
18701
+ ...startupOutcome.startup,
18702
+ rule: startupOutcome.rule,
18703
+ ...startupCover === void 0 ? {} : { cover: startupCover }
18704
+ },
17215
18705
  void 0,
17216
- tone
18706
+ tone,
18707
+ footSlip.length === 0 ? void 0 : footSlip,
18708
+ sightLine === void 0 || sightLine.samples.length === 0 ? void 0 : sightLine,
18709
+ hudAudit
17217
18710
  );
17218
18711
  if (cpuWindows.length !== cpuLabels.length) throw new Error("TN_PLAYTEST_CPU_WINDOW_FAILED: missing requested CPU window");
17219
18712
  if (completionWindow !== void 0) {
@@ -17224,6 +18717,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17224
18717
  browserArgs: resolveBrowserArguments(browserConfig.browserArgs)
17225
18718
  };
17226
18719
  }
18720
+ if (options.gameThread !== void 0) report.gameThread = options.gameThread;
17227
18721
  report.acquisition = { requestUrls: [...requestUrls], ...cpuLabels.length === 0 ? {} : { cpuWindows }, ...completionWindow === void 0 ? {} : { completionWindow } };
17228
18722
  await writeObservationArtifacts(activeConfig.artifactDirectory, scenario.artifacts, {
17229
18723
  console: consoleEntries,
@@ -17236,6 +18730,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17236
18730
  else await page.close();
17237
18731
  return addPreflightDiagnostic(report, preflight);
17238
18732
  } catch (error) {
18733
+ if (error instanceof WorkerGameRelaunch) throw error;
17239
18734
  try {
17240
18735
  if (!observationArtifactsWritten) await writeObservationArtifacts(activeConfig.artifactDirectory, scenario.artifacts, {
17241
18736
  console: consoleEntries,
@@ -17664,7 +19159,9 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
17664
19159
  // this the wait reads that as a slow loading gate and burns its whole deadline; with it
17665
19160
  // the report names the exit and carries the console tail that says why.
17666
19161
  hostAlive: () => target.driver.isAlive().catch(() => void 0),
17667
- pump: () => attached.advance(1)
19162
+ pump: async () => {
19163
+ await attached.advance(1);
19164
+ }
17668
19165
  });
17669
19166
  await throwIfAborted(target);
17670
19167
  for (let frame = 0; frame < scenario.warmupFrames; frame += 1) {
@@ -17700,7 +19197,7 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
17700
19197
  const before = await bridge.sample(sampleRequest);
17701
19198
  if (completionLabel !== void 0 && before.clock.mode !== "fixed-step") throw new Error("TN_PLAYTEST_COMPLETION_WINDOW_FAILED: prefix requires fixed-step clock");
17702
19199
  if (scenario.artifacts?.screenshots === "before-after" && config.captureArtifactScreenshots !== false) {
17703
- await captureDeviceScreenshot(target, join(config.artifactDirectory, "before.png"), tone, "before.png", void 0, renderOnly);
19200
+ await captureDeviceScreenshot(target, join(config.artifactDirectory, "before.png"), tone, "before.png", void 0, renderOnly, scenario.assert?.tone);
17704
19201
  }
17705
19202
  const pathEntity = scenario.assert?.movement?.pathLength === void 0 ? void 0 : scenario.assert.movement.entity ?? scenario.subject;
17706
19203
  const pathPositions = [];
@@ -17753,12 +19250,14 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
17753
19250
  throw new PlaytestBridgeError(playtestDiagnostic(
17754
19251
  "TN_PLAYTEST_OBSERVATION_UNAVAILABLE",
17755
19252
  `Resource wait for '${wait.id}.${wait.path}' has no timeout.`,
17756
- "Validate the scenario with timeoutMs as a positive integer no greater than 120000."
19253
+ "Validate the scenario with timeoutMs as a positive integer no greater than 300000."
17757
19254
  ));
17758
19255
  }
17759
19256
  const attachedBridge = bridge;
17760
19257
  afterInput = await waitForResource({
17761
- advance: () => attachedBridge.advance(1),
19258
+ advance: async () => {
19259
+ await attachedBridge.advance(1);
19260
+ },
17762
19261
  id: wait.id,
17763
19262
  path: wait.path,
17764
19263
  predicate: wait,
@@ -17859,7 +19358,9 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
17859
19358
  const pid = target.driver.processId;
17860
19359
  if (pid === void 0) throw new Error("TN_PLAYTEST_CPU_WINDOW_FAILED: native child PID unavailable");
17861
19360
  return { rootPid: pid, pid, tid: pid };
17862
- }, measuredBridge, () => measuredBridge.advance(1e3)));
19361
+ }, measuredBridge, async () => {
19362
+ await measuredBridge.advance(1e3);
19363
+ }));
17863
19364
  } finally {
17864
19365
  if (holdRender) await transport.call("_holdAutomaticRender", false);
17865
19366
  }
@@ -17886,7 +19387,7 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
17886
19387
  const wantsStepTone = step.label !== void 0 && scenario.assert?.tone?.some(({ atStep }) => atStep === step.label) === true;
17887
19388
  if (step.screenshot !== void 0 || wantsStepTone) {
17888
19389
  const label = step.screenshot === void 0 ? `tone-${index}.png` : `${safePart(step.screenshot)}.png`;
17889
- await captureDeviceScreenshot(target, join(config.artifactDirectory, label), tone, label, step.label, renderOnly);
19390
+ await captureDeviceScreenshot(target, join(config.artifactDirectory, label), tone, label, step.label, renderOnly, scenario.assert?.tone);
17890
19391
  }
17891
19392
  if (step.release && pressed !== void 0) {
17892
19393
  const released = typeof pressed === "string" ? [pressed] : [...pressed];
@@ -17935,7 +19436,7 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
17935
19436
  metrics?.stop();
17936
19437
  await metrics?.sampleNow("after").catch(() => void 0);
17937
19438
  if (scenario.artifacts?.screenshots !== false || scenario.assert?.tone?.some(({ atStep }) => atStep === void 0) === true) {
17938
- await captureDeviceScreenshot(target, join(config.artifactDirectory, "after.png"), tone, "after.png", void 0, renderOnly);
19439
+ await captureDeviceScreenshot(target, join(config.artifactDirectory, "after.png"), tone, "after.png", void 0, renderOnly, scenario.assert?.tone);
17939
19440
  }
17940
19441
  if (!await target.driver.isAlive()) {
17941
19442
  return failureReport(config, scenario, playtestDiagnostic(
@@ -18069,11 +19570,12 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
18069
19570
  if (cleanupErrors.length > 0) cleanupState.error = cleanupFailure(cleanupErrors);
18070
19571
  }
18071
19572
  }
18072
- async function captureDeviceScreenshot(target, path2, tone, label, atStep, renderOnly) {
19573
+ async function captureDeviceScreenshot(target, path2, tone, label, atStep, renderOnly, toneAssertions = []) {
18073
19574
  await target.driver.screenshot(path2, renderOnly);
18074
19575
  const png = await readFile(path2);
18075
19576
  const stats = target.name === "desktop" ? assertDesktopCaptureNotBlank(png, path2) : assertCaptureNotBlank(png, path2);
18076
19577
  if (stats.tone !== void 0) tone.push({ code: "TN_TONE", label, ...atStep === void 0 ? {} : { atStep }, ...stats.tone });
19578
+ tone.push(...collectRegionalTone(png, toneAssertions, label, atStep));
18077
19579
  }
18078
19580
  function deviceMetricsRecorder(target) {
18079
19581
  if (target.name !== "android") return void 0;
@@ -18659,6 +20161,7 @@ function deviceFailure(serial, error) {
18659
20161
  const detail = error instanceof Error ? error.message : String(error);
18660
20162
  return new Error(`TN_PLAYTEST_DEVICE_FAILED: Android Chrome device '${serial}' failed: ${detail}`);
18661
20163
  }
20164
+ init_captureEnvironment();
18662
20165
 
18663
20166
  // src/runner/desktop.ts
18664
20167
  init_capture();
@@ -18683,21 +20186,15 @@ var LocalDeviceMailbox = class {
18683
20186
  }
18684
20187
  }
18685
20188
  async remove(path2) {
18686
- for (let retry = 0; ; retry += 1) {
18687
- try {
18688
- await rm(path2, { force: true });
18689
- return;
18690
- } catch (error) {
18691
- if (retry >= 10 || !isTransientMailboxLock(error)) throw error;
18692
- await delay3(20);
18693
- }
18694
- }
20189
+ await retryMailboxLock(() => rm(path2, { force: true }));
18695
20190
  }
18696
20191
  async write(path2, contents) {
18697
20192
  await mkdir(dirname(path2), { recursive: true });
18698
20193
  const temporary = `${path2}.tmp`;
18699
- await writeFile(temporary, contents, "utf8");
18700
- await rename(temporary, path2);
20194
+ await retryMailboxLock(async () => {
20195
+ await writeFile(temporary, contents, "utf8");
20196
+ await rename(temporary, path2);
20197
+ });
18701
20198
  }
18702
20199
  };
18703
20200
  var DesktopPlaytestDriver = class {
@@ -18742,6 +20239,10 @@ var DesktopPlaytestDriver = class {
18742
20239
  ...process.env,
18743
20240
  ...process.platform === "linux" && process.env.SDL_VIDEODRIVER === void 0 ? { SDL_VIDEODRIVER: "x11" } : {},
18744
20241
  MYSTRAL_HEADLESS: "1",
20242
+ // A debug launch, because the run's own warning evaluator reads `TN_SCENE_WARNING` and the
20243
+ // engine prints it only where a developer asked for the dev surfaces. The shell's value must
20244
+ // not decide it: an inherited `DEV_MODE=0` would leave the check blind rather than red.
20245
+ DEV_MODE: "1",
18745
20246
  ...this.options.env,
18746
20247
  TN_PLAYTEST_MAILBOX_ROOT: this.mailboxRoot,
18747
20248
  // The host reads the request before it evaluates the game entry, the way the browser runner
@@ -18939,6 +20440,17 @@ function isProcessExited(child) {
18939
20440
  function delay3(milliseconds) {
18940
20441
  return new Promise((resolve13) => setTimeout(resolve13, milliseconds));
18941
20442
  }
20443
+ async function retryMailboxLock(operation) {
20444
+ for (let retry = 0; ; retry += 1) {
20445
+ try {
20446
+ await operation();
20447
+ return;
20448
+ } catch (error) {
20449
+ if (retry >= 100 || !isTransientMailboxLock(error)) throw error;
20450
+ await delay3(20);
20451
+ }
20452
+ }
20453
+ }
18942
20454
  function isTransientMailboxLock(error) {
18943
20455
  const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
18944
20456
  return code === "EPERM" || code === "EBUSY";
@@ -19311,7 +20823,9 @@ var XcrunIosDriver = class {
19311
20823
  async prepareSimulator(endpoint, mailboxRoot) {
19312
20824
  const device = this.device();
19313
20825
  await this.run(["simctl", "bootstatus", device, "-b"]);
20826
+ const previous = await this.registeredBundlePath(device);
19314
20827
  await this.run(["simctl", "install", device, this.options.appPath]);
20828
+ await this.awaitInstalledBundle(device, previous);
19315
20829
  const container = (await this.run([
19316
20830
  "simctl",
19317
20831
  "get_app_container",
@@ -19364,6 +20878,28 @@ var XcrunIosDriver = class {
19364
20878
  ]);
19365
20879
  this.pid = parseLaunchedPid(output);
19366
20880
  }
20881
+ // `simctl install` returns while the simulator still lists the replaced bundle, which it has
20882
+ // moved to `containermanagerd/Dead/`. A launch in that window starts the previous build: a CI
20883
+ // physics scenario ran the input smoke game from a Dead container and failed every assertion.
20884
+ // Every reinstall gets a new bundle container, so launch only once the listed path is new.
20885
+ async awaitInstalledBundle(device, previous) {
20886
+ const deadline = Date.now() + kIosInstallRegistrationMs;
20887
+ for (; ; ) {
20888
+ const listed = await this.run(["simctl", "listapps", device]);
20889
+ const path2 = parseListedBundlePath(listed, this.options.bundleId);
20890
+ if (path2 !== void 0 && path2 !== previous && !path2.includes("/Dead/")) return;
20891
+ if (Date.now() >= deadline) {
20892
+ const at = listed.indexOf(`"${this.options.bundleId}"`);
20893
+ throw new Error(
20894
+ `TN_PLAYTEST_IOS_INSTALL_UNREGISTERED: ${this.options.bundleId} still lists '${path2 ?? "no bundle"}' ${kIosInstallRegistrationMs} ms after simctl install. listapps: ` + listed.slice(Math.max(at, 0), Math.max(at, 0) + 800)
20895
+ );
20896
+ }
20897
+ await new Promise((resolve13) => setTimeout(resolve13, kIosInstallPollMs));
20898
+ }
20899
+ }
20900
+ async registeredBundlePath(device) {
20901
+ return parseListedBundlePath(await this.run(["simctl", "listapps", device]), this.options.bundleId);
20902
+ }
19367
20903
  device() {
19368
20904
  return this.options.device ?? "booted";
19369
20905
  }
@@ -19371,6 +20907,14 @@ var XcrunIosDriver = class {
19371
20907
  return this.mailboxRoot === void 0 ? path2 : join(this.mailboxRoot, basename(path2));
19372
20908
  }
19373
20909
  };
20910
+ var kIosInstallRegistrationMs = 6e4;
20911
+ var kIosInstallPollMs = 250;
20912
+ function parseListedBundlePath(output, bundleId) {
20913
+ const key = new RegExp(`"${bundleId.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}"\\s*=\\s*\\{`, "u").exec(output);
20914
+ if (key === null) return void 0;
20915
+ const path2 = /\n\s*Path = (?:"([^"]*)"|([^;\s]+));/u.exec(output.slice(key.index));
20916
+ return path2?.[1] ?? path2?.[2];
20917
+ }
19374
20918
  function parseLaunchedPid(output) {
19375
20919
  const pid = /(?:pid\s+|:\s*)(\d+)\b/iu.exec(output)?.[1];
19376
20920
  if (pid === void 0) throw new Error(`iOS launch did not report a process id: ${output.trim()}`);