@threenative/playtest 0.3.5 → 0.3.8

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(
@@ -2425,6 +2806,52 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2425
2806
  addPassBound("triangles", kind, ceiling);
2426
2807
  return { assertions: results, diagnostics };
2427
2808
  }
2809
+ function emitFrameBound(ceiling, intervalP95, observed, sampleCount, samplesPass, lane, results, diagnostics, path2, sourcePath) {
2810
+ const cpu = observed.flatMap(({ phases }) => phases === void 0 || typeof phases.update !== "number" || typeof phases.render !== "number" ? [] : [phases.update + phases.render]);
2811
+ const hitches = observed.filter(({ frameMs, phases }) => phases === void 0 && frameMs >= HITCH_MS).length;
2812
+ const cpuP95 = cpu.length > 0 && cpu.length + hitches === sampleCount ? nearestRank(cpu, 0.95) : void 0;
2813
+ const missing = [
2814
+ ...cpuP95 === void 0 ? ["the CPU frame split (phases.update and phases.render)"] : [],
2815
+ ...lane.gpuP95 === void 0 ? ["the GPU time (a TN_FRAME_BUDGET window with a gpu reading)"] : []
2816
+ ];
2817
+ const costP95 = cpuP95 === void 0 || lane.gpuP95 === void 0 ? void 0 : Math.max(cpuP95, lane.gpuP95);
2818
+ const virtual = lane.display === "virtual";
2819
+ const costPass = costP95 !== void 0 && costP95 <= ceiling;
2820
+ const intervalPass = virtual || intervalP95 !== void 0 && intervalP95 <= ceiling;
2821
+ const thinGpu = lane.gpuP95 !== void 0 && !(lane.gpuSamples !== void 0 && lane.gpuSamples >= MIN_GPU_SAMPLES);
2822
+ const pass = samplesPass && costPass && intervalPass && !thinGpu;
2823
+ const round4 = (value) => value === void 0 ? null : Math.round(value * 100) / 100;
2824
+ results.push({
2825
+ details: {
2826
+ actual: round4(virtual || !costPass ? costP95 : intervalP95),
2827
+ cost: { cpuP95: round4(cpuP95), gpuP95: round4(lane.gpuP95), gpuSamples: lane.gpuSamples ?? null, hitchFrames: hitches, p95: round4(costP95) },
2828
+ display: lane.display,
2829
+ expected: ceiling,
2830
+ interval: virtual ? { gated: false, p95: round4(intervalP95), reason: XVFB_CADENCE } : { gated: true, p95: round4(intervalP95) },
2831
+ sampleCount,
2832
+ unit: "ms"
2833
+ },
2834
+ id: "performance.maxFrameMsP95",
2835
+ pass
2836
+ });
2837
+ if (pass) return;
2838
+ const foreign = lane.foreignGpu ?? [];
2839
+ const contended = missing.length === 0 && !costPass && foreign.length > 0;
2840
+ 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`;
2841
+ const fewSamples = missing.length === 0 && costPass && thinGpu;
2842
+ diagnostics.push({
2843
+ code: fewSamples ? "TN_PLAYTEST_PERF_FEW_GPU_SAMPLES" : "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
2844
+ message: `performance.maxFrameMsP95 ${fewSamples ? fewGpuSamples(lane.gpuSamples) : detail}.`,
2845
+ observedRuntimePath: path2,
2846
+ severity: "error",
2847
+ sourcePath,
2848
+ 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."
2849
+ });
2850
+ }
2851
+ function fewGpuSamples(samples) {
2852
+ const held = samples === void 0 ? "reports no sample count" : `holds ${samples} GPU sample${samples === 1 ? "" : "s"}`;
2853
+ return `cannot be judged: the latest GPU window ${held}, under the minimum of ${MIN_GPU_SAMPLES}`;
2854
+ }
2428
2855
  function isRuntimeDiagnosticsSample(value) {
2429
2856
  if (!isRecord(value) || typeof value.frameMs !== "number" || !Number.isFinite(value.frameMs) || value.frameMs <= 0) {
2430
2857
  return false;
@@ -2617,11 +3044,15 @@ function minimumResolvedDistance(effectLog, effectLogSeries, entityId, target, b
2617
3044
  if (baseline !== void 0 && atStep === void 0) positions2.unshift(baseline);
2618
3045
  return positions2.length === 0 ? void 0 : Math.min(...positions2.map((position) => vectorDistance(position, target)));
2619
3046
  }
3047
+ var HITCH_MS, XVFB_CADENCE;
2620
3048
  var init_render_evidence = __esm({
2621
3049
  "src/evaluators/render-evidence.ts"() {
2622
3050
  init_protocol();
2623
3051
  init_measures();
3052
+ init_frame_cost();
2624
3053
  init_assertion_report();
3054
+ HITCH_MS = 2e3;
3055
+ XVFB_CADENCE = "display cadence, not gated: the runner's private Xvfb paces frames on its own timer, not the game's cost";
2625
3056
  }
2626
3057
  });
2627
3058
 
@@ -2759,6 +3190,17 @@ function emitEvidenceFamilies(ctx) {
2759
3190
  const pass = observed !== void 0 && observed.nonblankPixelRatio >= minimum;
2760
3191
  assertions.push({ id: `visual.${index}.region`, pass, details: { after: pass, expected: { equals: true }, minimum, observed: observed?.nonblankPixelRatio } });
2761
3192
  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." });
3193
+ if (staticRegion.minSharpness !== void 0) {
3194
+ const sharpness = observed?.sharpness;
3195
+ const sharpPass = sharpness !== void 0 && sharpness >= staticRegion.minSharpness;
3196
+ assertions.push({ id: `visual.${index}.region.sharpness`, pass: sharpPass, details: { minimum: staticRegion.minSharpness, observed: sharpness ?? null } });
3197
+ if (!sharpPass) diagnostics.push({
3198
+ code: "TN_PLAYTEST_REGION_BLURRED",
3199
+ 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).`,
3200
+ severity: "error",
3201
+ 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."
3202
+ });
3203
+ }
2762
3204
  if (staticRegion.minDarkPixelRatio !== void 0) {
2763
3205
  const darkPass = observed?.darkPixelRatio !== void 0 && observed.darkPixelRatio >= staticRegion.minDarkPixelRatio;
2764
3206
  assertions.push({
@@ -2827,12 +3269,14 @@ function emitMovementEvidence(ctx) {
2827
3269
  scenarioAssertions.diagnostics,
2828
3270
  input.report.target
2829
3271
  );
3272
+ const warningTexts = perfWarnings((input.report.observations?.console ?? []).map(({ text }) => text));
2830
3273
  const policyDiagnostics = evaluateDiagnosticsPolicy(input.report, diagnosticsPolicy);
2831
3274
  diagnostics.push(...policyDiagnostics);
2832
3275
  assertions.push({
2833
3276
  details: {
2834
3277
  consoleErrors: consoleErrors(input.report.observations?.console ?? []).length,
2835
3278
  networkErrors: input.report.observations?.network.length ?? 0,
3279
+ ...warningTexts.length === 0 ? {} : { perfWarnings: warningTexts },
2836
3280
  policy: diagnosticsPolicy,
2837
3281
  runtimeDiagnostics: runtimeDiagnostics(input.report.observations?.runtimeDiagnostics).length
2838
3282
  },
@@ -3243,7 +3687,8 @@ function emitMovementEvidence(ctx) {
3243
3687
  }
3244
3688
  for (const assertion of scenarioAssertions.animation ?? []) {
3245
3689
  const entity = assertion.entity ?? input.scenario.subject ?? input.report.entity;
3246
- const runtime = runtimeAnimationObservations(input.report.observations?.runtimeObservations);
3690
+ const stepAnimation = runtimeGameplayAtStep(input.report.observations?.runtimeObservations, assertion.atStep)?.animation;
3691
+ const runtime = assertion.atStep === void 0 ? runtimeAnimationObservations(input.report.observations?.runtimeObservations) : isRecord(stepAnimation) ? stepAnimation : void 0;
3247
3692
  if (runtime !== void 0) {
3248
3693
  const observed = isRecord(runtime[entity]) ? runtime[entity] : void 0;
3249
3694
  const clip = typeof observed?.clip === "string" ? observed.clip : void 0;
@@ -3349,6 +3794,7 @@ var init_movement_evidence = __esm({
3349
3794
  "src/evaluators/movement-evidence.ts"() {
3350
3795
  init_assertion_schema();
3351
3796
  init_assertion_report();
3797
+ init_perf_warnings();
3352
3798
  init_helpers();
3353
3799
  }
3354
3800
  });
@@ -3623,19 +4069,156 @@ var init_parity_evidence = __esm({
3623
4069
  }
3624
4070
  });
3625
4071
 
4072
+ // src/evaluators/adapter-class.ts
4073
+ function classifyAdapter(report) {
4074
+ const capture = report.capture;
4075
+ if (capture === void 0 || capture.rendererKind !== "webgpu") return {};
4076
+ if (adapterIdentity(capture.adapter) === void 0) return {};
4077
+ const software = softwareAdapterName(capture.adapter);
4078
+ if (software !== void 0) return { adapterClass: "software", softwareAdapter: software };
4079
+ const gpuFamily = gpuFamilyOf(capture.adapter);
4080
+ return gpuFamily === void 0 ? { adapterClass: "hardware" } : { adapterClass: "hardware", gpuFamily };
4081
+ }
4082
+ function adapterIdentity(adapter) {
4083
+ if (adapter === void 0) return void 0;
4084
+ for (const key of ADAPTER_IDENTITY_KEYS) {
4085
+ const value = adapter[key];
4086
+ if (typeof value === "string" && value.trim() !== "") return value;
4087
+ }
4088
+ return void 0;
4089
+ }
4090
+ function gpuFamilyOf(adapter) {
4091
+ if (adapter === void 0) return void 0;
4092
+ const field = (key) => {
4093
+ const value = adapter[key];
4094
+ return typeof value === "string" ? value : "";
4095
+ };
4096
+ const fields = {
4097
+ architecture: field("architecture"),
4098
+ description: field("description"),
4099
+ device: field("device"),
4100
+ vendor: field("vendor")
4101
+ };
4102
+ for (const rule of FAMILY_RULES) {
4103
+ const family = rule(fields);
4104
+ if (family !== void 0) return family;
4105
+ }
4106
+ return void 0;
4107
+ }
4108
+ function adapterFieldsFromIdentity(identity) {
4109
+ if (typeof identity !== "string") return void 0;
4110
+ const prefix = "webgpu:";
4111
+ if (!identity.startsWith(prefix)) return void 0;
4112
+ const fields = /* @__PURE__ */ Object.create(null);
4113
+ for (const pair of identity.slice(prefix.length).split("|")) {
4114
+ const separator = pair.indexOf("=");
4115
+ if (separator <= 0) return void 0;
4116
+ const key = pair.slice(0, separator);
4117
+ if (!ADAPTER_IDENTITY_KEYS.includes(key) || Object.hasOwn(fields, key)) {
4118
+ return void 0;
4119
+ }
4120
+ let value;
4121
+ try {
4122
+ value = decodeURIComponent(pair.slice(separator + 1));
4123
+ } catch {
4124
+ return void 0;
4125
+ }
4126
+ if (value.trim() === "") return void 0;
4127
+ fields[key] = value;
4128
+ }
4129
+ if (Object.keys(fields).length === 0) return void 0;
4130
+ return fields;
4131
+ }
4132
+ function nativeCaptureProvenance(census, target, viewport) {
4133
+ if (census === void 0 || census === null || typeof census !== "object" || Array.isArray(census)) return void 0;
4134
+ const adapterRecord = census.adapter;
4135
+ if (adapterRecord === void 0 || adapterRecord === null || typeof adapterRecord !== "object" || Array.isArray(adapterRecord)) return void 0;
4136
+ const adapter = adapterFieldsFromIdentity(adapterRecord.identity);
4137
+ if (adapter === void 0) return void 0;
4138
+ return {
4139
+ adapter,
4140
+ // A native launch carries no browser command line; there is no argument list to report and
4141
+ // inventing one would be a flag nobody can check.
4142
+ browserArgs: [],
4143
+ captureMethod: "device.screenshot",
4144
+ rendererKind: "webgpu",
4145
+ target,
4146
+ viewport
4147
+ };
4148
+ }
4149
+ var ADAPTER_IDENTITY_KEYS, MALI_MODEL, ADRENO_MODEL, AMD_INTEGRATED, INTEL_DISCRETE, FAMILY_RULES;
4150
+ var init_adapter_class = __esm({
4151
+ "src/evaluators/adapter-class.ts"() {
4152
+ init_browser();
4153
+ ADAPTER_IDENTITY_KEYS = ["architecture", "description", "device", "vendor"];
4154
+ MALI_MODEL = /\bmali[\s_-]*g?[\s-]*(\d{2,3})/i;
4155
+ ADRENO_MODEL = /\badreno\W*(?:tm\W*)?(\d)(\d\d|xx)/i;
4156
+ AMD_INTEGRATED = /radeon(?:\(tm\))?\s+(?:graphics|\d{3}m)\b/i;
4157
+ INTEL_DISCRETE = /\barc\b|xe2?-hpg|battlemage|alchemist/i;
4158
+ FAMILY_RULES = [
4159
+ ({ architecture, description, device }) => {
4160
+ const number = [description, device, architecture].map((value) => MALI_MODEL.exec(value)?.[1]).find((value) => value !== void 0);
4161
+ if (number === void 0) return void 0;
4162
+ const model = Number(number);
4163
+ if (model >= 710) return "mobile-high";
4164
+ return model < 57 || model === 71 || model === 72 ? "mobile-low" : "mobile-mid";
4165
+ },
4166
+ ({ architecture, vendor }) => {
4167
+ if (!/\barm\b/i.test(vendor)) return void 0;
4168
+ if (/midgard|bifrost/i.test(architecture)) return "mobile-low";
4169
+ if (/valhall/i.test(architecture)) return "mobile-mid";
4170
+ return /5th-?gen|immortalis/i.test(architecture) ? "mobile-high" : void 0;
4171
+ },
4172
+ ({ architecture, description, device }) => {
4173
+ const match = [description, device, architecture].map((value) => ADRENO_MODEL.exec(value)).find((value) => value !== null && value !== void 0);
4174
+ if (match === null || match === void 0) return void 0;
4175
+ const generation = Number(match[1]);
4176
+ if (generation <= 4) return "mobile-low";
4177
+ if (generation === 5) return "mobile-mid";
4178
+ if (generation === 6) return match[2] !== "xx" && Number(match[2]) >= 30 ? "mobile-high" : "mobile-mid";
4179
+ return "mobile-high";
4180
+ },
4181
+ ({ architecture, description, device, vendor }) => /nvidia/i.test(vendor) && ![architecture, description, device].some((value) => /tegra/i.test(value)) ? "discrete" : void 0,
4182
+ ({ architecture, description, device, vendor }) => {
4183
+ if (!/intel/i.test(vendor)) return void 0;
4184
+ return [architecture, description, device].some((value) => INTEL_DISCRETE.test(value)) ? "discrete" : "integrated";
4185
+ },
4186
+ // An APU and a card share an architecture name, so an AMD adapter that names no iGPU is `discrete`.
4187
+ ({ description, vendor }) => /\b(?:amd|ati)\b/i.test(vendor) ? AMD_INTEGRATED.test(description) ? "integrated" : "discrete" : void 0
4188
+ ];
4189
+ }
4190
+ });
4191
+
3626
4192
  // src/evaluators/perf-signals-world.ts
4193
+ function gpuLane(consoleTexts) {
4194
+ const { p95, samples } = gpuWindows(consoleTexts);
4195
+ return p95 === void 0 ? {} : { gpuP95: p95, ...samples === void 0 ? {} : { gpuSamples: samples } };
4196
+ }
3627
4197
  function emitPerfSignalsWorld(ctx) {
3628
4198
  const { assertions, diagnostics } = ctx;
3629
4199
  const { input, scenarioAssertions } = ctx;
3630
4200
  emitTerrainResidency(input.report.observations?.components?.terrain, assertions, diagnostics);
3631
4201
  if (scenarioAssertions.performance !== void 0) {
4202
+ const budget = frameBudget(scenarioAssertions.performance.maxFrameMsP95, classifyAdapter(input.report), scenarioAssertions.performance.maxFrameMsReason);
3632
4203
  const result = evaluatePerformanceAssertion(
3633
- scenarioAssertions.performance,
4204
+ budget.maxFrameMsP95 === void 0 ? scenarioAssertions.performance : { ...scenarioAssertions.performance, maxFrameMsP95: budget.maxFrameMsP95 },
3634
4205
  input.report.observations?.performanceSeries,
3635
- input.scenario.sourcePath
4206
+ input.scenario.sourcePath,
4207
+ { display: frameDisplay(), foreignGpu: foreignGpuProcesses(), ...gpuLane((input.report.observations?.console ?? []).map(({ text }) => text)) }
3636
4208
  );
3637
- assertions.push(...result.assertions);
4209
+ assertions.push(...result.assertions.map((row) => row.id === "performance.samples" || row.id === "performance.maxFrameMsP95" ? { ...row, details: { ...row.details, frameBudget: budget } } : row));
3638
4210
  diagnostics.push(...result.diagnostics);
4211
+ if (budget.unmeasurable === true) {
4212
+ assertions.push({ details: { frameBudget: budget }, id: "performance.maxFrameMsP95", pass: false });
4213
+ diagnostics.push({
4214
+ code: "TN_PLAYTEST_PERFORMANCE_UNMEASURABLE",
4215
+ message: `performance.maxFrameMsP95 cannot be judged: ${budget.reason}.`,
4216
+ observedRuntimePath: `${input.scenario.sourcePath ?? "playtest"}/observations.json/performanceSeries`,
4217
+ severity: "error",
4218
+ sourcePath: input.scenario.sourcePath,
4219
+ suggestion: "Run the scenario on a hardware GPU, or set maxFrameMsP95 with a maxFrameMsReason that names the adapter."
4220
+ });
4221
+ }
3639
4222
  }
3640
4223
  for (const assertion of scenarioAssertions.resources ?? []) {
3641
4224
  if (assertion.anyOf !== void 0) {
@@ -3679,7 +4262,7 @@ function emitPerfSignalsWorld(ctx) {
3679
4262
  const samples = assertion.atSteps.map((expected) => {
3680
4263
  const sample = (input.report.observations?.resourceSeries ?? []).find((candidate) => candidate.label === expected.label);
3681
4264
  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));
4265
+ 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
4266
  return { expected, pass: pass2, value };
3684
4267
  });
3685
4268
  const pass = samples.every((sample) => sample.pass);
@@ -3764,10 +4347,27 @@ function emitTerrainResidency(component, assertions, diagnostics) {
3764
4347
  suggestion: "Expose TerrainTiles.debug() through the terrain entity and inspect the residency counters."
3765
4348
  });
3766
4349
  }
4350
+ function frameBudget(explicit, adapter, reason) {
4351
+ const identity = {
4352
+ ...adapter.adapterClass === void 0 ? {} : { adapterClass: adapter.adapterClass },
4353
+ ...adapter.gpuFamily === void 0 ? {} : { gpuFamily: adapter.gpuFamily }
4354
+ };
4355
+ if (explicit !== void 0) {
4356
+ return { ...identity, maxFrameMsP95: explicit, reason: `maxFrameMsP95 set in the scenario overrides ${FRAME_BUDGET_MS} ms${reason === void 0 ? "" : `: ${reason}`}`, source: "scenario" };
4357
+ }
4358
+ if (adapter.adapterClass === "software") {
4359
+ return { ...identity, reason: `software adapter ${adapter.softwareAdapter ?? ""} is unmeasurable: it cannot carry a frame rate`.replace(" ", " "), source: "adapter", unmeasurable: true };
4360
+ }
4361
+ return { ...identity, maxFrameMsP95: FRAME_BUDGET_MS, reason: `one 60 Hz frame (${FRAME_BUDGET_MS} ms) on every tier`, source: "adapter" };
4362
+ }
4363
+ var FRAME_BUDGET_MS;
3767
4364
  var init_perf_signals_world = __esm({
3768
4365
  "src/evaluators/perf-signals-world.ts"() {
3769
4366
  init_assertion_report();
4367
+ init_adapter_class();
4368
+ init_frame_cost();
3770
4369
  init_helpers();
4370
+ FRAME_BUDGET_MS = 16.7;
3771
4371
  }
3772
4372
  });
3773
4373
 
@@ -4268,157 +4868,37 @@ function emitWorldTopology(value, assertions, diagnostics) {
4268
4868
  severity: "error",
4269
4869
  suggestion: "Inspect the seeded field and keep synthesis, erosion, and flow in their declared order."
4270
4870
  });
4271
- } catch (error) {
4272
- fail2(error instanceof Error ? error.message : String(error));
4273
- }
4274
- }
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;
4871
+ } catch (error) {
4872
+ fail2(error instanceof Error ? error.message : String(error));
4361
4873
  }
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
4874
  }
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
- ];
4875
+ var WORLD_TOPOLOGY_METRIC_FAILURES, WORLD_TOPOLOGY_MEASUREMENT_SIZE, DEFAULT_WORLD_TOPOLOGY_THRESHOLDS;
4876
+ var init_world_gameplay = __esm({
4877
+ "src/evaluators/world-gameplay.ts"() {
4878
+ init_assertion_report();
4879
+ init_helpers();
4880
+ WORLD_TOPOLOGY_METRIC_FAILURES = {
4881
+ directionalAnisotropy: "directional-anisotropy",
4882
+ powerSpectrumSlope: "power-spectrum-slope",
4883
+ reliefFieldEdge: "relief-field-edge",
4884
+ median64mRelief: "median-64m-relief",
4885
+ maxHortonStrahlerOrder: "horton-strahler-order",
4886
+ profileCurvatureExcessKurtosis: "curvature-excess-kurtosis",
4887
+ effectiveVertexDensityPerKm2: "effective-vertex-density",
4888
+ slopeTailAbove30Degrees: "slope-tail-above-30-degrees"
4889
+ };
4890
+ WORLD_TOPOLOGY_MEASUREMENT_SIZE = 1024;
4891
+ DEFAULT_WORLD_TOPOLOGY_THRESHOLDS = {
4892
+ maxDirectionalAnisotropy: 0.1,
4893
+ minPowerSpectrumSlope: 2.5,
4894
+ maxPowerSpectrumSlope: 5,
4895
+ minReliefFieldEdge: 0.1,
4896
+ maxMedian64mRelief: 0.25,
4897
+ minHortonStrahlerOrder: 5,
4898
+ minProfileCurvatureExcessKurtosis: 5,
4899
+ minEffectiveVertexDensityPerKm2: 5e5,
4900
+ minSlopeTailAbove30Degrees: 0.1
4901
+ };
4422
4902
  }
4423
4903
  });
4424
4904
 
@@ -4856,6 +5336,366 @@ var init_scene_nodes = __esm({
4856
5336
  }
4857
5337
  });
4858
5338
 
5339
+ // src/evaluators/foot-slip.ts
5340
+ function measureFootSlip(observation, stepSeconds = DEFAULT_STEP_SECONDS) {
5341
+ const { samples } = observation;
5342
+ let travel = 0;
5343
+ for (let index = 1; index < samples.length; index += 1) {
5344
+ const before = samples[index - 1].body;
5345
+ const after = samples[index].body;
5346
+ if (before !== null && after !== null) travel += Math.hypot(after[0] - before[0], after[2] - before[2]);
5347
+ }
5348
+ if (samples.length < 2 || samples.some(({ body }) => body === null))
5349
+ return { feet: [], travel, unobserved: `the subject '${observation.entity}' was not reported on every tick` };
5350
+ const missing = observation.feet.filter((_name, foot) => samples.some((sample) => sample.feet[foot] === null));
5351
+ if (missing.length > 0)
5352
+ 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` };
5353
+ if (travel < FOOT_SLIP_MIN_TRAVEL_M)
5354
+ 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` };
5355
+ const feet = observation.feet.map((name, foot) => {
5356
+ const heights = samples.map((sample) => sample.feet[foot][1] - sample.body[1]);
5357
+ const low = Math.min(...heights);
5358
+ const lift = Math.max(...heights) - low;
5359
+ const planted = heights.map((height) => height <= low + FOOT_SLIP_CONTACT_BAND * lift);
5360
+ let footTravel = 0;
5361
+ let bodyTravel = 0;
5362
+ let contactPairs = 0;
5363
+ for (let index = 1; index < samples.length; index += 1) {
5364
+ if (!planted[index - 1] || !planted[index]) continue;
5365
+ const [fx0, , fz0] = samples[index - 1].feet[foot];
5366
+ const [fx1, , fz1] = samples[index].feet[foot];
5367
+ const [bx0, , bz0] = samples[index - 1].body;
5368
+ const [bx1, , bz1] = samples[index].body;
5369
+ footTravel += Math.hypot(fx1 - fx0, fz1 - fz0);
5370
+ bodyTravel += Math.hypot(bx1 - bx0, bz1 - bz0);
5371
+ contactPairs += 1;
5372
+ }
5373
+ return {
5374
+ contactPairs,
5375
+ lift,
5376
+ name,
5377
+ ...contactPairs < MIN_CONTACT_PAIRS || bodyTravel <= 0 ? {} : { slip: footTravel / bodyTravel, speed: footTravel / (contactPairs * stepSeconds) }
5378
+ };
5379
+ });
5380
+ return { feet, travel };
5381
+ }
5382
+ function emitFootSlip(ctx) {
5383
+ const assertions = ctx.scenarioAssertions.footSlip;
5384
+ if (assertions === void 0 || assertions.length === 0) return;
5385
+ assertions.forEach((assertion, index) => {
5386
+ const id = `footSlip[${index}]`;
5387
+ const observation = ctx.input.report.observations?.footSlip?.find(({ label }) => label === assertion.atStep);
5388
+ const measure = observation === void 0 ? void 0 : measureFootSlip(observation, assertion.stepSeconds);
5389
+ const unmeasured = measure?.feet.find(({ slip }) => slip === void 0);
5390
+ 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`);
5391
+ if (reason !== void 0) {
5392
+ ctx.assertions.push({ details: { atStep: assertion.atStep, reason, ...measure === void 0 ? {} : { travel: measure.travel } }, id: `${id}.observed`, pass: false });
5393
+ ctx.diagnostics.push({
5394
+ code: "TN_PLAYTEST_FOOT_SLIP_UNOBSERVED",
5395
+ message: `footSlip at '${assertion.atStep}' was not measured: ${reason}.`,
5396
+ observedRuntimePath: "observations.json/footSlip",
5397
+ severity: "error",
5398
+ 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."
5399
+ });
5400
+ return;
5401
+ }
5402
+ const animation = runtimeGameplaySamples(ctx.input.report.observations?.runtimeObservations).find(({ label }) => label === assertion.atStep)?.gameplay.animation;
5403
+ const stride = isRecord(animation) ? strideReading(animation[observation.entity]) : void 0;
5404
+ if (stride !== void 0 && strideHasNoFootPlant(stride)) {
5405
+ ctx.assertions.push({ details: { atStep: assertion.atStep, reason: NO_FOOT_PLANT_DETAIL, stride, travel: measure.travel }, id: `${id}.observed`, pass: false });
5406
+ ctx.diagnostics.push({
5407
+ code: "TN_PLAYTEST_STRIDE_NO_FOOT_PLANT",
5408
+ message: `footSlip at '${assertion.atStep}' failed closed: ${NO_FOOT_PLANT_DETAIL}.`,
5409
+ observedRuntimePath: "observations.json/runtimeObservations",
5410
+ severity: "error",
5411
+ 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."
5412
+ });
5413
+ return;
5414
+ }
5415
+ const worst = Math.max(...measure.feet.map(({ slip }) => slip));
5416
+ const worstSpeed = Math.max(...measure.feet.map(({ speed }) => speed));
5417
+ const slipPass = assertion.maxSlip === void 0 || worst <= assertion.maxSlip;
5418
+ const speedPass = assertion.maxSlideSpeed === void 0 || worstSpeed <= assertion.maxSlideSpeed;
5419
+ ctx.assertions.push({
5420
+ details: {
5421
+ atStep: assertion.atStep,
5422
+ expected: { maxSlideSpeed: assertion.maxSlideSpeed, maxSlip: assertion.maxSlip },
5423
+ feet: measure.feet,
5424
+ travel: measure.travel,
5425
+ worst,
5426
+ worstSpeed
5427
+ },
5428
+ id: `${id}.slip`,
5429
+ pass: slipPass && speedPass
5430
+ });
5431
+ if (!slipPass)
5432
+ ctx.diagnostics.push({
5433
+ code: "TN_PLAYTEST_FOOT_SLIP",
5434
+ message: `A planted foot travelled ${worst.toFixed(2)} m per metre of body travel at '${assertion.atStep}', ceiling ${assertion.maxSlip}.`,
5435
+ observedRuntimePath: "observations.json/footSlip",
5436
+ severity: "error",
5437
+ 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."
5438
+ });
5439
+ if (!speedPass)
5440
+ ctx.diagnostics.push({
5441
+ code: "TN_PLAYTEST_FOOT_SLIP",
5442
+ message: `A planted foot slid at ${worstSpeed.toFixed(2)} m/s at '${assertion.atStep}', ceiling ${assertion.maxSlideSpeed} m/s.`,
5443
+ observedRuntimePath: "observations.json/footSlip",
5444
+ severity: "error",
5445
+ 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."
5446
+ });
5447
+ });
5448
+ }
5449
+ var FOOT_SLIP_MIN_TRAVEL_M, FOOT_SLIP_CONTACT_BAND, MIN_CONTACT_PAIRS, DEFAULT_STEP_SECONDS;
5450
+ var init_foot_slip = __esm({
5451
+ "src/evaluators/foot-slip.ts"() {
5452
+ init_assertion_report();
5453
+ init_families_observation();
5454
+ FOOT_SLIP_MIN_TRAVEL_M = 0.5;
5455
+ FOOT_SLIP_CONTACT_BAND = 0.25;
5456
+ MIN_CONTACT_PAIRS = 4;
5457
+ DEFAULT_STEP_SECONDS = 1 / 60;
5458
+ }
5459
+ });
5460
+
5461
+ // src/evaluators/sight-line.ts
5462
+ function topBlockers(blockers) {
5463
+ const counts = /* @__PURE__ */ new Map();
5464
+ for (const name of blockers) counts.set(name, (counts.get(name) ?? 0) + 1);
5465
+ return [...counts.entries()].sort(([leftName, leftCount], [rightName, rightCount]) => rightCount - leftCount || leftName.localeCompare(rightName)).slice(0, MAX_BLOCKER_NAMES).map(([name]) => name);
5466
+ }
5467
+ function emitSightLine(ctx) {
5468
+ const assertion = ctx.scenarioAssertions.sightLine;
5469
+ if (assertion === void 0) return;
5470
+ const observation = ctx.input.report.observations?.sightLine;
5471
+ const samples = observation?.samples ?? [];
5472
+ if (samples.length === 0) {
5473
+ ctx.assertions.push({ details: { samples: 0 }, id: "sightLine.observed", pass: false });
5474
+ ctx.diagnostics.push({
5475
+ code: "TN_PLAYTEST_SIGHT_LINE_UNOBSERVED",
5476
+ message: "A sightLine assertion was evaluated against a run that sampled no camera-to-subject sight line.",
5477
+ observedRuntimePath: "observations.json/sightLine",
5478
+ severity: "error",
5479
+ suggestion: "Run on the browser target and make sure the scenario advances at least one step whose subject is registered with the bridge."
5480
+ });
5481
+ return;
5482
+ }
5483
+ const blockedCount = samples.filter(({ blocked }) => blocked).length;
5484
+ const ratio = blockedCount / samples.length;
5485
+ const pass = ratio <= assertion.maxBlockedRatio;
5486
+ const blockers = topBlockers(samples.flatMap((sample) => sample.blockers));
5487
+ ctx.assertions.push({
5488
+ details: { blocked: blockedCount, blockers, ratio, samples: samples.length },
5489
+ id: "sightLine",
5490
+ pass
5491
+ });
5492
+ if (!pass) {
5493
+ ctx.diagnostics.push({
5494
+ code: "TN_PLAYTEST_SIGHT_LINE_BLOCKED",
5495
+ message: `Solid geometry blocked the camera's view of '${observation.entity}' on ${blockedCount} of ${samples.length} samples (${(ratio * 100).toFixed(1)}%), ceiling ${assertion.maxBlockedRatio}.`,
5496
+ observedRuntimePath: "observations.json/sightLine",
5497
+ severity: "error",
5498
+ 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."
5499
+ });
5500
+ }
5501
+ }
5502
+ var MAX_BLOCKER_NAMES;
5503
+ var init_sight_line = __esm({
5504
+ "src/evaluators/sight-line.ts"() {
5505
+ MAX_BLOCKER_NAMES = 5;
5506
+ }
5507
+ });
5508
+
5509
+ // src/evaluators/hud-audit.ts
5510
+ function channelLuminance(channel) {
5511
+ const value = channel / 255;
5512
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
5513
+ }
5514
+ function relativeLuminance([red, green, blue]) {
5515
+ return 0.2126 * channelLuminance(red) + 0.7152 * channelLuminance(green) + 0.0722 * channelLuminance(blue);
5516
+ }
5517
+ function contrastRatio(foreground, background) {
5518
+ const alpha = Math.min(Math.max(foreground[3], 0), 1);
5519
+ const composited = [
5520
+ foreground[0] * alpha + background[0] * (1 - alpha),
5521
+ foreground[1] * alpha + background[1] * (1 - alpha),
5522
+ foreground[2] * alpha + background[2] * (1 - alpha),
5523
+ 1
5524
+ ];
5525
+ const first = relativeLuminance(composited);
5526
+ const second = relativeLuminance(background);
5527
+ return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
5528
+ }
5529
+ function readsAsDeveloperText(text) {
5530
+ return DEVELOPER_TEXT.test(text) || UNRESOLVED_TEXT.test(text) || COERCED_OBJECT.test(text);
5531
+ }
5532
+ function offenders(items) {
5533
+ return items.slice(0, MAX_OFFENDERS).map(({ selector, text }) => ({ selector, text }));
5534
+ }
5535
+ function emitHudAudit(ctx) {
5536
+ const assertion = ctx.scenarioAssertions.hudAudit;
5537
+ if (assertion === void 0) return;
5538
+ const items = ctx.input.report.observations?.hudAudit?.items ?? [];
5539
+ if (items.length === 0) {
5540
+ ctx.assertions.push({ details: { items: 0 }, id: "hudAudit.observed", pass: false });
5541
+ ctx.diagnostics.push({
5542
+ code: "TN_PLAYTEST_HUD_AUDIT_UNOBSERVED",
5543
+ message: "A hudAudit assertion was evaluated against a run that reported no visible page text.",
5544
+ observedRuntimePath: "observations.json/hudAudit",
5545
+ severity: "error",
5546
+ suggestion: "Run on the browser target and make sure the page draws player-facing text in the DOM, outside a canvas."
5547
+ });
5548
+ return;
5549
+ }
5550
+ if (assertion.noDebugText === true) {
5551
+ const found = items.filter(({ text }) => readsAsDeveloperText(text));
5552
+ const pass = found.length === 0;
5553
+ ctx.assertions.push({
5554
+ details: { checked: items.length, offenders: offenders(found) },
5555
+ id: "hudAudit.debugText",
5556
+ pass
5557
+ });
5558
+ if (!pass) {
5559
+ ctx.diagnostics.push({
5560
+ code: "TN_PLAYTEST_HUD_DEBUG_TEXT",
5561
+ 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(", ")}.`,
5562
+ observedRuntimePath: "observations.json/hudAudit/items",
5563
+ severity: "error",
5564
+ suggestion: "Replace debug, TODO, placeholder and unresolved values with the copy the player should read, then rerun the scenario."
5565
+ });
5566
+ }
5567
+ }
5568
+ if (assertion.minContrast !== void 0) {
5569
+ const judged = items.filter(({ background }) => background[3] >= JUDGED_BACKGROUND_ALPHA);
5570
+ const unjudged = items.length - judged.length;
5571
+ 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);
5572
+ const pass = worst.every(({ ratio }) => ratio >= assertion.minContrast);
5573
+ ctx.assertions.push({
5574
+ details: { judged: judged.length, minContrast: assertion.minContrast, unjudged, worst },
5575
+ id: "hudAudit.contrast",
5576
+ pass
5577
+ });
5578
+ if (!pass) {
5579
+ ctx.diagnostics.push({
5580
+ code: "TN_PLAYTEST_HUD_CONTRAST",
5581
+ 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(", ")}.`,
5582
+ observedRuntimePath: "observations.json/hudAudit/items",
5583
+ severity: "error",
5584
+ suggestion: "Raise the text colour's contrast against its backing plate, or darken the plate, until every judged item reaches the floor."
5585
+ });
5586
+ }
5587
+ }
5588
+ }
5589
+ var MAX_OFFENDERS, JUDGED_BACKGROUND_ALPHA, DEVELOPER_TEXT, UNRESOLVED_TEXT, COERCED_OBJECT;
5590
+ var init_hud_audit = __esm({
5591
+ "src/evaluators/hud-audit.ts"() {
5592
+ MAX_OFFENDERS = 5;
5593
+ JUDGED_BACKGROUND_ALPHA = 0.5;
5594
+ DEVELOPER_TEXT = /\b(debug|todo|fixme|lorem ipsum|placeholder|probe|raycast|hitbox|wall ray)\b/iu;
5595
+ UNRESOLVED_TEXT = /\b(undefined|null|NaN)\b/u;
5596
+ COERCED_OBJECT = /\[object /u;
5597
+ }
5598
+ });
5599
+
5600
+ // src/evaluators/engine-cost.ts
5601
+ function engineCostWindows(lines) {
5602
+ const windows = [];
5603
+ let top;
5604
+ for (const line of lines) {
5605
+ if (typeof line !== "string") continue;
5606
+ const census = line.indexOf(BRIDGE_CENSUS_MARKER);
5607
+ if (census !== -1) {
5608
+ try {
5609
+ top = JSON.parse(line.slice(census + BRIDGE_CENSUS_MARKER.length)).top;
5610
+ } catch {
5611
+ top = void 0;
5612
+ }
5613
+ continue;
5614
+ }
5615
+ const at = line.indexOf(FRAME_BUDGET_MARKER);
5616
+ if (at === -1) continue;
5617
+ try {
5618
+ const report = JSON.parse(line.slice(at + FRAME_BUDGET_MARKER.length));
5619
+ const engine = report.counters?.engine;
5620
+ if (engine === void 0) continue;
5621
+ if (engine === null || typeof engine !== "object" || Array.isArray(engine)) throw new Error("invalid engine counters");
5622
+ const series = {
5623
+ ...engine,
5624
+ ...report.counters?.bridgeCrossings === void 0 ? {} : { bridgeCrossings: report.counters.bridgeCrossings }
5625
+ };
5626
+ for (const summary2 of Object.values(series)) {
5627
+ 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");
5628
+ }
5629
+ const pick = (field) => Object.fromEntries(Object.entries(series).map(([name, summary2]) => [name, summary2[field]]));
5630
+ windows.push({ maxFrame: pick("max"), perFrame: pick("mean"), top, ...report.window === void 0 ? {} : { window: report.window } });
5631
+ } catch {
5632
+ windows.push(void 0);
5633
+ }
5634
+ }
5635
+ return windows;
5636
+ }
5637
+ function topCaller(window2) {
5638
+ const top = window2.top?.[0];
5639
+ return top === void 0 ? "no census before this window" : `${top.name ?? "?"} ${top.perFrame ?? "?"}/frame from ${top.caller ?? "unknown"}`;
5640
+ }
5641
+ function emitEngineCost(ctx) {
5642
+ const assertion = ctx.scenarioAssertions.engineCost;
5643
+ if (assertion === void 0) return;
5644
+ const windows = engineCostWindows((ctx.input.report.observations?.console ?? []).map(({ text }) => text));
5645
+ const stillWindows = assertion.still?.windows ?? 0;
5646
+ const skipped = assertion.skipWindows ?? 0;
5647
+ const needed = Math.max(assertion.minWindows ?? 1, skipped + stillWindows + (assertion.moving === void 0 ? 0 : 1));
5648
+ const readable = windows.filter((window2) => window2 !== void 0);
5649
+ const observed = readable.length >= needed && readable.length === windows.length;
5650
+ ctx.assertions.push({ details: { windows: windows.length, unreadable: windows.length - readable.length, needed }, id: "engineCost.observed", pass: observed });
5651
+ if (!observed) {
5652
+ ctx.diagnostics.push({
5653
+ code: "TN_PLAYTEST_ENGINE_COST_UNOBSERVED",
5654
+ message: `engineCost needs ${needed} readable TN_FRAME_BUDGET window(s) with counters.engine; the run printed ${windows.length}, ${windows.length - readable.length} unreadable.`,
5655
+ observedRuntimePath: "observations.json/console",
5656
+ severity: "error",
5657
+ 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."
5658
+ });
5659
+ return;
5660
+ }
5661
+ const bounded = readable.slice(skipped);
5662
+ for (const [kind, table, scope, windows2] of [
5663
+ ["perFrame", assertion.maxPerFrame, "maxPerFrame", bounded],
5664
+ ["maxFrame", assertion.maxInFrame, "maxInFrame", bounded],
5665
+ ["perFrame", assertion.still?.maxPerFrame, "still.maxPerFrame", bounded.slice(0, stillWindows)],
5666
+ ["perFrame", assertion.moving?.maxPerFrame, "moving.maxPerFrame", bounded.slice(stillWindows)],
5667
+ ["maxFrame", assertion.moving?.maxInFrame, "moving.maxInFrame", bounded.slice(stillWindows)]
5668
+ ]) {
5669
+ for (const [name, bound] of Object.entries(table ?? {})) {
5670
+ const values = windows2.map((window2) => window2[kind]?.[name]);
5671
+ const missing = values.findIndex((value2) => typeof value2 !== "number" || !Number.isFinite(value2));
5672
+ const worst = windows2.reduce(
5673
+ (top, window2) => (window2[kind]?.[name] ?? -1) > (top?.[kind]?.[name] ?? -1) ? window2 : top,
5674
+ void 0
5675
+ );
5676
+ const value = worst?.[kind]?.[name] ?? Number.NaN;
5677
+ const pass = missing === -1 && value <= bound;
5678
+ const id = `engineCost.${scope}.${name}`;
5679
+ ctx.assertions.push({ details: { bound, value, window: worst?.window, source: assertion.source }, id, pass });
5680
+ if (pass) continue;
5681
+ ctx.diagnostics.push({
5682
+ code: "TN_PLAYTEST_ENGINE_COST_OVER_BOUND",
5683
+ 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)}.`,
5684
+ observedRuntimePath: "observations.json/console",
5685
+ severity: "error",
5686
+ 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."
5687
+ });
5688
+ }
5689
+ }
5690
+ }
5691
+ var FRAME_BUDGET_MARKER, BRIDGE_CENSUS_MARKER;
5692
+ var init_engine_cost = __esm({
5693
+ "src/evaluators/engine-cost.ts"() {
5694
+ FRAME_BUDGET_MARKER = "TN_FRAME_BUDGET:";
5695
+ BRIDGE_CENSUS_MARKER = "TN_BRIDGE_CENSUS:";
5696
+ }
5697
+ });
5698
+
4859
5699
  // src/runner/sceneRoom.ts
4860
5700
  function summariseRoom(scene) {
4861
5701
  const types = {};
@@ -5065,7 +5905,40 @@ var init_scene = __esm({
5065
5905
  });
5066
5906
 
5067
5907
  // src/evaluators/startup.ts
5908
+ function emitOffscreenBytes(ctx) {
5909
+ const ceiling = ctx.scenarioAssertions.startup?.maxOffscreenBytes;
5910
+ const observed = ctx.input.report.observations?.startup?.offscreenBytes;
5911
+ const unsized = observed !== void 0 && observed.awaitedBytes === 0 && observed.unsizedFiles > 0;
5912
+ if (ceiling !== void 0) {
5913
+ const measured = observed !== void 0 && !unsized;
5914
+ const pass = measured && observed.offscreenBytes <= ceiling;
5915
+ ctx.assertions.push({
5916
+ details: { expected: ceiling, observed: measured ? observed.offscreenBytes : void 0 },
5917
+ id: "startup.offscreenBytes",
5918
+ pass
5919
+ });
5920
+ if (!pass) {
5921
+ ctx.diagnostics.push({
5922
+ code: measured ? "TN_PLAYTEST_STARTUP_OFFSCREEN_BYTES" : "TN_PLAYTEST_STARTUP_UNOBSERVABLE",
5923
+ 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.`,
5924
+ observedRuntimePath: "observations.json/startup/offscreenBytes",
5925
+ severity: "error",
5926
+ 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."
5927
+ });
5928
+ return;
5929
+ }
5930
+ }
5931
+ if (observed?.warn !== true) return;
5932
+ ctx.diagnostics.push({
5933
+ code: "TN_PLAYTEST_STARTUP_OFFSCREEN_BYTES",
5934
+ 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(", ")}).`,
5935
+ observedRuntimePath: "observations.json/startup/offscreenBytes",
5936
+ severity: "warning",
5937
+ suggestion: observed.fix
5938
+ });
5939
+ }
5068
5940
  function emitStartup(ctx) {
5941
+ emitOffscreenBytes(ctx);
5069
5942
  const assertion = ctx.scenarioAssertions.startup;
5070
5943
  if (assertion === void 0) return;
5071
5944
  const timeline = ctx.input.report.observations?.startup?.timeline;
@@ -5088,10 +5961,34 @@ function emitStartup(ctx) {
5088
5961
  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
5962
  });
5090
5963
  }
5964
+ if (assertion.steadyCover === true) emitSteadyCover(ctx);
5965
+ }
5966
+ function emitSteadyCover(ctx) {
5967
+ const cover = ctx.input.report.observations?.startup?.cover;
5968
+ const observed = cover !== void 0 && cover.frames > 0 && cover.worldMs !== void 0;
5969
+ const uiOverCover = cover?.uiOverCover ?? [];
5970
+ const pass = observed && cover.differing.length === 0 && uiOverCover.length === 0;
5971
+ ctx.assertions.push({
5972
+ 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 },
5973
+ id: "startup.steadyCover",
5974
+ pass
5975
+ });
5976
+ if (pass) return;
5977
+ const first = cover?.differing[0];
5978
+ const ui = uiOverCover[0];
5979
+ ctx.diagnostics.push({
5980
+ code: !observed ? "TN_PLAYTEST_STARTUP_COVER_UNOBSERVED" : first === void 0 && ui !== void 0 ? "TN_PLAYTEST_STARTUP_UI_OVER_COVER" : "TN_PLAYTEST_STARTUP_COVER_BROKEN",
5981
+ 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.",
5982
+ observedRuntimePath: "observations.json/startup/cover",
5983
+ severity: "error",
5984
+ 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."
5985
+ });
5091
5986
  }
5092
- var MILESTONES;
5987
+ var MB, mb, MILESTONES;
5093
5988
  var init_startup = __esm({
5094
5989
  "src/evaluators/startup.ts"() {
5990
+ MB = 1e6;
5991
+ mb = (bytes) => `${(bytes / MB).toFixed(1)} MB`;
5095
5992
  MILESTONES = {
5096
5993
  maxCompileSettledMs: "compileSettledMs",
5097
5994
  maxEnteredMs: "enteredMs",
@@ -6315,6 +7212,10 @@ function evaluateRichPlaytestAssertions(input) {
6315
7212
  emitPipelineCensus(ctx);
6316
7213
  emitScene(ctx);
6317
7214
  emitSceneNodes(ctx);
7215
+ emitFootSlip(ctx);
7216
+ emitSightLine(ctx);
7217
+ emitHudAudit(ctx);
7218
+ emitEngineCost(ctx);
6318
7219
  if (scenarioAssertions.geometry !== void 0) {
6319
7220
  const observed = input.report.observations?.geometry;
6320
7221
  const status = observed?.status;
@@ -6357,6 +7258,10 @@ var init_assertion_evaluators = __esm({
6357
7258
  init_render_chain();
6358
7259
  init_caused_by();
6359
7260
  init_scene_nodes();
7261
+ init_foot_slip();
7262
+ init_sight_line();
7263
+ init_hud_audit();
7264
+ init_engine_cost();
6360
7265
  init_scene();
6361
7266
  init_startup();
6362
7267
  init_pipeline_census();
@@ -6521,6 +7426,7 @@ var init_generated_assertion_validators = __esm({
6521
7426
  }),
6522
7427
  "performance": Object.freeze({
6523
7428
  "maxFrameMsP95": (value) => typeof value === "number" && Number.isFinite(value),
7429
+ "maxFrameMsReason": (value) => typeof value === "string" && value.trim() !== "",
6524
7430
  "minFps": (value) => typeof value === "number" && Number.isFinite(value),
6525
7431
  "maxPhaseMsP95": (value) => isRecord2(value),
6526
7432
  "maxDrawCalls": (value) => typeof value === "number" && Number.isFinite(value),
@@ -6578,6 +7484,7 @@ var init_generated_assertion_validators = __esm({
6578
7484
  "animation": Object.freeze({
6579
7485
  "entity": (value) => typeof value === "string" && value.trim() !== "",
6580
7486
  "clip": (value) => typeof value === "string" && value.trim() !== "",
7487
+ "atStep": (value) => typeof value === "string" && value.trim() !== "",
6581
7488
  "entered": (value) => typeof value === "boolean",
6582
7489
  "advancedFrames": (value) => typeof value === "number" && Number.isFinite(value),
6583
7490
  "finished": (value) => typeof value === "boolean",
@@ -6602,6 +7509,31 @@ var init_generated_assertion_validators = __esm({
6602
7509
  "maxCount": (value) => typeof value === "number" && Number.isFinite(value),
6603
7510
  "minTriangles": (value) => typeof value === "number" && Number.isFinite(value)
6604
7511
  }),
7512
+ "footSlip": Object.freeze({
7513
+ "atStep": (value) => typeof value === "string" && value.trim() !== "",
7514
+ "feet": (value) => Array.isArray(value),
7515
+ "maxSlip": (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
7516
+ "maxSlideSpeed": (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
7517
+ "stepSeconds": (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
7518
+ "entity": (value) => typeof value === "string" && value.trim() !== ""
7519
+ }),
7520
+ "sightLine": Object.freeze({
7521
+ "entity": (value) => typeof value === "string" && value.trim() !== "",
7522
+ "maxBlockedRatio": (value) => typeof value === "number" && Number.isFinite(value)
7523
+ }),
7524
+ "engineCost": Object.freeze({
7525
+ "maxPerFrame": (value) => isRecord2(value),
7526
+ "maxInFrame": (value) => isRecord2(value),
7527
+ "minWindows": (value) => typeof value === "number" && Number.isInteger(value) && value > 0,
7528
+ "skipWindows": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
7529
+ "still": (value) => isRecord2(value),
7530
+ "moving": (value) => isRecord2(value),
7531
+ "source": (value) => typeof value === "string" && value.trim() !== ""
7532
+ }),
7533
+ "hudAudit": Object.freeze({
7534
+ "minContrast": (value) => typeof value === "number" && Number.isFinite(value),
7535
+ "noDebugText": (value) => value === true
7536
+ }),
6605
7537
  "causedBy": Object.freeze({
6606
7538
  "cause": (value) => isRecord2(value),
6607
7539
  "effect": (value) => isRecord2(value),
@@ -6611,7 +7543,9 @@ var init_generated_assertion_validators = __esm({
6611
7543
  "startup": Object.freeze({
6612
7544
  "maxEnteredMs": (value) => typeof value === "number" && Number.isFinite(value),
6613
7545
  "maxCompileSettledMs": (value) => typeof value === "number" && Number.isFinite(value),
6614
- "maxReadyMs": (value) => typeof value === "number" && Number.isFinite(value)
7546
+ "maxReadyMs": (value) => typeof value === "number" && Number.isFinite(value),
7547
+ "maxOffscreenBytes": (value) => typeof value === "number" && Number.isFinite(value),
7548
+ "steadyCover": (value) => typeof value === "boolean"
6615
7549
  }),
6616
7550
  "pipelineCensus": Object.freeze({
6617
7551
  "maxNodeBuildsAfterWarmUpSettled": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
@@ -6645,6 +7579,9 @@ function validateVisualAssertion(value, scenarioPath, objectPath) {
6645
7579
  if (authoredEdge !== void 0) {
6646
7580
  throw invalidScenario(scenarioPath, `'${objectPath}.region.${authoredEdge}' cannot be combined with an element-bound region; the element supplies its bounds.`);
6647
7581
  }
7582
+ if (hasKey(regionRecord, "minSharpness")) {
7583
+ throw invalidScenario(scenarioPath, `'${objectPath}.region.minSharpness' measures the rendered frame; bound a static x/y/width/height region instead of an element.`);
7584
+ }
6648
7585
  region = {
6649
7586
  element,
6650
7587
  ...present("maxDarkPixelRatio", optionalRatio(regionRecord, "maxDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
@@ -6663,6 +7600,7 @@ function validateVisualAssertion(value, scenarioPath, objectPath) {
6663
7600
  }
6664
7601
  region = {
6665
7602
  ...edges,
7603
+ ...present("minSharpness", optionalPositiveNumber(regionRecord, "minSharpness", scenarioPath, `${objectPath}.region`)),
6666
7604
  ...present("maxDarkPixelRatio", optionalRatio(regionRecord, "maxDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
6667
7605
  ...present("maxLuminance", optionalRatio(regionRecord, "maxLuminance", scenarioPath, `${objectPath}.region`)),
6668
7606
  ...present("minDarkPixelRatio", optionalRatio(regionRecord, "minDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
@@ -6866,16 +7804,26 @@ function validateDeviceMetricsAssertion(value, scenarioPath, objectPath) {
6866
7804
  }
6867
7805
  function validatePerformanceAssertion(value, scenarioPath, objectPath) {
6868
7806
  const record4 = requireRecord(value, scenarioPath, objectPath);
6869
- rejectUnknownKeys(record4, ["maxDrawCalls", "maxFrameMsP95", "maxPassDrawCalls", "maxPassTriangles", "maxPhaseMsP95", "maxTriangles", "minFps"], scenarioPath, objectPath);
7807
+ rejectUnknownKeys(record4, ["maxDrawCalls", "maxFrameMsP95", "maxFrameMsReason", "maxPassDrawCalls", "maxPassTriangles", "maxPhaseMsP95", "maxTriangles", "minFps"], scenarioPath, objectPath);
6870
7808
  const assertion = {
6871
7809
  ...present("maxDrawCalls", optionalNonNegativeNumber(record4, "maxDrawCalls", scenarioPath, objectPath)),
6872
7810
  ...present("maxFrameMsP95", optionalNonNegativeNumber(record4, "maxFrameMsP95", scenarioPath, objectPath)),
7811
+ ...present("maxFrameMsReason", optionalString(record4, "maxFrameMsReason", scenarioPath, objectPath)),
6873
7812
  ...present("maxPassDrawCalls", validatePassBudget(record4.maxPassDrawCalls, scenarioPath, `${objectPath}.maxPassDrawCalls`)),
6874
7813
  ...present("maxPassTriangles", validatePassBudget(record4.maxPassTriangles, scenarioPath, `${objectPath}.maxPassTriangles`)),
6875
7814
  ...present("maxPhaseMsP95", validatePhaseBudget(record4.maxPhaseMsP95, scenarioPath, `${objectPath}.maxPhaseMsP95`)),
6876
7815
  ...present("maxTriangles", optionalNonNegativeNumber(record4, "maxTriangles", scenarioPath, objectPath)),
6877
7816
  ...present("minFps", optionalNonNegativeNumber(record4, "minFps", scenarioPath, objectPath))
6878
7817
  };
7818
+ if (assertion.maxFrameMsP95 === LEGACY_SCAFFOLD_FRAME_MS && record4.maxFrameMsReason === void 0) {
7819
+ return { ...assertion, maxFrameMsReason: LEGACY_SCAFFOLD_FRAME_REASON };
7820
+ }
7821
+ if (assertion.maxFrameMsP95 !== void 0 && assertion.maxFrameMsP95 > 16.7 && (assertion.maxFrameMsReason ?? "").trim() === "") {
7822
+ throw invalidScenario(
7823
+ scenarioPath,
7824
+ `'${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.`
7825
+ );
7826
+ }
6879
7827
  if (Object.keys(assertion).length === 0) {
6880
7828
  throw invalidScenario(
6881
7829
  scenarioPath,
@@ -7036,8 +7984,21 @@ function validateStartupAssertion(value, scenarioPath, objectPath) {
7036
7984
  }
7037
7985
  result[key] = ceiling;
7038
7986
  }
7987
+ const bytes = record4.maxOffscreenBytes;
7988
+ if (bytes !== void 0) {
7989
+ if (typeof bytes !== "number" || !Number.isInteger(bytes) || bytes < 0) {
7990
+ throw invalidScenario(scenarioPath, `'${objectPath}.maxOffscreenBytes' must be a non-negative integer number of bytes, received ${describeValue(bytes)}.`);
7991
+ }
7992
+ result.maxOffscreenBytes = bytes;
7993
+ }
7994
+ if (record4.steadyCover !== void 0) {
7995
+ if (record4.steadyCover !== true) {
7996
+ throw invalidScenario(scenarioPath, `'${objectPath}.steadyCover' must be true, received ${describeValue(record4.steadyCover)}; leave it out to skip the check.`);
7997
+ }
7998
+ result.steadyCover = true;
7999
+ }
7039
8000
  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.`);
8001
+ throw invalidScenario(scenarioPath, `'${objectPath}' must set at least one of ${[...STARTUP_CEILINGS, "maxOffscreenBytes", "steadyCover"].join(", ")}; an empty startup assertion observes nothing.`);
7041
8002
  }
7042
8003
  return result;
7043
8004
  }
@@ -7337,12 +8298,116 @@ function validateSceneNodesAssertion(value, scenarioPath, objectPath) {
7337
8298
  );
7338
8299
  return result;
7339
8300
  }
8301
+ function validateFootSlipAssertion(value, scenarioPath, objectPath) {
8302
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8303
+ rejectUnknownKeys(record4, ["atStep", "entity", "feet", "maxSlideSpeed", "maxSlip", "stepSeconds"], scenarioPath, objectPath);
8304
+ const feet = record4.feet;
8305
+ if (!Array.isArray(feet) || feet.length === 0 || feet.some((foot) => typeof foot !== "string" || foot.trim() === "") || new Set(feet).size !== feet.length)
8306
+ throw invalidScenario(scenarioPath, `${objectPath}.feet must be a non-empty array of unique node names; got ${describeValue(feet)}.`);
8307
+ const maxSlip = optionalPositiveNumber(record4, "maxSlip", scenarioPath, objectPath);
8308
+ const maxSlideSpeed = optionalPositiveNumber(record4, "maxSlideSpeed", scenarioPath, objectPath);
8309
+ if (maxSlip === void 0 && maxSlideSpeed === void 0)
8310
+ throw invalidScenario(scenarioPath, `${objectPath}.maxSlip or ${objectPath}.maxSlideSpeed is required; a slip measure with no ceiling bounds nothing.`);
8311
+ return {
8312
+ atStep: requireString(record4, "atStep", scenarioPath, objectPath),
8313
+ ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
8314
+ feet,
8315
+ ...present("maxSlideSpeed", maxSlideSpeed),
8316
+ ...present("maxSlip", maxSlip),
8317
+ ...present("stepSeconds", optionalPositiveNumber(record4, "stepSeconds", scenarioPath, objectPath))
8318
+ };
8319
+ }
8320
+ function validateSightLineAssertion(value, scenarioPath, objectPath) {
8321
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8322
+ rejectUnknownKeys(record4, ["entity", "maxBlockedRatio"], scenarioPath, objectPath);
8323
+ const maxBlockedRatio = optionalRatio(record4, "maxBlockedRatio", scenarioPath, objectPath);
8324
+ if (maxBlockedRatio === void 0) throw invalidScenario(scenarioPath, `${objectPath}.maxBlockedRatio is required; a sight line with no allowed blocked share bounds nothing.`);
8325
+ return {
8326
+ ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
8327
+ maxBlockedRatio
8328
+ };
8329
+ }
8330
+ function validateEngineCostAssertion(value, scenarioPath, objectPath) {
8331
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8332
+ rejectUnknownKeys(record4, ["maxInFrame", "maxPerFrame", "minWindows", "moving", "skipWindows", "source", "still"], scenarioPath, objectPath);
8333
+ const bounds = (key, owner = record4, at = objectPath) => {
8334
+ if (!hasKey(owner, key)) return void 0;
8335
+ const table = requireRecord(owner[key], scenarioPath, `${at}.${key}`);
8336
+ const names = Object.keys(table);
8337
+ if (names.length === 0) throw invalidScenario(scenarioPath, `'${at}.${key}' names no counter.`);
8338
+ for (const name of names) {
8339
+ const bound = table[name];
8340
+ if (typeof bound !== "number" || !Number.isFinite(bound) || bound < 0)
8341
+ throw invalidScenario(scenarioPath, `'${at}.${key}.${name}' must be a non-negative number, received ${describeValue(bound)}.`);
8342
+ }
8343
+ return table;
8344
+ };
8345
+ const maxPerFrame = bounds("maxPerFrame");
8346
+ const maxInFrame = bounds("maxInFrame");
8347
+ let still;
8348
+ if (hasKey(record4, "still")) {
8349
+ const at = `${objectPath}.still`;
8350
+ const stillRecord = requireRecord(record4.still, scenarioPath, at);
8351
+ rejectUnknownKeys(stillRecord, ["maxPerFrame", "windows"], scenarioPath, at);
8352
+ const windows = optionalPositiveInteger(stillRecord, "windows", scenarioPath, at);
8353
+ const stillBounds = bounds("maxPerFrame", stillRecord, at);
8354
+ if (windows === void 0 || stillBounds === void 0)
8355
+ throw invalidScenario(scenarioPath, `${at} needs 'windows' and 'maxPerFrame'.`);
8356
+ still = { maxPerFrame: stillBounds, windows };
8357
+ }
8358
+ let moving;
8359
+ if (hasKey(record4, "moving")) {
8360
+ const at = `${objectPath}.moving`;
8361
+ const movingRecord = requireRecord(record4.moving, scenarioPath, at);
8362
+ rejectUnknownKeys(movingRecord, ["maxInFrame", "maxPerFrame"], scenarioPath, at);
8363
+ if (still === void 0) throw invalidScenario(scenarioPath, `${at} needs 'still': the moving windows are the ones after it.`);
8364
+ const movingPerFrame = bounds("maxPerFrame", movingRecord, at);
8365
+ const movingInFrame = bounds("maxInFrame", movingRecord, at);
8366
+ if (movingPerFrame === void 0 && movingInFrame === void 0)
8367
+ throw invalidScenario(scenarioPath, `${at} must bound at least one counter.`);
8368
+ moving = { ...present("maxPerFrame", movingPerFrame), ...present("maxInFrame", movingInFrame) };
8369
+ }
8370
+ if (maxPerFrame === void 0 && maxInFrame === void 0 && still === void 0 && moving === void 0)
8371
+ throw invalidScenario(scenarioPath, `${objectPath} must bound at least one counter in 'maxPerFrame', 'maxInFrame', 'still' or 'moving'.`);
8372
+ const source = requireString(record4, "source", scenarioPath, objectPath);
8373
+ if (source.trim().length < 12)
8374
+ throw invalidScenario(scenarioPath, `'${objectPath}.source' must say where the bounds came from.`);
8375
+ return {
8376
+ ...present("maxPerFrame", maxPerFrame),
8377
+ ...present("maxInFrame", maxInFrame),
8378
+ ...present("minWindows", optionalPositiveInteger(record4, "minWindows", scenarioPath, objectPath)),
8379
+ ...present("skipWindows", optionalNonNegativeInteger(record4, "skipWindows", scenarioPath, objectPath)),
8380
+ source,
8381
+ ...present("still", still),
8382
+ ...present("moving", moving)
8383
+ };
8384
+ }
8385
+ function validateHudAuditAssertion(value, scenarioPath, objectPath) {
8386
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8387
+ rejectUnknownKeys(record4, ["minContrast", "noDebugText"], scenarioPath, objectPath);
8388
+ const noDebugText = optionalBoolean(record4, "noDebugText", scenarioPath, objectPath);
8389
+ if (noDebugText === false) {
8390
+ throw invalidScenario(scenarioPath, `'${objectPath}.noDebugText' may only be true; remove the key to stop scanning for developer text.`);
8391
+ }
8392
+ const minContrast = optionalNumber2(record4, "minContrast", scenarioPath, objectPath);
8393
+ if (minContrast !== void 0 && (minContrast < 1 || minContrast > 21)) {
8394
+ throw invalidScenario(scenarioPath, `'${objectPath}.minContrast' must be between 1 and 21, received ${describeValue(minContrast)}.`);
8395
+ }
8396
+ if (noDebugText === void 0 && minContrast === void 0) {
8397
+ throw invalidScenario(scenarioPath, `${objectPath} must declare at least one of 'minContrast' or 'noDebugText'.`);
8398
+ }
8399
+ return {
8400
+ ...present("minContrast", minContrast),
8401
+ ...noDebugText === void 0 ? {} : { noDebugText: true }
8402
+ };
8403
+ }
7340
8404
  function validateAnimationAssertion(value, scenarioPath, objectPath) {
7341
8405
  const record4 = requireRecord(value, scenarioPath, objectPath);
7342
- rejectUnknownKeys(record4, ["advancedFrames", "allowTrivial", "clip", "entered", "entity", "finished", "maxFootSlide", "strideSynced"], scenarioPath, objectPath);
8406
+ rejectUnknownKeys(record4, ["advancedFrames", "allowTrivial", "atStep", "clip", "entered", "entity", "finished", "maxFootSlide", "strideSynced"], scenarioPath, objectPath);
7343
8407
  return {
7344
8408
  ...present("advancedFrames", optionalNumber2(record4, "advancedFrames", scenarioPath, objectPath)),
7345
8409
  ...present("allowTrivial", optionalTrivialityReason(record4, "allowTrivial", scenarioPath, objectPath)),
8410
+ ...present("atStep", optionalString(record4, "atStep", scenarioPath, objectPath)),
7346
8411
  ...present("clip", optionalString(record4, "clip", scenarioPath, objectPath)),
7347
8412
  ...present("entered", optionalBoolean(record4, "entered", scenarioPath, objectPath)),
7348
8413
  ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
@@ -7372,12 +8437,14 @@ function validatePathAssertion(value, scenarioPath, objectPath) {
7372
8437
  const atSteps = Array.isArray(record4.atSteps) ? record4.atSteps.map((step, index) => {
7373
8438
  const stepPath = `${objectPath}.atSteps[${index}]`;
7374
8439
  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.`);
8440
+ const stepLte = optionalNumber2(entry, "lte", scenarioPath, stepPath);
8441
+ if (!hasKey(entry, "equals") && entry.textIncludes === void 0 && stepLte === void 0) {
8442
+ throw invalidScenario(scenarioPath, `'${stepPath}' must set equals, lte or textIncludes; a labeled step with no expectation passes on any value.`);
7377
8443
  }
7378
8444
  return {
7379
8445
  ...hasKey(entry, "equals") ? { equals: entry.equals } : {},
7380
8446
  label: requireString(entry, "label", scenarioPath, stepPath),
8447
+ ...present("lte", stepLte),
7381
8448
  ...present("textIncludes", optionalString(entry, "textIncludes", scenarioPath, stepPath))
7382
8449
  };
7383
8450
  }) : void 0;
@@ -7534,7 +8601,7 @@ function validateNestedAssertionKeys(kind, value, scenarioPath, suffix) {
7534
8601
  if (Array.isArray(value.atSteps)) {
7535
8602
  value.atSteps.forEach((step, index) => {
7536
8603
  if (isRecord3(step)) {
7537
- rejectUnknownKeys(step, kind === "components" ? ["equals", "label"] : ["equals", "label", "textIncludes"], scenarioPath, `assert.${kind}${suffix}.atSteps[${index}]`);
8604
+ rejectUnknownKeys(step, kind === "components" ? ["equals", "label"] : ["equals", "label", "lte", "textIncludes"], scenarioPath, `assert.${kind}${suffix}.atSteps[${index}]`);
7538
8605
  }
7539
8606
  });
7540
8607
  }
@@ -7543,7 +8610,7 @@ function validateNestedAssertionKeys(kind, value, scenarioPath, suffix) {
7543
8610
  const fields = {
7544
8611
  entityVisible: ["entity", "minProjectedPixels", "throughoutFrames"],
7545
8612
  frameDiff: ["baselineImage", "maxChangedPixelRatio", "minChangedPixelRatio"],
7546
- region: ["element", "height", "maxDarkPixelRatio", "maxLuminance", "minDarkPixelRatio", "minNonblankPixelRatio", "width", "x", "y"]
8613
+ region: ["element", "height", "maxDarkPixelRatio", "maxLuminance", "minDarkPixelRatio", "minNonblankPixelRatio", "minSharpness", "width", "x", "y"]
7547
8614
  };
7548
8615
  for (const [field, keys] of Object.entries(fields)) {
7549
8616
  if (isRecord3(value[field])) {
@@ -7599,7 +8666,7 @@ function rejectRenderChainExpectationKeys(value, scenarioPath, objectPath) {
7599
8666
  }
7600
8667
  }
7601
8668
  }
7602
- var STARTUP_CEILINGS, PIPELINE_CENSUS_CEILINGS, SCENE_FLAGS, SCENE_NODE_SELECTOR_KEYS, SCENE_NODE_BOUNDS, RENDER_CHAIN_NESTED_KEYS;
8669
+ 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
8670
  var init_schema_accessors = __esm({
7604
8671
  "src/scenario/schema-accessors.ts"() {
7605
8672
  init_assertions();
@@ -7607,6 +8674,8 @@ var init_schema_accessors = __esm({
7607
8674
  init_errors();
7608
8675
  init_schema_base();
7609
8676
  init_generated_assertion_validators();
8677
+ LEGACY_SCAFFOLD_FRAME_MS = 33;
8678
+ 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
8679
  STARTUP_CEILINGS = ["maxEnteredMs", "maxCompileSettledMs", "maxReadyMs"];
7611
8680
  PIPELINE_CENSUS_CEILINGS = [
7612
8681
  "maxNodeBuildsAfterWarmUpSettled",
@@ -7657,12 +8726,25 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7657
8726
  if (value.bootFailure !== void 0 && target !== "web") {
7658
8727
  throw invalidScenario(scenarioPath, "Scenario bootFailure is browser-only and requires target 'web'.");
7659
8728
  }
8729
+ if (value.clock !== void 0 && value.clock !== "wall-clock") {
8730
+ throw invalidScenario(scenarioPath, "Scenario clock must be 'wall-clock' when present.");
8731
+ }
8732
+ if (value.clock !== void 0 && target !== "web") {
8733
+ throw invalidScenario(scenarioPath, "Scenario clock is browser-only and requires target 'web'.");
8734
+ }
7660
8735
  if (value.reducedMotion !== void 0 && value.reducedMotion !== "reduce") {
7661
8736
  throw invalidScenario(scenarioPath, "Scenario reducedMotion must be 'reduce' when present.");
7662
8737
  }
7663
8738
  if (value.reducedMotion !== void 0 && target !== "web") {
7664
8739
  throw invalidScenario(scenarioPath, "Scenario reducedMotion is browser-only and requires target 'web'.");
7665
8740
  }
8741
+ if (value.network !== void 0 && !isRecord3(value.network)) {
8742
+ throw invalidScenario(scenarioPath, "Scenario network must be an object with downloadKbps and latencyMs.");
8743
+ }
8744
+ const network = value.network === void 0 ? void 0 : validateNetworkProfile(value.network, scenarioPath);
8745
+ if (network !== void 0 && target !== "web") {
8746
+ throw invalidScenario(scenarioPath, "Scenario network is browser-only and requires target 'web'.");
8747
+ }
7666
8748
  const inputDelivery = value.inputDelivery ?? "deterministic";
7667
8749
  if (inputDelivery !== "deterministic" && inputDelivery !== "focused-dom") {
7668
8750
  throw invalidScenario(scenarioPath, "Scenario inputDelivery must be deterministic or focused-dom.");
@@ -7677,7 +8759,7 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7677
8759
  throw invalidScenario(scenarioPath, "Scenario subject must be a non-empty entity id when present.");
7678
8760
  }
7679
8761
  const subject = typeof value.subject === "string" ? value.subject : void 0;
7680
- const steps = value.steps.map((step, index) => validateStep(step, scenarioPath, index));
8762
+ 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
8763
  if (steps.some(({ kind }) => kind === "aimAt") && subject === void 0) {
7682
8764
  throw invalidScenario(scenarioPath, "A step with kind 'aimAt' aims the subject player start; declare scenario.subject or replace the step.");
7683
8765
  }
@@ -7689,8 +8771,10 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7689
8771
  ...assertions === void 0 ? {} : { assert: assertions },
7690
8772
  ...typeof value.awaitStartup === "boolean" ? { awaitStartup: value.awaitStartup } : {},
7691
8773
  ...value.bootFailure === "renderer-no-adapter" ? { bootFailure: value.bootFailure } : {},
8774
+ ...value.clock === "wall-clock" ? { clock: value.clock } : {},
7692
8775
  inputDelivery,
7693
8776
  name,
8777
+ ...network === void 0 ? {} : { network },
7694
8778
  ...value.parity === void 0 ? {} : { parity: validateParityConfig(requireRecord(value.parity, scenarioPath, "parity"), scenarioPath) },
7695
8779
  ...value.reducedMotion === "reduce" ? { reducedMotion: value.reducedMotion } : {},
7696
8780
  schemaVersion: 1,
@@ -7704,6 +8788,55 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7704
8788
  warmupFrames: optionalNonNegativeInteger(value, "warmupFrames", scenarioPath, "scenario") ?? 0
7705
8789
  };
7706
8790
  }
8791
+ function expandExploreStep(value, scenarioPath, index) {
8792
+ rejectUnknownKeys(value, ["actions", "kind", "label", "move", "pointer", "seed", "ticks"], scenarioPath, `steps[${index}]`);
8793
+ const keys = (field) => {
8794
+ const list = value[field];
8795
+ if (list === void 0 && field === "actions") return [];
8796
+ if (!Array.isArray(list) || list.length === 0 || list.some((key) => typeof key !== "string" || key.trim() === "") || new Set(list).size !== list.length) {
8797
+ throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' must define ${field} as a non-empty array of unique key names.`);
8798
+ }
8799
+ return list;
8800
+ };
8801
+ if (!Number.isSafeInteger(value.seed)) throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' must define seed as an integer.`);
8802
+ const ticks = positiveInteger2(value.ticks);
8803
+ if (ticks === void 0) throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' must define ticks as a positive integer.`);
8804
+ if (value.pointer !== void 0 && typeof value.pointer !== "boolean") throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' pointer must be a boolean.`);
8805
+ 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.`);
8806
+ const move = keys("move");
8807
+ const actions = keys("actions");
8808
+ let state = value.seed >>> 0;
8809
+ const random = () => {
8810
+ state = state + 1831565813 >>> 0;
8811
+ let t = state;
8812
+ t = Math.imul(t ^ t >>> 15, t | 1);
8813
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
8814
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
8815
+ };
8816
+ const pick = (list) => list[Math.floor(random() * list.length)];
8817
+ const steps = [];
8818
+ let heading = pick(move);
8819
+ for (let left = ticks; left > 0; ) {
8820
+ const holdTicks = Math.min(left, 10 + Math.floor(random() * 50));
8821
+ if (random() < 0.2) heading = pick(move);
8822
+ const press = /* @__PURE__ */ new Set([heading]);
8823
+ if (move.length > 1 && random() < 0.35) press.add(pick(move));
8824
+ if (actions.length > 0 && random() < 0.5) {
8825
+ press.add(pick(actions));
8826
+ if (random() < 0.25) press.add(pick(actions));
8827
+ }
8828
+ steps.push({
8829
+ holdTicks,
8830
+ kind: "input",
8831
+ press: [...press],
8832
+ ...value.pointer === true ? { pointerPosition: { x: random(), y: random() } } : {},
8833
+ release: true
8834
+ });
8835
+ left -= holdTicks;
8836
+ }
8837
+ if (typeof value.label === "string") steps[steps.length - 1].label = value.label;
8838
+ return steps;
8839
+ }
7707
8840
  function validateArtifacts(value, scenarioPath) {
7708
8841
  rejectUnknownKeys(value, ["console", "contactSheet", "effectLog", "network", "runtimeTrace", "screenshots"], scenarioPath, "artifacts");
7709
8842
  for (const key of ["console", "contactSheet", "network", "runtimeTrace"]) {
@@ -7786,6 +8919,21 @@ function validateParityTargets(value, scenarioPath, objectPath) {
7786
8919
  return target;
7787
8920
  });
7788
8921
  }
8922
+ function validateNetworkProfile(value, scenarioPath) {
8923
+ rejectUnknownKeys(value, ["downloadKbps", "latencyMs"], scenarioPath, "network");
8924
+ const downloadKbps = value.downloadKbps;
8925
+ if (typeof downloadKbps !== "number" || !Number.isFinite(downloadKbps) || downloadKbps <= 0) {
8926
+ throw invalidScenario(
8927
+ scenarioPath,
8928
+ "Scenario network.downloadKbps must be a positive number of kilobits per second."
8929
+ );
8930
+ }
8931
+ const latencyMs = value.latencyMs;
8932
+ if (typeof latencyMs !== "number" || !Number.isFinite(latencyMs) || latencyMs < 0) {
8933
+ throw invalidScenario(scenarioPath, "Scenario network.latencyMs must be a non-negative number.");
8934
+ }
8935
+ return { downloadKbps, latencyMs };
8936
+ }
7789
8937
  function validateSetup(value, scenarioPath, subject) {
7790
8938
  rejectUnknownKeys(value, ["aim", "entities", "place", "resources", "spawn"], scenarioPath, "setup");
7791
8939
  const spawn10 = validateSpawnRequest(value.spawn, scenarioPath);
@@ -8000,7 +9148,7 @@ function validateStep(value, scenarioPath, index) {
8000
9148
  const waitTicks = positiveInteger2(value.waitTicks);
8001
9149
  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
9150
  if (value.kind !== void 0 && kind === void 0) {
8003
- throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'input', 'lifecycle', or 'wait'.`);
9151
+ throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'explore', 'input', 'lifecycle', or 'wait'.`);
8004
9152
  }
8005
9153
  const at = validateClickTarget(value.at, scenarioPath, index);
8006
9154
  const target = validateAimTarget(value.target, scenarioPath, index);
@@ -8328,6 +9476,14 @@ function validateStepLabels(steps, assertions, scenarioPath) {
8328
9476
  for (const [index, assertion] of (assertions.tone ?? []).entries()) {
8329
9477
  requireLabel(assertion.atStep, `assert.tone[${index}].atStep`);
8330
9478
  }
9479
+ for (const [index, assertion] of (assertions.animation ?? []).entries()) {
9480
+ requireLabel(assertion.atStep, `assert.animation[${index}].atStep`);
9481
+ }
9482
+ for (const [index, assertion] of (assertions.footSlip ?? []).entries()) {
9483
+ requireLabel(assertion.atStep, `assert.footSlip[${index}].atStep`);
9484
+ if (assertions.footSlip.findIndex(({ atStep }) => atStep === assertion.atStep) !== index)
9485
+ throw invalidScenario(scenarioPath, `Assertion 'assert.footSlip[${index}]' repeats atStep '${assertion.atStep}'; list every foot in one assertion.`);
9486
+ }
8331
9487
  for (const [index, assertion] of (assertions.signals ?? []).entries()) {
8332
9488
  requireLabel(assertion.atStep, `assert.signals[${index}].atStep`);
8333
9489
  }
@@ -8368,6 +9524,9 @@ function validateAssertions(value, scenarioPath) {
8368
9524
  if (Array.isArray(value.signals) && value.signals.length === 0) {
8369
9525
  throw invalidScenario(scenarioPath, "Assertion 'assert.signals' must contain at least one signal assertion.");
8370
9526
  }
9527
+ if (Array.isArray(value.footSlip) && value.footSlip.length === 0) {
9528
+ throw invalidScenario(scenarioPath, "Assertion 'assert.footSlip' must contain at least one foot-slip assertion.");
9529
+ }
8371
9530
  if (Array.isArray(value.tone) && value.tone.length === 0) {
8372
9531
  throw invalidScenario(scenarioPath, "Assertion 'assert.tone' must contain at least one tone assertion.");
8373
9532
  }
@@ -8383,7 +9542,7 @@ function validateAssertions(value, scenarioPath) {
8383
9542
  );
8384
9543
  }
8385
9544
  const diagnostics = isRecord3(value.diagnostics) ? value.diagnostics : void 0;
8386
- const performance = isRecord3(value.performance) ? validatePerformanceAssertion(value.performance, scenarioPath, "assert.performance") : void 0;
9545
+ const performance2 = isRecord3(value.performance) ? validatePerformanceAssertion(value.performance, scenarioPath, "assert.performance") : void 0;
8387
9546
  const deviceMetrics = value.deviceMetrics === void 0 ? void 0 : validateDeviceMetricsAssertion(value.deviceMetrics, scenarioPath, "assert.deviceMetrics");
8388
9547
  const parity = value.parity === void 0 ? void 0 : validateParityAssertion(value.parity, scenarioPath, "assert.parity");
8389
9548
  const framebufferCoverage = isRecord3(value.framebufferCoverage) ? validateFramebufferCoverageAssertion(
@@ -8442,7 +9601,7 @@ function validateAssertions(value, scenarioPath) {
8442
9601
  ...Array.isArray(value.hud) ? {
8443
9602
  hud: value.hud.map((entry, index) => validatePathAssertion(entry, scenarioPath, `assert.hud[${index}]`))
8444
9603
  } : {},
8445
- ...performance === void 0 ? {} : { performance },
9604
+ ...performance2 === void 0 ? {} : { performance: performance2 },
8446
9605
  ...renderChain === void 0 ? {} : { renderChain },
8447
9606
  ...startup === void 0 ? {} : { startup },
8448
9607
  ...pipelineCensus === void 0 ? {} : { pipelineCensus },
@@ -8451,6 +9610,12 @@ function validateAssertions(value, scenarioPath) {
8451
9610
  ...hasKey(value, "causedBy") ? {
8452
9611
  causedBy: requireArray(value, "causedBy", scenarioPath, "assert.causedBy").map((entry, index) => validateCausedByAssertion(entry, scenarioPath, `assert.causedBy[${index}]`))
8453
9612
  } : {},
9613
+ ...hasKey(value, "footSlip") ? {
9614
+ footSlip: requireArray(value, "footSlip", scenarioPath, "assert.footSlip").map((entry, index) => validateFootSlipAssertion(entry, scenarioPath, `assert.footSlip[${index}]`))
9615
+ } : {},
9616
+ ...hasKey(value, "sightLine") ? { sightLine: validateSightLineAssertion(value.sightLine, scenarioPath, "assert.sightLine") } : {},
9617
+ ...hasKey(value, "hudAudit") ? { hudAudit: validateHudAuditAssertion(value.hudAudit, scenarioPath, "assert.hudAudit") } : {},
9618
+ ...hasKey(value, "engineCost") ? { engineCost: validateEngineCostAssertion(value.engineCost, scenarioPath, "assert.engineCost") } : {},
8454
9619
  ...hasKey(value, "sceneNodes") ? {
8455
9620
  sceneNodes: requireArray(value, "sceneNodes", scenarioPath, "assert.sceneNodes").map((entry, index) => validateSceneNodesAssertion(entry, scenarioPath, `assert.sceneNodes[${index}]`))
8456
9621
  } : {},
@@ -8807,8 +9972,10 @@ var init_schema_validate = __esm({
8807
9972
  "assert",
8808
9973
  "awaitStartup",
8809
9974
  "bootFailure",
9975
+ "clock",
8810
9976
  "inputDelivery",
8811
9977
  "name",
9978
+ "network",
8812
9979
  "parity",
8813
9980
  "reducedMotion",
8814
9981
  "schemaVersion",
@@ -8843,7 +10010,7 @@ var init_schema_validate = __esm({
8843
10010
  "wheel",
8844
10011
  "window"
8845
10012
  ];
8846
- MAX_RESOURCE_WAIT_TIMEOUT_MS = 12e4;
10013
+ MAX_RESOURCE_WAIT_TIMEOUT_MS = 3e5;
8847
10014
  }
8848
10015
  });
8849
10016
 
@@ -9408,7 +10575,7 @@ var init_observationFields = __esm({
9408
10575
  "startup",
9409
10576
  "visual"
9410
10577
  ];
9411
- HOST_PLAYTEST_OBSERVATION_FIELDS = ["deviceLifecycle", "deviceMetrics", "tone"];
10578
+ HOST_PLAYTEST_OBSERVATION_FIELDS = ["deviceLifecycle", "deviceMetrics", "footSlip", "hudAudit", "sightLine", "tone"];
9412
10579
  }
9413
10580
  });
9414
10581
 
@@ -9608,12 +10775,13 @@ function managedServerError(message, url, timeoutMs, output) {
9608
10775
  "Run the server command directly, fix its first error, then rerun the same playtest command."
9609
10776
  ));
9610
10777
  }
9611
- var UNHANDLED_REJECTION_PREFIX, SCREENSHOT_TIMEOUT_MS, MAX_FIXED_STEP_STARTUP_RETRIES, STOPPED_LOOP_ERROR, ManagedServerError;
10778
+ var UNHANDLED_REJECTION_PREFIX, SCREENSHOT_TIMEOUT_MS, PRESENTATION_BOUND_MS, MAX_FIXED_STEP_STARTUP_RETRIES, STOPPED_LOOP_ERROR, ManagedServerError;
9612
10779
  var init_shared = __esm({
9613
10780
  "src/runner/shared.ts"() {
9614
10781
  init_index();
9615
10782
  UNHANDLED_REJECTION_PREFIX = "__THREENATIVE_PLAYTEST_UNHANDLED_REJECTION__:";
9616
10783
  SCREENSHOT_TIMEOUT_MS = 12e4;
10784
+ PRESENTATION_BOUND_MS = 1e4;
9617
10785
  MAX_FIXED_STEP_STARTUP_RETRIES = 120;
9618
10786
  STOPPED_LOOP_ERROR = "Cannot advance a stopped loop.";
9619
10787
  ManagedServerError = class extends Error {
@@ -9695,6 +10863,7 @@ var init_setup_request = __esm({
9695
10863
  // src/runner/bridgeClient.ts
9696
10864
  var bridgeClient_exports = {};
9697
10865
  __export(bridgeClient_exports, {
10866
+ PENDING_BRIDGE_OPERATIONS_GLOBAL: () => PENDING_BRIDGE_OPERATIONS_GLOBAL,
9698
10867
  PlaytestBridgeError: () => PlaytestBridgeError,
9699
10868
  PlaywrightTransport: () => PlaywrightTransport,
9700
10869
  advanceTimeoutMs: () => advanceTimeoutMs,
@@ -9780,7 +10949,8 @@ async function connectPlaytestBridgeTransport(transport, scenario, timeoutMs = b
9780
10949
  }
9781
10950
  return {
9782
10951
  advance: async (ticks, options) => {
9783
- await transport.call("advance", ticks, advanceTimeoutMs(ticks), options);
10952
+ const result = await transport.call("advance", ticks, advanceTimeoutMs(ticks), options);
10953
+ return typeof result?.ticks === "number" ? result.ticks : void 0;
9784
10954
  },
9785
10955
  applySetup: async (request) => {
9786
10956
  assertBoundedPayload(request);
@@ -9892,15 +11062,30 @@ async function bridgeCall(page, method, argument, timeoutMs = PLAYTEST_PROTOCOL_
9892
11062
  try {
9893
11063
  return await Promise.race([
9894
11064
  page.evaluate(
9895
- async ({ argument: argument2, globalName, method: method2, options: options2 }) => {
11065
+ ({ argument: argument2, globalName, method: method2, options: options2, pendingOperationsGlobal }) => {
9896
11066
  const bridge = globalThis[globalName];
9897
11067
  const operation = bridge?.[method2];
9898
11068
  if (typeof operation !== "function") {
9899
11069
  throw new Error(`Bridge operation '${method2}' is unavailable.`);
9900
11070
  }
9901
- return operation.call(bridge, argument2, options2);
11071
+ const result = operation.call(bridge, argument2, options2);
11072
+ if (result === null || typeof result !== "object" && typeof result !== "function") return result;
11073
+ if (typeof result.then !== "function") return result;
11074
+ const host = globalThis;
11075
+ const pending = host[pendingOperationsGlobal] ?? /* @__PURE__ */ new Set();
11076
+ host[pendingOperationsGlobal] = pending;
11077
+ pending.add(result);
11078
+ const forget = () => pending.delete(result);
11079
+ void result.then(forget, forget);
11080
+ return result;
9902
11081
  },
9903
- { argument, globalName: PLAYTEST_BRIDGE_GLOBAL, method, options }
11082
+ {
11083
+ argument,
11084
+ globalName: PLAYTEST_BRIDGE_GLOBAL,
11085
+ method,
11086
+ options,
11087
+ pendingOperationsGlobal: PENDING_BRIDGE_OPERATIONS_GLOBAL
11088
+ }
9904
11089
  ),
9905
11090
  new Promise((_resolve, reject) => {
9906
11091
  timeout = setTimeout(() => reject(new PlaytestBridgeError(playtestDiagnostic(
@@ -9914,7 +11099,7 @@ async function bridgeCall(page, method, argument, timeoutMs = PLAYTEST_PROTOCOL_
9914
11099
  if (timeout !== void 0) clearTimeout(timeout);
9915
11100
  }
9916
11101
  }
9917
- var STANDALONE_OBSERVATION_FIELD_SET, HOST_OBSERVATION_FIELD_SET, BROWSER_CAPABILITIES, PlaytestBridgeError, PlaywrightTransport;
11102
+ var STANDALONE_OBSERVATION_FIELD_SET, HOST_OBSERVATION_FIELD_SET, BROWSER_CAPABILITIES, PlaytestBridgeError, PlaywrightTransport, PENDING_BRIDGE_OPERATIONS_GLOBAL;
9918
11103
  var init_bridgeClient = __esm({
9919
11104
  "src/runner/bridgeClient.ts"() {
9920
11105
  init_index();
@@ -9961,6 +11146,7 @@ var init_bridgeClient = __esm({
9961
11146
  }).then(() => true).catch(() => false);
9962
11147
  }
9963
11148
  };
11149
+ PENDING_BRIDGE_OPERATIONS_GLOBAL = "__THREENATIVE_PLAYTEST_PENDING_OPERATIONS__";
9964
11150
  }
9965
11151
  });
9966
11152
 
@@ -10018,6 +11204,9 @@ var PlaytestCliUsageError = class extends Error {
10018
11204
  this.name = "PlaytestCliUsageError";
10019
11205
  }
10020
11206
  };
11207
+ function withScenarioClock(config, scenario) {
11208
+ return scenario.clock === "wall-clock" && config.liveClock !== true ? { ...config, liveClock: true } : config;
11209
+ }
10021
11210
  function formatUsage() {
10022
11211
  const flags = Object.entries(PLAYTEST_FLAGS).map(
10023
11212
  ([name, details]) => ` ${name.padEnd(20)} ${details.summary} (default: ${details.default})`
@@ -10253,7 +11442,7 @@ function parseStandalonePlaytestArgs(argv, cwd = process.cwd()) {
10253
11442
  ...flags.get("--xcrun")?.[0] === void 0 ? {} : { xcrunPath: flags.get("--xcrun")[0] }
10254
11443
  };
10255
11444
  }
10256
- var SCENARIO_GLOB = /[*?[]/u;
11445
+ var SCENARIO_GLOB = /[*?[{]/u;
10257
11446
  function expandScenarioPattern(projectPath, pattern) {
10258
11447
  if (!SCENARIO_GLOB.test(pattern)) return [pattern];
10259
11448
  const normalizedPattern = pattern.replaceAll("\\", "/");
@@ -10290,14 +11479,21 @@ function matchGlobParts(pattern, file) {
10290
11479
  return file.length > 0 && segmentMatches(head ?? "", file[0]) && matchGlobParts(tail, file.slice(1));
10291
11480
  }
10292
11481
  function segmentMatches(pattern, value) {
10293
- let expression = "^";
11482
+ return new RegExp(`^${segmentExpression(pattern)}$`, "u").test(value);
11483
+ }
11484
+ function segmentExpression(pattern) {
11485
+ let expression = "";
10294
11486
  for (let index = 0; index < pattern.length; index += 1) {
10295
11487
  const character = pattern[index];
10296
- if (character === "*") expression += "[^/]*";
11488
+ const close = character === "{" ? pattern.indexOf("}", index) : -1;
11489
+ if (close > index) {
11490
+ expression += `(?:${pattern.slice(index + 1, close).split(",").map(segmentExpression).join("|")})`;
11491
+ index = close;
11492
+ } else if (character === "*") expression += "[^/]*";
10297
11493
  else if (character === "?") expression += "[^/]";
10298
11494
  else expression += escapeRegExp(character);
10299
11495
  }
10300
- return new RegExp(`${expression}$`, "u").test(value);
11496
+ return expression;
10301
11497
  }
10302
11498
  function escapeRegExp(value) {
10303
11499
  return value.replace(/[|\\{}()[\]^$+?.]/gu, "\\$&");
@@ -10526,12 +11722,12 @@ function withPerformanceBudget(scenario, budget) {
10526
11722
  maxPassTriangles: { ...budget.maxPassTriangles, ...declared?.maxPassTriangles },
10527
11723
  maxPhaseMsP95: { ...budget.maxPhaseMsP95, ...declared?.maxPhaseMsP95 }
10528
11724
  };
10529
- const performance = {
11725
+ const performance2 = {
10530
11726
  ...budget,
10531
11727
  ...declared,
10532
11728
  ...Object.fromEntries(Object.entries(maps).filter(([, value]) => Object.keys(value).length > 0))
10533
11729
  };
10534
- return { ...scenario, assert: { ...scenario.assert, performance } };
11730
+ return { ...scenario, assert: { ...scenario.assert, performance: performance2 } };
10535
11731
  }
10536
11732
  async function resolveBuildReport(config) {
10537
11733
  if (config.buildReportPath === void 0) return config;
@@ -11281,7 +12477,9 @@ function parseAndroidConsoleEntries(output, app) {
11281
12477
  `(?:^|[^\\w.])${app.packageName.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}(?=[:/\\s,})]|$)`,
11282
12478
  "u"
11283
12479
  );
11284
- return output.split(/\r?\n/u).filter((line) => !/^[VDIWEF]\/(?:SurfaceSyncGroup|TransitionController)\(/u.test(line)).filter((line) => {
12480
+ return output.split(/\r?\n/u).filter(
12481
+ (line) => !/^[VDIWEF]\/(?:SurfaceSyncGroup|TransitionController|AppHibernationService)\(/u.test(line)
12482
+ ).filter((line) => {
11285
12483
  if (app === void 0) return /Mystral|THREENATIVE|chromium/u.test(line);
11286
12484
  if (app.pids.size === 0) return line.trim().length > 0;
11287
12485
  const pid = /^[VDIWEF]\/[^\n(]+\(\s*(\d+)\)/u.exec(line)?.[1];
@@ -11903,6 +13101,24 @@ function startupLine(overview) {
11903
13101
  if (overview.page?.adapter !== void 0) parts.push(`adapter ${overview.page.adapter}`);
11904
13102
  return overview.startupMs === void 0 && overview.page === void 0 && overview.startup === void 0 ? void 0 : ` startup ${parts.join(" \xB7 ")}`;
11905
13103
  }
13104
+ var REVEAL_ESTIMATE_LINK_MBIT = 20;
13105
+ function revealLine(overview) {
13106
+ const offscreen = overview.startup?.offscreenBytes;
13107
+ if (offscreen === void 0) return void 0;
13108
+ const mb2 = (bytes) => `${(bytes / 1e6).toFixed(1)} MB`;
13109
+ const seconds = offscreen.awaitedBytes * 8 / (REVEAL_ESTIMATE_LINK_MBIT * 1e6);
13110
+ const parts = [
13111
+ `awaited ${mb2(offscreen.awaitedBytes)}`,
13112
+ `off-screen ${mb2(offscreen.offscreenBytes)}`,
13113
+ `est. reveal download ${seconds.toFixed(1)} s at ${REVEAL_ESTIMATE_LINK_MBIT} Mbit/s`
13114
+ ];
13115
+ if (offscreen.unsizedFiles > 0) parts.push(`${offscreen.unsizedFiles} file(s) with no manifest size`);
13116
+ const worst = offscreen.top[0];
13117
+ const tail = offscreen.offscreenBytes > 0 && worst !== void 0 ? `
13118
+ largest off-screen: ${offscreen.top.map((file) => `${file.path} ${mb2(file.bytes)} (${file.reason})`).join(", ")}${offscreen.warn ? `
13119
+ warning: ${offscreen.fix}` : ""}` : "";
13120
+ return ` reveal ${parts.join(" \xB7 ")}${tail}`;
13121
+ }
11906
13122
  function screenLine(overview) {
11907
13123
  const { screen } = overview;
11908
13124
  if (screen === void 0) return void 0;
@@ -11945,6 +13161,7 @@ function formatSceneOverview(overview) {
11945
13161
  const lines = [
11946
13162
  `scene overview \u2014 ${overview.url}`,
11947
13163
  startupLine(overview),
13164
+ revealLine(overview),
11948
13165
  screenLine(overview),
11949
13166
  ` 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}`}`,
11950
13167
  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`,
@@ -12048,254 +13265,77 @@ async function pageProbe(page, consoleErrors4) {
12048
13265
  }
12049
13266
  }
12050
13267
  return {
12051
- ...adapter === void 0 || adapter.length === 0 ? {} : { adapter },
12052
- ...adapterInfo === void 0 ? {} : { adapterInfo },
12053
- ...canvas === null ? {} : {
12054
- canvas: {
12055
- dpr: globalThis.devicePixelRatio,
12056
- height: canvas.height,
12057
- width: canvas.width
12058
- }
12059
- }
12060
- };
12061
- }).catch(() => ({}));
12062
- return { ...probe, consoleErrors: [...consoleErrors4] };
12063
- }
12064
- async function screenshotStats(page, inspectFrame2) {
12065
- try {
12066
- return inspectFrame2(await page.screenshot({ type: "png" }));
12067
- } catch {
12068
- return void 0;
12069
- }
12070
- }
12071
- async function initStandalonePlaytest(projectPath = process.cwd()) {
12072
- const files = {
12073
- "playtest.adapter.example.ts": `import { installThreePlaytestBridge } from "@threenative/playtest/three";
12074
-
12075
- installThreePlaytestBridge({
12076
- camera,
12077
- entities: [{ id: "player", object: player }],
12078
- renderer,
12079
- scene,
12080
- });
12081
- `,
12082
- "playtest.config.json": `${JSON.stringify({
12083
- artifactDirectory: "artifacts/playtest",
12084
- scenario: "playtests/smoke.playtest.json",
12085
- url: "http://127.0.0.1:5173"
12086
- }, null, 2)}
12087
- `,
12088
- "playtests/smoke.playtest.json": `${JSON.stringify({
12089
- assert: { movement: { entity: "player", minDistance: 0.1 } },
12090
- name: "smoke",
12091
- schemaVersion: 1,
12092
- steps: [{ holdTicks: 8, press: "KeyW", release: true }],
12093
- subject: "player",
12094
- target: "web",
12095
- viewport: { height: 720, width: 1280 },
12096
- warmupFrames: 2
12097
- }, null, 2)}
12098
- `
12099
- };
12100
- const created = [];
12101
- for (const relativePath of Object.keys(files)) {
12102
- try {
12103
- await access(resolve(projectPath, relativePath));
12104
- throw new Error(`Refusing to overwrite existing '${relativePath}'. Move it or choose a clean project directory.`);
12105
- } catch (error) {
12106
- if (error instanceof Error && "code" in error && error.code === "ENOENT") continue;
12107
- throw error;
12108
- }
12109
- }
12110
- for (const [relativePath, content] of Object.entries(files)) {
12111
- const absolutePath = resolve(projectPath, relativePath);
12112
- await mkdir(resolve(absolutePath, ".."), { recursive: true });
12113
- await writeFile(absolutePath, content, { encoding: "utf8", flag: "wx" });
12114
- created.push(relativePath);
12115
- }
12116
- return { created };
12117
- }
12118
- var DEFAULT_XVFB_SCREEN = "1600x900x24";
12119
- var HOST_DISPLAY_ENV = "TN_PLAYTEST_HOST_DISPLAY";
12120
- var STRIPPED_WAYLAND_VARS = ["WAYLAND_DISPLAY", "WAYLAND_SOCKET", "XDG_SESSION_TYPE"];
12121
- function decideDisplayStrategy(input) {
12122
- if (input.platform !== "linux") return { kind: "host" };
12123
- const privateXvfb = {
12124
- kind: "private-xvfb",
12125
- screen: input.env.TN_XVFB_SCREEN ?? DEFAULT_XVFB_SCREEN
12126
- };
12127
- if (!hostDisplayRequested(input.env)) return privateXvfb;
12128
- const display = input.env.DISPLAY;
12129
- if (display === void 0 || display.length === 0) {
12130
- throw new Error("TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: the requested host display requires DISPLAY.");
12131
- }
12132
- const available = input.displaySocketExists?.(display) ?? x11DisplayIsUsable(display, input.env);
12133
- if (!available) {
12134
- throw new Error(`TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: cannot connect to requested DISPLAY=${display}. Refusing to substitute a private Xvfb.`);
12135
- }
12136
- return { display, kind: "existing" };
12137
- }
12138
- function hostDisplayRequested(env) {
12139
- const value = env[HOST_DISPLAY_ENV];
12140
- return value === "1" || value?.toLowerCase() === "true";
12141
- }
12142
- function x11DisplayIsUsable(display, env) {
12143
- const probe = spawnSync("xdpyinfo", ["-display", display], { env, stdio: "ignore", timeout: 2e3 });
12144
- if (probe.error) {
12145
- throw new Error(`TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: cannot verify DISPLAY=${display}: xdpyinfo ${probe.error.message}.`);
12146
- }
12147
- return probe.status === 0;
12148
- }
12149
- function childEnvForDisplay(env, display) {
12150
- const child = { ...env };
12151
- for (const name of STRIPPED_WAYLAND_VARS) delete child[name];
12152
- child.DISPLAY = display;
12153
- return child;
12154
- }
12155
- function runNeedsPixels(config, scenario) {
12156
- if (config.headless !== true) return true;
12157
- const takesScreenshot = scenario.artifacts?.screenshots !== false || scenario.steps.some(({ screenshot }) => screenshot !== void 0);
12158
- const evaluatesVisual = (scenario.assert?.visual?.length ?? 0) > 0 || (scenario.assert?.tone?.length ?? 0) > 0;
12159
- return takesScreenshot || evaluatesVisual || scenario.assert?.framebufferCoverage !== void 0;
12160
- }
12161
- async function provideDisplay(options = {}) {
12162
- const env = options.env ?? process.env;
12163
- const platform = options.platform ?? process.platform;
12164
- const strategy = decideDisplayStrategy({
12165
- displaySocketExists: options.displaySocketExists,
12166
- env,
12167
- platform
12168
- });
12169
- if (strategy.kind === "host") {
12170
- return {
12171
- compositor: void 0,
12172
- display: void 0,
12173
- env: { ...env },
12174
- release: async () => void 0,
12175
- strategy
12176
- };
12177
- }
12178
- if (strategy.kind === "existing") {
12179
- return {
12180
- compositor: void 0,
12181
- display: strategy.display,
12182
- env: childEnvForDisplay(env, strategy.display),
12183
- release: async () => void 0,
12184
- strategy
12185
- };
12186
- }
12187
- const commandExists2 = options.commandExists ?? defaultCommandExists;
12188
- if (!commandExists2("Xvfb")) {
12189
- throw new Error(
12190
- "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."
12191
- );
12192
- }
12193
- const spawnProcess = options.spawnProcess ?? spawn;
12194
- const xvfb = spawnProcess("Xvfb", [
12195
- "-displayfd",
12196
- "3",
12197
- "-nolisten",
12198
- "tcp",
12199
- // COMPOSITE and SHAPE are what a compositing manager needs before it can blend anything, and
12200
- // the native desktop runtime refuses to attach its UI overlay to a display without one. Xvfb
12201
- // does not enable them by default, so every native UI run on a private display reported
12202
- // `TN_UI_OVERLAY:{"attached":false,"reason":"no compositing manager is running"}` — including
12203
- // the starter template's own shipped native-playtests/react-hud scenario, which failed out of
12204
- // the box on a freshly scaffolded project. A browser run does not care either way.
12205
- "+extension",
12206
- "COMPOSITE",
12207
- "+extension",
12208
- "SHAPE",
12209
- "-screen",
12210
- "0",
12211
- strategy.screen
12212
- ], { stdio: ["ignore", "ignore", "pipe", "pipe"] });
12213
- xvfb.on?.("error", () => void 0);
12214
- try {
12215
- const number = await readXvfbDisplayNumber(xvfb);
12216
- const display = `:${number}`;
12217
- const compositor = await startCompositor(display, { commandExists: commandExists2, env, spawnProcess });
12218
- return {
12219
- compositor: compositor?.name,
12220
- display,
12221
- env: childEnvForDisplay(env, display),
12222
- release: async () => {
12223
- if (compositor !== void 0) await stopChild(compositor.child);
12224
- await stopChild(xvfb);
12225
- },
12226
- strategy
12227
- };
12228
- } catch (error) {
12229
- await stopChild(xvfb);
12230
- throw error;
12231
- }
12232
- }
12233
- var COMPOSITORS = [
12234
- { args: ["-n"], name: "xcompmgr" },
12235
- { args: [], name: "picom" },
12236
- { args: [], name: "compton" }
12237
- ];
12238
- var COMPOSITOR_SETTLE_MS = 250;
12239
- async function startCompositor(display, options) {
12240
- const choice = COMPOSITORS.find(({ name }) => options.commandExists(name));
12241
- if (choice === void 0) return void 0;
12242
- const child = options.spawnProcess(choice.name, [...choice.args], {
12243
- env: { ...options.env, DISPLAY: display },
12244
- stdio: "ignore"
12245
- });
12246
- let spawnFailed = false;
12247
- child.on?.("error", () => {
12248
- spawnFailed = true;
12249
- });
12250
- await new Promise((settle) => setTimeout(settle, COMPOSITOR_SETTLE_MS));
12251
- if (spawnFailed) return void 0;
12252
- if ((child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null) return void 0;
12253
- return { child, name: choice.name };
12254
- }
12255
- var XVFB_DISPLAY_TIMEOUT_MS = 3e4;
12256
- async function readXvfbDisplayNumber(xvfb) {
12257
- const report = xvfb.stdio[3];
12258
- if (report === null || report === void 0 || typeof report.on !== "function") {
12259
- throw new Error("Xvfb was spawned without a display-report descriptor to read.");
12260
- }
12261
- const stream = report;
12262
- return new Promise((resolveDisplay, rejectDisplay) => {
12263
- let settled = false;
12264
- const finish = (settle) => {
12265
- if (settled) return;
12266
- settled = true;
12267
- clearTimeout(timer);
12268
- stream.removeListener("data", onData);
12269
- stream.removeListener("close", onClose);
12270
- settle();
12271
- };
12272
- const onData = (chunk) => {
12273
- const number = Number.parseInt(String(chunk).trim(), 10);
12274
- if (Number.isInteger(number) && number >= 0) finish(() => resolveDisplay(number));
13268
+ ...adapter === void 0 || adapter.length === 0 ? {} : { adapter },
13269
+ ...adapterInfo === void 0 ? {} : { adapterInfo },
13270
+ ...canvas === null ? {} : {
13271
+ canvas: {
13272
+ dpr: globalThis.devicePixelRatio,
13273
+ height: canvas.height,
13274
+ width: canvas.width
13275
+ }
13276
+ }
12275
13277
  };
12276
- const onClose = () => finish(() => rejectDisplay(new Error("Xvfb exited before it reported a display.")));
12277
- const timer = setTimeout(() => finish(() => {
12278
- rejectDisplay(new Error(`Xvfb did not report a display within ${XVFB_DISPLAY_TIMEOUT_MS}ms.`));
12279
- }), XVFB_DISPLAY_TIMEOUT_MS);
12280
- stream.on("data", onData);
12281
- stream.on("close", onClose);
12282
- });
13278
+ }).catch(() => ({}));
13279
+ return { ...probe, consoleErrors: [...consoleErrors4] };
12283
13280
  }
12284
- async function stopChild(child) {
12285
- const exitedAlready = () => (child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null;
12286
- if (exitedAlready()) return;
12287
- child.kill("SIGTERM");
12288
- const started = Date.now();
12289
- while (Date.now() - started < 1e3 && !exitedAlready()) {
12290
- await new Promise((resolveWait) => setTimeout(resolveWait, 25));
13281
+ async function screenshotStats(page, inspectFrame2) {
13282
+ try {
13283
+ return inspectFrame2(await page.screenshot({ type: "png" }));
13284
+ } catch {
13285
+ return void 0;
12291
13286
  }
12292
- if (!exitedAlready()) child.kill("SIGKILL");
12293
13287
  }
12294
- function defaultCommandExists(command) {
12295
- const paths = (process.env.PATH ?? "").split(":").filter((segment) => segment.length > 0);
12296
- return paths.some((directory) => existsSync(join(directory, command)));
13288
+ async function initStandalonePlaytest(projectPath = process.cwd()) {
13289
+ const files = {
13290
+ "playtest.adapter.example.ts": `import { installThreePlaytestBridge } from "@threenative/playtest/three";
13291
+
13292
+ installThreePlaytestBridge({
13293
+ camera,
13294
+ entities: [{ id: "player", object: player }],
13295
+ renderer,
13296
+ scene,
13297
+ });
13298
+ `,
13299
+ "playtest.config.json": `${JSON.stringify({
13300
+ artifactDirectory: "artifacts/playtest",
13301
+ scenario: "playtests/smoke.playtest.json",
13302
+ url: "http://127.0.0.1:5173"
13303
+ }, null, 2)}
13304
+ `,
13305
+ "playtests/smoke.playtest.json": `${JSON.stringify({
13306
+ assert: { movement: { entity: "player", minDistance: 0.1 } },
13307
+ name: "smoke",
13308
+ schemaVersion: 1,
13309
+ steps: [{ holdTicks: 8, press: "KeyW", release: true }],
13310
+ subject: "player",
13311
+ target: "web",
13312
+ viewport: { height: 720, width: 1280 },
13313
+ warmupFrames: 2
13314
+ }, null, 2)}
13315
+ `
13316
+ };
13317
+ const created = [];
13318
+ for (const relativePath of Object.keys(files)) {
13319
+ try {
13320
+ await access(resolve(projectPath, relativePath));
13321
+ throw new Error(`Refusing to overwrite existing '${relativePath}'. Move it or choose a clean project directory.`);
13322
+ } catch (error) {
13323
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") continue;
13324
+ throw error;
13325
+ }
13326
+ }
13327
+ for (const [relativePath, content] of Object.entries(files)) {
13328
+ const absolutePath = resolve(projectPath, relativePath);
13329
+ await mkdir(resolve(absolutePath, ".."), { recursive: true });
13330
+ await writeFile(absolutePath, content, { encoding: "utf8", flag: "wx" });
13331
+ created.push(relativePath);
13332
+ }
13333
+ return { created };
12297
13334
  }
12298
13335
 
13336
+ // src/runner/perf.ts
13337
+ init_captureEnvironment();
13338
+
12299
13339
  // src/runner/pipeline-cache-observations.ts
12300
13340
  var marker = "TN_PIPELINE_CACHE:";
12301
13341
  var malformed2 = () => {
@@ -12817,9 +13857,10 @@ async function measureCpuWindow(label, resolveOwner, bridge, advance, options =
12817
13857
  }
12818
13858
 
12819
13859
  // src/runner/perf.ts
12820
- var FRAME_BUDGET_MARKER = "TN_FRAME_BUDGET:";
13860
+ var FRAME_BUDGET_MARKER2 = "TN_FRAME_BUDGET:";
12821
13861
  var PROJECTION_MARKER = "TN_PROJECTION:";
12822
13862
  var HOST_GAP_MARKER = "TN_HOST_GAP:";
13863
+ var PLAYER_FRAME_MARKER = "TN_PLAYER_FRAME:";
12823
13864
  var HITCH_MARKER = "TN_FRAME_HITCH:";
12824
13865
  var SLOW_PHASE_MARKER = "TN_SLOW_PHASE:";
12825
13866
  var PRESENTS_TICK_MARKER = "TN_PRESENTS_TICK:";
@@ -12987,6 +14028,42 @@ function requireSoakFrames(frames) {
12987
14028
  }
12988
14029
  return frames;
12989
14030
  }
14031
+ var RECORD_CAUSES = ["order", "offset", "count", "other"];
14032
+ function summarizePassRecording(frames) {
14033
+ const recorded = frames.filter((frame) => frame.recordCause !== void 0);
14034
+ if (recorded.length === 0) return void 0;
14035
+ const mean = (read2) => recorded.reduce((sum, frame) => {
14036
+ const value = read2(frame);
14037
+ if (value === void 0 || !Number.isFinite(value)) {
14038
+ throw new Error(`TN_PERF_MARKER_MALFORMED: a ${PLAYER_FRAME_MARKER.slice(0, -1)} line with recordCause lacks a stage field`);
14039
+ }
14040
+ return sum + value;
14041
+ }, 0) / recorded.length;
14042
+ const rebuilds = { order: 0, offset: 0, count: 0, other: 0 };
14043
+ for (const frame of recorded) {
14044
+ const cause = frame.recordCause ?? 0;
14045
+ if (!Number.isInteger(cause) || cause < 0 || cause > RECORD_CAUSES.length) {
14046
+ throw new Error(`TN_PERF_MARKER_MALFORMED: recordCause ${cause} is not a Renderer::RecordCause`);
14047
+ }
14048
+ if (cause > 0) rebuilds[RECORD_CAUSES[cause - 1]] += 1;
14049
+ }
14050
+ const cpuFrameMs = mean((frame) => frame.cpuFrameMs);
14051
+ const gameJs = mean((frame) => frame.gameJsMs);
14052
+ const renderPrepare = mean((frame) => frame.renderPrepareMs);
14053
+ const renderEncode = mean((frame) => frame.renderEncodeMs);
14054
+ return {
14055
+ frames: recorded.length,
14056
+ cpuFrameMs,
14057
+ stagesMs: { gameJs, renderPrepare, renderEncode, other: cpuFrameMs - gameJs - renderPrepare - renderEncode },
14058
+ rebuilds,
14059
+ mainRecordedDraws: recorded.reduce((sum, frame) => sum + (frame.mainRecorded ?? 0), 0),
14060
+ auxRecordedDraws: recorded.reduce((sum, frame) => sum + (frame.auxRecorded ?? 0), 0),
14061
+ shadowRecordedDraws: recorded.reduce((sum, frame) => sum + (frame.shadowRecorded ?? 0), 0),
14062
+ shadowDraws: mean((frame) => frame.shadowDraws),
14063
+ recordMs: mean((frame) => frame.recordMs),
14064
+ shadowEncodeMs: mean((frame) => frame.shadowEncodeMs)
14065
+ };
14066
+ }
12990
14067
  var PRESENTS_REACHED_DISPLAY_RATIO = 0.95;
12991
14068
  function rankExactReasons(exact) {
12992
14069
  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));
@@ -13008,9 +14085,12 @@ function parsePerformanceMarkers(text) {
13008
14085
  const projections = [];
13009
14086
  const projectionPayloads = /* @__PURE__ */ new Set();
13010
14087
  let presentMode;
14088
+ const playerFrames = [];
13011
14089
  const pipelineEvents = parsePipelineEventMarkers(text);
13012
14090
  for (const line of text.split("\n")) {
13013
- const budget = parseMarkerLine(line, FRAME_BUDGET_MARKER);
14091
+ const playerFrame = parseMarkerLine(line, PLAYER_FRAME_MARKER);
14092
+ if (playerFrame !== void 0) playerFrames.push(playerFrame);
14093
+ const budget = parseMarkerLine(line, FRAME_BUDGET_MARKER2);
13014
14094
  if (budget !== void 0) {
13015
14095
  const payload = JSON.stringify(budget);
13016
14096
  if (!budgetPayloads.has(payload)) {
@@ -13053,10 +14133,12 @@ function parsePerformanceMarkers(text) {
13053
14133
  const mode = PRESENT_MODE_PATTERN.exec(line);
13054
14134
  if (mode?.[1] !== void 0) presentMode = mode[1];
13055
14135
  }
14136
+ const passRecording = summarizePassRecording(playerFrames);
13056
14137
  return {
13057
14138
  budgets,
13058
14139
  hitches,
13059
14140
  hostGaps,
14141
+ ...passRecording === void 0 ? {} : { passRecording },
13060
14142
  pipelineEvents,
13061
14143
  pipelineCaches: parsePipelineCacheObservations(text),
13062
14144
  presentGaps,
@@ -13172,6 +14254,7 @@ function assessPerfMarkers(parse, bounds, source, display) {
13172
14254
  presentMode: parse.presentMode,
13173
14255
  slowPhases: parse.slowPhases,
13174
14256
  projections: parse.projections,
14257
+ ...parse.passRecording === void 0 ? {} : { passRecording: parse.passRecording },
13175
14258
  source,
13176
14259
  violations
13177
14260
  };
@@ -13312,7 +14395,7 @@ async function runExecutableOn(args, executable, display) {
13312
14395
  const cpuSnapshots = [];
13313
14396
  const cpuWindows = [];
13314
14397
  let cpuUnavailable = process.platform === "linux" ? void 0 : `on-CPU time needs Linux schedstat accounting; this host is ${process.platform}`;
13315
- const enoughWindows = () => collected.split(FRAME_BUDGET_MARKER).length - 1 >= args.requireWindows + 1;
14398
+ const enoughWindows = () => collected.split(FRAME_BUDGET_MARKER2).length - 1 >= args.requireWindows + 1;
13316
14399
  const readMemory = () => {
13317
14400
  try {
13318
14401
  return readProcStatusMemory(child.pid);
@@ -13405,7 +14488,7 @@ async function runExecutableOn(args, executable, display) {
13405
14488
  function framesReported(text) {
13406
14489
  let total = 0;
13407
14490
  for (const line of text.split("\n")) {
13408
- const window2 = parseMarkerLine(line, FRAME_BUDGET_MARKER);
14491
+ const window2 = parseMarkerLine(line, FRAME_BUDGET_MARKER2);
13409
14492
  if (window2 !== void 0) total += window2.frames;
13410
14493
  }
13411
14494
  return total;
@@ -13415,7 +14498,7 @@ function completeFrameWindows(text) {
13415
14498
  if (end === -1) return [];
13416
14499
  const windows = [];
13417
14500
  for (const line of text.slice(0, end).split("\n")) {
13418
- const window2 = parseMarkerLine(line, FRAME_BUDGET_MARKER);
14501
+ const window2 = parseMarkerLine(line, FRAME_BUDGET_MARKER2);
13419
14502
  if (window2 !== void 0) windows.push(window2);
13420
14503
  }
13421
14504
  return windows;
@@ -13462,7 +14545,7 @@ function newestProcessLines(text) {
13462
14545
  return lines.filter((line) => logcatPid(line) === void 0 || logcatPid(line) === pid).join("\n");
13463
14546
  }
13464
14547
  function newestPid(text) {
13465
- const newest = [...text.split("\n")].reverse().find((line) => line.includes(FRAME_BUDGET_MARKER));
14548
+ const newest = [...text.split("\n")].reverse().find((line) => line.includes(FRAME_BUDGET_MARKER2));
13466
14549
  return newest === void 0 ? void 0 : logcatPid(newest);
13467
14550
  }
13468
14551
  function logcatPid(line) {
@@ -13612,6 +14695,7 @@ function formatPerfReport(report) {
13612
14695
  }
13613
14696
  lines.push(...formatDrawSources(report.budgets));
13614
14697
  lines.push(...formatProjection(report.projections));
14698
+ if (report.passRecording !== void 0) lines.push(...formatPassRecording(report.passRecording));
13615
14699
  const lastGap = report.hostGaps.at(-1);
13616
14700
  if (lastGap !== void 0) {
13617
14701
  lines.push(`host gap segments (${lastGap.frames}-frame window, p50 ms):`);
@@ -13693,6 +14777,15 @@ function formatDrawSources(windows) {
13693
14777
  `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`)
13694
14778
  ];
13695
14779
  }
14780
+ function formatPassRecording(summary2) {
14781
+ const { stagesMs: stages, rebuilds } = summary2;
14782
+ const covered = stages.gameJs + stages.renderPrepare + stages.renderEncode;
14783
+ return [
14784
+ `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"}%)`,
14785
+ ` 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`,
14786
+ ` recording ${summary2.recordMs.toFixed(3)} ms, shadow direct encode ${summary2.shadowEncodeMs.toFixed(3)} ms (${summary2.shadowDraws.toFixed(1)} shadow draws)`
14787
+ ];
14788
+ }
13696
14789
  function formatProjection(windows) {
13697
14790
  const last = windows.at(-1);
13698
14791
  if (last === void 0) {
@@ -14439,6 +15532,82 @@ function containsPaintedPixels(screenshot) {
14439
15532
  }
14440
15533
  return false;
14441
15534
  }
15535
+ async function sampleHudAudit(page) {
15536
+ return page.evaluate(() => {
15537
+ const MAX_ITEMS = 400;
15538
+ const MAX_TEXT = 120;
15539
+ const parseColour = (value) => {
15540
+ const match = /^rgba?\((.+)\)$/u.exec(value.trim());
15541
+ if (match !== null) {
15542
+ const parts = match[1].split(/[\s,/]+/u).filter((part) => part !== "");
15543
+ const channels = parts.slice(0, 3).map((part) => Number.parseFloat(part));
15544
+ const alphaText = parts[3];
15545
+ const alpha = alphaText === void 0 ? 1 : Number.parseFloat(alphaText);
15546
+ const normalizedAlpha = alpha > 1 ? alpha / 255 : alpha;
15547
+ if (channels.length === 3 && channels.every((channel) => Number.isFinite(channel)) && Number.isFinite(normalizedAlpha)) {
15548
+ return [channels[0], channels[1], channels[2], Math.min(Math.max(normalizedAlpha, 0), 1)];
15549
+ }
15550
+ }
15551
+ const canvas = document.createElement("canvas");
15552
+ canvas.width = 1;
15553
+ canvas.height = 1;
15554
+ const context = canvas.getContext("2d", { willReadFrequently: true });
15555
+ if (context === null) return [0, 0, 0, 1];
15556
+ context.clearRect(0, 0, 1, 1);
15557
+ context.fillStyle = value;
15558
+ context.fillRect(0, 0, 1, 1);
15559
+ const data = context.getImageData(0, 0, 1, 1).data;
15560
+ return [data[0], data[1], data[2], data[3] / 255];
15561
+ };
15562
+ const backing = (element) => {
15563
+ let accumulated = [0, 0, 0, 0];
15564
+ for (let current = element; current !== null; current = current.parentElement) {
15565
+ const [r, g, b, a] = parseColour(window.getComputedStyle(current).backgroundColor);
15566
+ if (a > 0 && accumulated[3] < 0.99) {
15567
+ const near = accumulated[3];
15568
+ const total = near + a * (1 - near);
15569
+ if (total > 0) {
15570
+ accumulated = [
15571
+ (accumulated[0] * near + r * a * (1 - near)) / total,
15572
+ (accumulated[1] * near + g * a * (1 - near)) / total,
15573
+ (accumulated[2] * near + b * a * (1 - near)) / total,
15574
+ total
15575
+ ];
15576
+ }
15577
+ }
15578
+ if (accumulated[3] >= 0.99 || current === document.documentElement) break;
15579
+ }
15580
+ return accumulated;
15581
+ };
15582
+ const items = [];
15583
+ for (const element of document.body.querySelectorAll("*")) {
15584
+ if (items.length === MAX_ITEMS) break;
15585
+ if (element.closest("script, style, canvas, noscript") !== null) continue;
15586
+ let ownText = "";
15587
+ for (const node of element.childNodes) {
15588
+ if (node.nodeType === 3) ownText += node.textContent ?? "";
15589
+ }
15590
+ const text = ownText.replace(/\s+/gu, " ").trim();
15591
+ if (text === "") continue;
15592
+ const style = window.getComputedStyle(element);
15593
+ if (style.display === "none" || style.visibility !== "visible") continue;
15594
+ const opacity = Number.parseFloat(style.opacity);
15595
+ if (!Number.isFinite(opacity) || opacity <= 0) continue;
15596
+ const rect = element.getBoundingClientRect();
15597
+ if (rect.width <= 0 || rect.height <= 0) continue;
15598
+ if (rect.right <= 0 || rect.bottom <= 0 || rect.left >= window.innerWidth || rect.top >= window.innerHeight) continue;
15599
+ const classes = Array.from(element.classList).slice(0, 2).map((name) => `.${name}`).join("");
15600
+ items.push({
15601
+ background: backing(element),
15602
+ color: parseColour(style.color),
15603
+ fontSizePx: Number.parseFloat(style.fontSize),
15604
+ selector: `${element.tagName.toLowerCase()}${element.id === "" ? "" : `#${element.id}`}${classes}`,
15605
+ text: text.slice(0, MAX_TEXT)
15606
+ });
15607
+ }
15608
+ return { items };
15609
+ });
15610
+ }
14442
15611
  async function sampleHud(page, assertions) {
14443
15612
  if (assertions.length === 0) return {};
14444
15613
  const snapshots = await page.evaluate((requestedAssertions) => Object.fromEntries(requestedAssertions.flatMap(({ id, path: path2 }) => {
@@ -14825,9 +15994,50 @@ function regionMetrics(png, region) {
14825
15994
  if (luminance <= maximumLuminance) dark += 1;
14826
15995
  }
14827
15996
  }
14828
- return { darkPixelRatio: dark / pixels, nonblankPixelRatio: nonblank / pixels };
15997
+ return {
15998
+ darkPixelRatio: dark / pixels,
15999
+ nonblankPixelRatio: nonblank / pixels,
16000
+ ...region.minSharpness === void 0 ? {} : { sharpness: regionSharpness(png, x0, y0, x1, y1) }
16001
+ };
16002
+ }
16003
+ function regionSharpness(png, x0, y0, x1, y1) {
16004
+ const width = x1 - x0;
16005
+ const height = y1 - y0;
16006
+ const luma = new Float64Array(width * height);
16007
+ for (let y = 0; y < height; y += 1) {
16008
+ for (let x = 0; x < width; x += 1) {
16009
+ const offset = ((y0 + y) * png.width + x0 + x) * 4;
16010
+ luma[y * width + x] = 0.2126 * png.data[offset] + 0.7152 * png.data[offset + 1] + 0.0722 * png.data[offset + 2];
16011
+ }
16012
+ }
16013
+ const halfWidth = Math.floor(width / 2);
16014
+ const halfHeight = Math.floor(height / 2);
16015
+ const half = new Float64Array(halfWidth * halfHeight);
16016
+ for (let y = 0; y < halfHeight; y += 1) {
16017
+ for (let x = 0; x < halfWidth; x += 1) {
16018
+ const at = 2 * y * width + 2 * x;
16019
+ half[y * halfWidth + x] = (luma[at] + luma[at + 1] + luma[at + width] + luma[at + width + 1]) / 4;
16020
+ }
16021
+ }
16022
+ const coarse = laplacianVariance(half, halfWidth, halfHeight);
16023
+ return coarse === 0 ? 0 : laplacianVariance(luma, width, height) / coarse;
16024
+ }
16025
+ function laplacianVariance(luma, width, height) {
16026
+ let sum = 0;
16027
+ let squares = 0;
16028
+ let count = 0;
16029
+ for (let y = 1; y < height - 1; y += 1) {
16030
+ for (let x = 1; x < width - 1; x += 1) {
16031
+ const at = y * width + x;
16032
+ const value = luma[at - 1] + luma[at + 1] + luma[at - width] + luma[at + width] - 4 * luma[at];
16033
+ sum += value;
16034
+ squares += value * value;
16035
+ count += 1;
16036
+ }
16037
+ }
16038
+ return count === 0 ? 0 : squares / count - (sum / count) ** 2;
14829
16039
  }
14830
- async function runStep(page, bridge, step, viewport, pathEntity, pathPositions, inputState, movementSampleRequest, finalStep, subject, liveClock = false, cpuWindow, completionWindow) {
16040
+ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions, inputState, movementSampleRequest, finalStep, subject, liveClock = false, cpuWindow, stepWindow, sightLine) {
14831
16041
  if (step.waitForResource !== void 0) {
14832
16042
  if (bridge === void 0 || movementSampleRequest === void 0) {
14833
16043
  throw new PlaytestBridgeError(playtestDiagnostic(
@@ -14843,7 +16053,7 @@ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions,
14843
16053
  throw new PlaytestBridgeError(playtestDiagnostic(
14844
16054
  "TN_PLAYTEST_OBSERVATION_UNAVAILABLE",
14845
16055
  `Resource wait for '${wait.id}.${wait.path}' has no timeout.`,
14846
- "Validate the scenario with timeoutMs as a positive integer no greater than 120000."
16056
+ "Validate the scenario with timeoutMs as a positive integer no greater than 300000."
14847
16057
  ));
14848
16058
  }
14849
16059
  const after = await waitForResource({
@@ -14923,8 +16133,8 @@ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions,
14923
16133
  "Advertise runtime.fixedStep from the bridge so ticks are deterministic, or author the step in waitFrames/holdFrames, which are display frames and say so."
14924
16134
  ));
14925
16135
  }
14926
- if (completionWindow !== void 0) {
14927
- await completionWindow();
16136
+ if (stepWindow !== void 0) {
16137
+ await stepWindow(ticks);
14928
16138
  } else if (cpuWindow !== void 0) {
14929
16139
  if (step.kind !== "wait" || step.waitTicks !== 1e3 || ticks < 1e3 || !fixedStep || bridge === void 0 || liveClock) {
14930
16140
  throw new Error("TN_PLAYTEST_CPU_WINDOW_FAILED: measurement requires a fixed-step 1000-tick WAIT");
@@ -14933,16 +16143,19 @@ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions,
14933
16143
  await cpuWindow(() => advanceFixedStep(page, bridge, 1e3, true));
14934
16144
  await waitFrames(page, 1);
14935
16145
  await samplePathPosition(bridge, pathEntity, pathPositions);
16146
+ await sampleSightLine(bridge, sightLine);
14936
16147
  } else if (ticks > 0 && fixedStep) {
14937
16148
  const sampleTicks = 10;
14938
16149
  for (let index = 0; index < ticks; index += sampleTicks) {
14939
16150
  const batch = Math.min(sampleTicks, ticks - index);
14940
16151
  await advanceFixedStep(page, bridge, batch);
14941
16152
  await samplePathPosition(bridge, pathEntity, pathPositions);
16153
+ await sampleSightLine(bridge, sightLine);
14942
16154
  }
14943
16155
  } else {
14944
16156
  await waitFrames(page, Math.max(frames, ticks, 1));
14945
16157
  await samplePathPosition(bridge, pathEntity, pathPositions);
16158
+ await sampleSightLine(bridge, sightLine);
14946
16159
  }
14947
16160
  const afterInput = bridge === void 0 || movementSampleRequest === void 0 ? void 0 : await bridge.sample(movementSampleRequest);
14948
16161
  let afterStep = afterInput;
@@ -15091,11 +16304,11 @@ async function executeAimAtStep(bridge, step, subject) {
15091
16304
  async function advanceFixedStep(page, bridge, ticks, render = false) {
15092
16305
  if (!Number.isInteger(ticks) || ticks <= 0)
15093
16306
  throw new Error("advance ticks must be a positive integer.");
15094
- for (let tick = 0; tick < ticks; tick += 1) {
16307
+ for (let tick = 0; tick < ticks; ) {
15095
16308
  for (let attempt = 0; ; attempt += 1) {
15096
16309
  try {
15097
- if (render) await bridge.advance(1, { render: true });
15098
- else await bridge.advance(1);
16310
+ const advanced = render ? await bridge.advance(1, { render: true }) : await bridge.advance(1);
16311
+ tick += typeof advanced === "number" && advanced > 1 ? advanced : 1;
15099
16312
  break;
15100
16313
  } catch (error) {
15101
16314
  if (!(error instanceof Error) || !error.message.includes(STOPPED_LOOP_ERROR) || attempt >= MAX_FIXED_STEP_STARTUP_RETRIES)
@@ -15103,7 +16316,7 @@ async function advanceFixedStep(page, bridge, ticks, render = false) {
15103
16316
  await waitFrames(page, 1);
15104
16317
  }
15105
16318
  }
15106
- if (render && tick + 1 < ticks) await waitFrames(page, 1);
16319
+ if (render && tick < ticks) await waitFrames(page, 1);
15107
16320
  }
15108
16321
  }
15109
16322
  function playtestStepDrivesMovement(step, hasHeldInput) {
@@ -15173,6 +16386,23 @@ async function setPointerButtons(page, inputState, buttons) {
15173
16386
  }
15174
16387
  inputState.pointerButtons = buttons;
15175
16388
  }
16389
+ async function sampleFootSlip(page, bridge, ticks, label, entity, feet) {
16390
+ const samples = [];
16391
+ for (let tick = 0; tick < ticks; tick += 1) {
16392
+ await advanceFixedStep(page, bridge, 1);
16393
+ const snapshot = await bridge.sample({ entities: [entity], include: ["entities"], sceneNodes: feet.map((name) => ({ limit: 1, name })) });
16394
+ samples.push({
16395
+ body: entityPosition(snapshot, entity) ?? null,
16396
+ feet: feet.map((_name, index) => snapshot.sceneNodes?.[index]?.nodes[0]?.position ?? null)
16397
+ });
16398
+ }
16399
+ return { entity, feet, label, samples };
16400
+ }
16401
+ async function sampleSightLine(bridge, sightLine) {
16402
+ if (bridge === void 0 || sightLine === void 0) return;
16403
+ const snapshot = await bridge.sample({ sightLine: { entity: sightLine.entity } });
16404
+ if (snapshot.sightLine !== void 0) sightLine.samples.push(snapshot.sightLine);
16405
+ }
15176
16406
  async function samplePathPosition(bridge, entity, positions2) {
15177
16407
  if (bridge === void 0 || entity === void 0) return;
15178
16408
  const snapshot = await bridge.sample({ entities: [entity] });
@@ -15184,18 +16414,49 @@ async function sampleAfterTransition(page, bridge, request) {
15184
16414
  await waitFrames(page, 1);
15185
16415
  return bridge.sample(request);
15186
16416
  }
15187
- async function waitFrames(page, frames) {
16417
+ async function waitFrames(page, frames, timeoutMs) {
15188
16418
  if (frames <= 0) return;
15189
- await page.evaluate((count) => new Promise((resolveFrame) => {
15190
- const schedule = globalThis.requestAnimationFrame;
15191
- let remaining = count;
15192
- const next = () => {
15193
- remaining -= 1;
15194
- if (remaining <= 0) resolveFrame();
15195
- else schedule(next);
15196
- };
15197
- schedule(next);
15198
- }), frames);
16419
+ let budgetMs;
16420
+ if (timeoutMs === void 0) {
16421
+ budgetMs = advanceTimeoutMs(frames);
16422
+ } else if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
16423
+ throw new PlaytestBridgeError(playtestDiagnostic(
16424
+ "TN_PLAYTEST_OPERATION_TIMEOUT",
16425
+ `waitFrames requested ${frames} frame(s) but the supplied remaining budget of ${String(timeoutMs)}ms is not a positive, finite value.`,
16426
+ "Check that the page is producing requestAnimationFrame callbacks; the wait cannot complete while rendering is stalled."
16427
+ ));
16428
+ } else {
16429
+ budgetMs = timeoutMs;
16430
+ }
16431
+ let timeout;
16432
+ try {
16433
+ await Promise.race([
16434
+ page.evaluate((count) => new Promise((resolveFrame) => {
16435
+ const schedule = globalThis.requestAnimationFrame;
16436
+ let remaining = count;
16437
+ const next = () => {
16438
+ remaining -= 1;
16439
+ if (remaining <= 0) resolveFrame();
16440
+ else schedule(next);
16441
+ };
16442
+ schedule(next);
16443
+ }), frames),
16444
+ new Promise((_resolve, reject) => {
16445
+ timeout = setTimeout(() => reject(new PlaytestBridgeError(playtestDiagnostic(
16446
+ "TN_PLAYTEST_OPERATION_TIMEOUT",
16447
+ `waitFrames requested ${frames} frame(s) exceeded ${budgetMs}ms.`,
16448
+ "Check that the page is producing requestAnimationFrame callbacks; the wait cannot complete while rendering is stalled."
16449
+ ))), budgetMs);
16450
+ })
16451
+ ]);
16452
+ } finally {
16453
+ if (timeout !== void 0) clearTimeout(timeout);
16454
+ }
16455
+ }
16456
+ var WARMUP_FIRST_FRAME_BUDGET_MS = 15e3;
16457
+ var WARMUP_FRAME_BUDGET_MS = 2e4;
16458
+ async function waitWarmupFrames(page, frames) {
16459
+ await waitFrames(page, frames, WARMUP_FIRST_FRAME_BUDGET_MS + frames * WARMUP_FRAME_BUDGET_MS);
15199
16460
  }
15200
16461
  function completionWindowLabel(scenario, target, live, raw = process.env.TN_PLAYTEST_COMPLETION_WINDOW_LABEL) {
15201
16462
  if (raw === void 0) return void 0;
@@ -15213,16 +16474,20 @@ async function measureCompletionWindow(label, mode, poll, release) {
15213
16474
  const fail2 = (reason) => {
15214
16475
  throw new Error(`TN_PLAYTEST_COMPLETION_WINDOW_FAILED: ${reason}`);
15215
16476
  };
15216
- const bounded = async (operation, timeoutMs = 5e3) => {
16477
+ const bounded = async (operation, timeoutMs2 = 5e3) => {
15217
16478
  let timer;
15218
16479
  try {
15219
16480
  return await Promise.race([operation(), new Promise((_resolve, reject) => {
15220
- timer = setTimeout(() => reject(new Error("TN_PLAYTEST_COMPLETION_WINDOW_FAILED: operation timeout")), timeoutMs);
16481
+ timer = setTimeout(() => reject(new Error("TN_PLAYTEST_COMPLETION_WINDOW_FAILED: operation timeout")), timeoutMs2);
15221
16482
  })]);
15222
16483
  } finally {
15223
16484
  clearTimeout(timer);
15224
16485
  }
15225
16486
  };
16487
+ const minimumFrames = Number(process.env.TN_PLAYTEST_COMPLETION_WINDOW_MIN_FRAMES ?? 101);
16488
+ const timeoutMs = Number(process.env.TN_PLAYTEST_COMPLETION_WINDOW_TIMEOUT_MS ?? 1e4);
16489
+ if (!Number.isSafeInteger(minimumFrames) || minimumFrames < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1)
16490
+ fail2("invalid completion frame count or timeout");
15226
16491
  const samples = [];
15227
16492
  let previous;
15228
16493
  let failure;
@@ -15238,7 +16503,7 @@ async function measureCompletionWindow(label, mode, poll, release) {
15238
16503
  const negotiated = await bounded(() => mode("wall-clock"));
15239
16504
  if (negotiated?.mode !== "wall-clock" || !Number.isSafeInteger(negotiated.tick) || !Number.isSafeInteger(negotiated.epoch) || negotiated.epoch < 0) fail2("clock negotiation unavailable");
15240
16505
  epoch = negotiated.epoch;
15241
- const deadline = Date.now() + 1e4;
16506
+ const deadline = Date.now() + timeoutMs;
15242
16507
  measurement: while (Date.now() <= deadline) {
15243
16508
  const value = await bounded(poll, Math.max(1, deadline - Date.now()));
15244
16509
  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"))
@@ -15267,6 +16532,7 @@ async function measureCompletionWindow(label, mode, poll, release) {
15267
16532
  samples.push({ sequence: sample.sequence, completedAtMs: sample.completedAtMs });
15268
16533
  if (sample.completedAtMs - samples[0].completedAtMs >= 5e3) {
15269
16534
  if (samples.length < 101) fail2("fewer than 100 complete intervals");
16535
+ if (samples.length < minimumFrames) continue;
15270
16536
  const intervals = samples.slice(1).map((entry, index) => entry.completedAtMs - samples[index].completedAtMs).sort((a, b) => a - b);
15271
16537
  result = {
15272
16538
  label,
@@ -15321,6 +16587,7 @@ init_shared();
15321
16587
  init_index();
15322
16588
  init_bridgeClient();
15323
16589
  init_browser();
16590
+ init_captureEnvironment();
15324
16591
 
15325
16592
  // src/runner/observationSampling.ts
15326
16593
  init_index();
@@ -15630,11 +16897,11 @@ function isJudgeMarkerRequestFailure(method, url, judgeMarkerUrl) {
15630
16897
  function addPreflightDiagnostic(report, diagnostic2) {
15631
16898
  return diagnostic2 === void 0 ? report : { ...report, diagnostics: [diagnostic2, ...report.diagnostics] };
15632
16899
  }
15633
- 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;
16900
+ 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;
15634
16901
  function isSoftwareDeviceLossEntry(entry) {
15635
16902
  return (entry.type === "error" || entry.type === "assert" || entry.type === "pageerror") && SOFTWARE_DEVICE_LOSS.test(entry.text);
15636
16903
  }
15637
- 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) {
16904
+ 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) {
15638
16905
  const movementSample = isAnonymousMovementScenario(scenario) ? observedMovementSample(movementSamples) : void 0;
15639
16906
  const entity = scenario.assert?.movement?.entity ?? scenario.subject ?? movementSample?.entity ?? "";
15640
16907
  const wholeRunObserved = isAnonymousMovementScenario(scenario) ? false : entityPosition(beforeSnapshot, entity) !== void 0 && entityPosition(afterSnapshot, entity) !== void 0;
@@ -15724,6 +16991,9 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
15724
16991
  // room does. Never merged with the first: a node that has since been removed is gone, and
15725
16992
  // reporting it from the earlier sample would assert against a scene that no longer exists.
15726
16993
  ...afterSnapshot?.sceneNodes === void 0 && beforeSnapshot?.sceneNodes === void 0 ? {} : { sceneNodes: afterSnapshot?.sceneNodes ?? beforeSnapshot?.sceneNodes },
16994
+ ...footSlip === void 0 ? {} : { footSlip },
16995
+ ...sightLine === void 0 ? {} : { sightLine },
16996
+ ...hudAudit === void 0 ? {} : { hudAudit },
15727
16997
  ...startup === void 0 ? {} : { startup },
15728
16998
  ...beforeSnapshot?.gameplay === void 0 && afterSnapshot?.gameplay === void 0 && labeledSamples.every(({ snapshot }) => snapshot.gameplay === void 0) ? {} : {
15729
16999
  runtimeObservations: {
@@ -15816,43 +17086,74 @@ init_index();
15816
17086
  init_bridgeClient();
15817
17087
  async function waitForStartupReady(options) {
15818
17088
  const { bridge, pump } = options;
15819
- if (!bridge.description.capabilities.includes("runtime.startup")) return void 0;
17089
+ if (!bridge.description.capabilities.includes("runtime.startup")) {
17090
+ await options.warmup?.();
17091
+ return void 0;
17092
+ }
15820
17093
  const now = options.now ?? (() => Date.now());
15821
17094
  const timeoutMs = options.timeoutMs ?? PLAYTEST_STARTUP_READY_TIMEOUT_MS;
15822
17095
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
15823
17096
  throw new Error(`TN_PLAYTEST_STARTUP_TIMEOUT_INVALID: ${String(options.timeoutMs)}`);
17097
+ await options.warmup?.();
15824
17098
  const deadline = now() + timeoutMs;
15825
17099
  const aborted = options.aborted ?? (() => false);
15826
17100
  if (aborted()) throw abortedDuringStartup();
15827
17101
  const hostAlive = options.hostAlive ?? (async () => void 0);
15828
- let observed = await pollStartup(bridge);
15829
- while (observed === BUSY || observed.phase !== "ready") {
15830
- if (aborted()) throw abortedDuringStartup();
15831
- if (observed === BUSY && await hostAlive() === false) throw hostExitedDuringStartup();
15832
- if (now() >= deadline) {
15833
- throw new PlaytestBridgeError(playtestDiagnostic(
15834
- "TN_PLAYTEST_STARTUP_NOT_READY",
15835
- `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.`,
15836
- "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."
15837
- ));
15838
- }
15839
- try {
15840
- await pump();
15841
- } catch (error) {
15842
- if (error instanceof PlaytestBridgeError && error.diagnostic.code === "TN_PLAYTEST_OPERATION_TIMEOUT") {
15843
- observed = BUSY;
15844
- continue;
17102
+ let observed = BUSY;
17103
+ const timeoutError = () => new PlaytestBridgeError(playtestDiagnostic(
17104
+ "TN_PLAYTEST_STARTUP_NOT_READY",
17105
+ `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.`,
17106
+ "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."
17107
+ ));
17108
+ let settled = false;
17109
+ let timeout;
17110
+ const expired = new Promise((_resolve, reject) => {
17111
+ timeout = setTimeout(() => {
17112
+ settled = true;
17113
+ reject(timeoutError());
17114
+ }, timeoutMs);
17115
+ });
17116
+ try {
17117
+ return await Promise.race([expired, (async () => {
17118
+ if (settled) throw timeoutError();
17119
+ if (aborted()) throw abortedDuringStartup();
17120
+ if (settled || now() >= deadline) throw timeoutError();
17121
+ observed = await pollStartup(bridge);
17122
+ while (observed === BUSY || observed.phase !== "ready" || observed.revealed === false) {
17123
+ if (settled) throw timeoutError();
17124
+ if (aborted()) throw abortedDuringStartup();
17125
+ if (observed === BUSY) {
17126
+ const alive = await hostAlive();
17127
+ if (settled) throw timeoutError();
17128
+ if (alive === false) throw hostExitedDuringStartup();
17129
+ }
17130
+ if (settled || now() >= deadline) {
17131
+ throw timeoutError();
17132
+ }
17133
+ try {
17134
+ await pump(deadline - now());
17135
+ } catch (error) {
17136
+ if (error instanceof PlaytestBridgeError && error.diagnostic.code === "TN_PLAYTEST_OPERATION_TIMEOUT") {
17137
+ observed = BUSY;
17138
+ continue;
17139
+ }
17140
+ throw error;
17141
+ }
17142
+ if (settled || now() >= deadline) throw timeoutError();
17143
+ observed = await pollStartup(bridge);
15845
17144
  }
15846
- throw error;
15847
- }
15848
- observed = await pollStartup(bridge);
17145
+ if (settled || now() >= deadline) throw timeoutError();
17146
+ return {
17147
+ // A declared software lane reaches `ready` on the bounded window rather than on sustained
17148
+ // in-budget frames, so it is labelled for what it is: not a smoothness measurement.
17149
+ rule: options.declaredSoftware === true ? "compile-settled" : "sustained-frames",
17150
+ startup: observed
17151
+ };
17152
+ })()]);
17153
+ } finally {
17154
+ settled = true;
17155
+ if (timeout !== void 0) clearTimeout(timeout);
15849
17156
  }
15850
- return {
15851
- // A declared software lane reaches `ready` on the bounded window rather than on sustained
15852
- // in-budget frames, so it is labelled for what it is: not a smoothness measurement.
15853
- rule: options.declaredSoftware === true ? "compile-settled" : "sustained-frames",
15854
- startup: observed
15855
- };
15856
17157
  }
15857
17158
  function abortedDuringStartup() {
15858
17159
  return new PlaytestBridgeError(playtestDiagnostic(
@@ -16252,6 +17553,23 @@ function createOwnedRunResourceRelease(display, lease) {
16252
17553
  // src/runner/server.ts
16253
17554
  init_index();
16254
17555
  init_bridgeClient();
17556
+
17557
+ // src/runner/network.ts
17558
+ function networkBytesPerSecond(downloadKbps) {
17559
+ return downloadKbps * 1e3 / 8;
17560
+ }
17561
+ function networkEmulation(profile) {
17562
+ const bytesPerSecond = networkBytesPerSecond(profile.downloadKbps);
17563
+ return {
17564
+ connectionType: "cellular3g",
17565
+ downloadThroughput: bytesPerSecond,
17566
+ latency: profile.latencyMs,
17567
+ offline: false,
17568
+ uploadThroughput: bytesPerSecond
17569
+ };
17570
+ }
17571
+
17572
+ // src/runner/server.ts
16255
17573
  init_shared();
16256
17574
  function startManagedServer(config, dynamicPort) {
16257
17575
  const port = dynamicPort ?? managedPort(config);
@@ -16375,7 +17693,17 @@ function pageLifecycleDiagnostic(error, lifecycle, url) {
16375
17693
  "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."
16376
17694
  );
16377
17695
  }
17696
+ var throttledPages = /* @__PURE__ */ new WeakMap();
17697
+ async function applyNetworkProfile(page, scenario) {
17698
+ const profile = scenario.network;
17699
+ if (profile === void 0) return;
17700
+ const session = await page.context().newCDPSession(page);
17701
+ await session.send("Network.enable");
17702
+ await session.send("Network.emulateNetworkConditions", networkEmulation(profile));
17703
+ throttledPages.set(page, session);
17704
+ }
16378
17705
  async function openPageAndConnectBridge(page, config, scenario) {
17706
+ await applyNetworkProfile(page, scenario);
16379
17707
  const attempts = 3;
16380
17708
  let lastError;
16381
17709
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
@@ -16468,8 +17796,120 @@ init_shared();
16468
17796
  init_shared();
16469
17797
  init_index();
16470
17798
  init_capture();
17799
+
17800
+ // src/runner/capture-retry.ts
17801
+ init_capture();
17802
+ async function retakeWhileBlank(retake, grace, boundMs, now = Date.now) {
17803
+ const deadline = now() + boundMs;
17804
+ for (; ; ) {
17805
+ await grace();
17806
+ try {
17807
+ return await retake();
17808
+ } catch (error) {
17809
+ if (!(error instanceof CaptureGuardError) || now() >= deadline) throw error;
17810
+ }
17811
+ }
17812
+ }
17813
+
17814
+ // src/runner/runner.ts
16471
17815
  init_bridgeClient();
17816
+ var CHANNEL_TOLERANCE = 48;
17817
+ var DIFFERING_SHARE = 0.25;
17818
+ var UI_OVER_COVER_SHARE = 5e-3;
17819
+ var FIRST_PAINT_SLACK_MS = 8;
17820
+ var HANDOFF_FRAMES = 30;
17821
+ function meanColour(frame) {
17822
+ const sum = [0, 0, 0];
17823
+ const pixels = frame.width * frame.height;
17824
+ for (let i = 0; i < pixels; i += 1) {
17825
+ sum[0] += frame.data[i * 4] ?? 0;
17826
+ sum[1] += frame.data[i * 4 + 1] ?? 0;
17827
+ sum[2] += frame.data[i * 4 + 2] ?? 0;
17828
+ }
17829
+ return sum.map((value) => Math.round(value / Math.max(1, pixels)));
17830
+ }
17831
+ function differingShare(frame, reference) {
17832
+ if (frame.width !== reference.width || frame.height !== reference.height) return 1;
17833
+ const pixels = frame.width * frame.height;
17834
+ let moved = 0;
17835
+ for (let i = 0; i < pixels; i += 1) {
17836
+ for (let channel = 0; channel < 3; channel += 1) {
17837
+ if (Math.abs((frame.data[i * 4 + channel] ?? 0) - (reference.data[i * 4 + channel] ?? 0)) > CHANNEL_TOLERANCE) {
17838
+ moved += 1;
17839
+ break;
17840
+ }
17841
+ }
17842
+ }
17843
+ return moved / Math.max(1, pixels);
17844
+ }
17845
+ function uiShare(frame, cover, world) {
17846
+ if (frame.width !== cover.width || frame.width !== world.width || frame.height !== cover.height || frame.height !== world.height) return 0;
17847
+ const pixels = frame.width * frame.height;
17848
+ let ui = 0;
17849
+ for (let i = 0; i < pixels; i += 1) {
17850
+ let offCover = false;
17851
+ let onWorld = true;
17852
+ for (let channel = 0; channel < 3; channel += 1) {
17853
+ const value = frame.data[i * 4 + channel] ?? 0;
17854
+ if (Math.abs(value - (cover.data[i * 4 + channel] ?? 0)) > CHANNEL_TOLERANCE) offCover = true;
17855
+ if (Math.abs(value - (world.data[i * 4 + channel] ?? 0)) > CHANNEL_TOLERANCE) onWorld = false;
17856
+ }
17857
+ if (offCover && onWorld) ui += 1;
17858
+ }
17859
+ return ui / Math.max(1, pixels);
17860
+ }
17861
+ function compareStartupFrames(frames, readyMs = Number.POSITIVE_INFINITY, firstPaintMs = 0) {
17862
+ const startup = frames.filter((frame) => frame.ms >= firstPaintMs - FIRST_PAINT_SLACK_MS && frame.ms < readyMs);
17863
+ const handOff = frames.filter((frame) => frame.ms >= readyMs);
17864
+ const reference = startup.at(-1);
17865
+ if (reference === void 0) return { differing: [], frames: 0, reference: [0, 0, 0], uiOverCover: [] };
17866
+ const differing = [];
17867
+ for (const frame of startup) {
17868
+ const share = differingShare(frame, reference);
17869
+ if (share > DIFFERING_SHARE) differing.push({ mean: meanColour(frame), ms: Math.round(frame.ms), share: Number(share.toFixed(3)) });
17870
+ }
17871
+ const observation = { differing, frames: startup.length, reference: meanColour(reference), uiOverCover: [] };
17872
+ if (!Number.isFinite(readyMs)) return observation;
17873
+ const worldIndex = handOff.findIndex((frame) => differingShare(frame, reference) > DIFFERING_SHARE);
17874
+ const world = handOff[worldIndex];
17875
+ if (world === void 0) return observation;
17876
+ observation.worldMs = Math.round(world.ms);
17877
+ for (const frame of handOff.slice(0, worldIndex)) {
17878
+ const share = uiShare(frame, reference, world);
17879
+ if (share > UI_OVER_COVER_SHARE) observation.uiOverCover.push({ ms: Math.round(frame.ms), share: Number(share.toFixed(4)) });
17880
+ }
17881
+ return observation;
17882
+ }
17883
+ async function recordStartupCover(page) {
17884
+ const cdp = await page.context().newCDPSession(page);
17885
+ const frames = [];
17886
+ cdp.on("Page.screencastFrame", ({ data, metadata, sessionId }) => {
17887
+ frames.push({ epochMs: (metadata.timestamp ?? Date.now() / 1e3) * 1e3, png: Buffer.from(data, "base64") });
17888
+ void cdp.send("Page.screencastFrameAck", { sessionId }).catch(() => void 0);
17889
+ });
17890
+ await cdp.send("Page.startScreencast", { everyNthFrame: 1, format: "png", maxHeight: 72, maxWidth: 128 });
17891
+ return {
17892
+ async finish(readyMs) {
17893
+ await waitFrames(page, HANDOFF_FRAMES).catch(() => void 0);
17894
+ await cdp.send("Page.stopScreencast").catch(() => void 0);
17895
+ await cdp.detach().catch(() => void 0);
17896
+ const [origin, firstPaint] = await page.evaluate(() => [
17897
+ performance.timeOrigin,
17898
+ performance.getEntriesByName("first-paint")[0]?.startTime ?? 0
17899
+ ]);
17900
+ const startup = frames.filter(({ epochMs }) => epochMs >= origin).map(({ epochMs, png }) => {
17901
+ const image = PNG.sync.read(png);
17902
+ return { data: image.data, height: image.height, ms: epochMs - origin, width: image.width };
17903
+ });
17904
+ return compareStartupFrames(startup, readyMs, firstPaint);
17905
+ }
17906
+ };
17907
+ }
17908
+
17909
+ // src/runner/runner.ts
16472
17910
  init_browser();
17911
+ init_frame_cost();
17912
+ init_captureEnvironment();
16473
17913
  var REMOTE_BROWSER_SESSIONS = /* @__PURE__ */ new WeakMap();
16474
17914
  function remoteBrowserFor(config) {
16475
17915
  return REMOTE_BROWSER_SESSIONS.get(config);
@@ -16645,6 +18085,14 @@ async function writeObservationArtifacts(artifactDirectory, requested, observati
16645
18085
  }
16646
18086
  return written;
16647
18087
  }
18088
+ var WorkerGameRelaunch = class extends Error {
18089
+ };
18090
+ async function runsGameInWorker(page) {
18091
+ for (const worker of page.workers()) {
18092
+ if (await worker.evaluate("typeof globalThis.__tnGamePlatform").catch(() => void 0) === "object") return true;
18093
+ }
18094
+ return false;
18095
+ }
16648
18096
  async function runStandalonePlaytest(config, options = {}) {
16649
18097
  return runStandalonePlaytestInternal(config, {
16650
18098
  ...options,
@@ -16652,12 +18100,25 @@ async function runStandalonePlaytest(config, options = {}) {
16652
18100
  });
16653
18101
  }
16654
18102
  async function runStandalonePlaytestInternal(config, options = {}) {
18103
+ try {
18104
+ return await runStandalonePlaytestOnce(config, options);
18105
+ } catch (error) {
18106
+ if (!(error instanceof WorkerGameRelaunch)) throw error;
18107
+ return runStandalonePlaytestOnce(config, { ...options, gameThread: "worker" });
18108
+ }
18109
+ }
18110
+ async function runStandalonePlaytestOnce(config, options) {
16655
18111
  const usesFreePort = config.server !== void 0 && config.port === 0;
16656
- const activeConfig = usesFreePort ? await resolveManagedServerConfig(config) : config;
18112
+ const resolvedConfig = usesFreePort ? await resolveManagedServerConfig(config) : config;
16657
18113
  const scenario = withPerformanceBudget(
16658
- await loadPlaytestScenario(activeConfig.projectPath, activeConfig.scenarioPath),
16659
- activeConfig.performanceBudget
18114
+ await loadPlaytestScenario(resolvedConfig.projectPath, resolvedConfig.scenarioPath),
18115
+ resolvedConfig.performanceBudget
16660
18116
  );
18117
+ let activeConfig = withScenarioClock(resolvedConfig, scenario);
18118
+ const performance2 = scenario.assert?.performance;
18119
+ if ((activeConfig.target ?? "browser") === "browser" && activeConfig.liveClock === void 0 && (performance2?.maxFrameMsP95 !== void 0 || performance2?.minFps !== void 0)) {
18120
+ activeConfig = { ...activeConfig, liveClock: true };
18121
+ }
16661
18122
  const cpuLabels = cpuWindowLabels(scenario, "browser", activeConfig.liveClock === true);
16662
18123
  if (cpuLabels.length > 0 && options.remoteBrowser !== void 0) {
16663
18124
  throw new Error("TN_PLAYTEST_CPU_WINDOW_FAILED: remote browser has no local owned process tree");
@@ -16667,11 +18128,12 @@ async function runStandalonePlaytestInternal(config, options = {}) {
16667
18128
  let completionWindow;
16668
18129
  const completionDisplay = completionLabel === void 0 ? void 0 : completionWindowEnvironment("browser", activeConfig.headless);
16669
18130
  if (completionLabel !== void 0 && options.remoteBrowser !== void 0) throw new Error("TN_PLAYTEST_COMPLETION_WINDOW_FAILED: requires a fresh local browser process");
16670
- const browserConfig = scenario.assert?.performance === void 0 && completionLabel === void 0 ? activeConfig : {
18131
+ const measurementArgs = measurementBrowserArgs(scenario.assert?.performance !== void 0, completionLabel !== void 0, frameDisplay(), options.gameThread);
18132
+ const browserConfig = measurementArgs.length === 0 ? activeConfig : {
16671
18133
  ...activeConfig,
16672
18134
  browserArgs: [
16673
18135
  ...activeConfig.browserArgs ?? [],
16674
- ...PERFORMANCE_BROWSER_ARGS.filter((argument) => !activeConfig.browserArgs?.includes(argument))
18136
+ ...measurementArgs.filter((argument) => !activeConfig.browserArgs?.includes(argument))
16675
18137
  ]
16676
18138
  };
16677
18139
  await mkdir(activeConfig.artifactDirectory, { recursive: true });
@@ -16821,6 +18283,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
16821
18283
  await page.addInitScript((liveClock) => {
16822
18284
  globalThis.__THREENATIVE_PLAYTEST_RUNNER_EXPECTED__ = true;
16823
18285
  if (liveClock) globalThis.__THREENATIVE_PLAYTEST_CLOCK__ = "wall-clock";
18286
+ globalThis.__THREENATIVE_ENGINE_COST__ = true;
16824
18287
  window.addEventListener("unhandledrejection", (event) => {
16825
18288
  const reason = event.reason instanceof Error ? event.reason.stack || event.reason.message : String(event.reason);
16826
18289
  console.error(`__THREENATIVE_PLAYTEST_UNHANDLED_REJECTION__:${reason}`);
@@ -16857,7 +18320,9 @@ async function runStandalonePlaytestInternal(config, options = {}) {
16857
18320
  pageLifecycle.closed = true;
16858
18321
  });
16859
18322
  const activePage = page;
18323
+ const coverRecorder = scenario.assert?.startup?.steadyCover === true ? await recordStartupCover(page) : void 0;
16860
18324
  const bridge = await openRunnerPage(page, browserConfig, scenario, options.remoteBrowser);
18325
+ if (options.gameThread === void 0 && measurementArgs.includes("--disable-frame-rate-limit") && await runsGameInWorker(page)) throw new WorkerGameRelaunch();
16861
18326
  pageLifecycle.settled = true;
16862
18327
  const setupApplication2 = bridge?.setupApplication;
16863
18328
  if (scenario.setup !== void 0) {
@@ -16869,13 +18334,16 @@ async function runStandalonePlaytestInternal(config, options = {}) {
16869
18334
  ));
16870
18335
  }
16871
18336
  }
16872
- await waitFrames(page, scenario.warmupFrames);
18337
+ if (bridge === void 0 || scenario.awaitStartup === false) await waitFrames(page, scenario.warmupFrames);
16873
18338
  const startupOutcome = bridge === void 0 || scenario.awaitStartup === false ? void 0 : await waitForStartupReady({
16874
18339
  aborted: () => tearingDown,
16875
18340
  bridge,
16876
18341
  declaredSoftware: activeConfig.allowSoftwareAdapter === true,
16877
- pump: () => waitFrames(activePage, 1)
18342
+ warmup: () => waitWarmupFrames(activePage, scenario.warmupFrames),
18343
+ pump: (remainingMs) => waitFrames(activePage, 1, remainingMs)
16878
18344
  });
18345
+ const readyMs = startupOutcome?.startup.timeline?.readyMs;
18346
+ const startupCover = coverRecorder === void 0 || readyMs === void 0 ? void 0 : await coverRecorder.finish(readyMs);
16879
18347
  await alignScenarioStartTick(bridge, scenario.startTick, activeConfig.liveClock === true);
16880
18348
  const runtimeReady = await page.evaluate(
16881
18349
  () => document.readyState !== "loading" && document.querySelector("canvas") !== null
@@ -16957,17 +18425,22 @@ async function runStandalonePlaytestInternal(config, options = {}) {
16957
18425
  return { ...elementRegions === void 0 ? {} : { elementRegions }, image: png };
16958
18426
  } catch (error) {
16959
18427
  if (!(error instanceof CaptureGuardError)) throw error;
16960
- await presentationGrace();
16961
- if (captureElementBounds) elementRegions = await sampleVisualElementBounds(activePage, visualAssertions);
16962
18428
  try {
16963
- png = await activePage.screenshot(options2);
16964
- } catch {
16965
- }
16966
- try {
16967
- const stats = assertCaptureNotBlank(png, label);
16968
- if (stats.tone !== void 0) tone.push({ code: "TN_TONE", label, ...atStep === void 0 ? {} : { atStep }, ...stats.tone });
16969
- tone.push(...collectRegionalTone(png, scenario.assert?.tone ?? [], label, atStep));
16970
- return { ...elementRegions === void 0 ? {} : { elementRegions }, image: png };
18429
+ return await retakeWhileBlank(
18430
+ async () => {
18431
+ if (captureElementBounds) elementRegions = await sampleVisualElementBounds(activePage, visualAssertions);
18432
+ try {
18433
+ png = await activePage.screenshot(options2);
18434
+ } catch {
18435
+ }
18436
+ const stats = assertCaptureNotBlank(png, label);
18437
+ if (stats.tone !== void 0) tone.push({ code: "TN_TONE", label, ...atStep === void 0 ? {} : { atStep }, ...stats.tone });
18438
+ tone.push(...collectRegionalTone(png, scenario.assert?.tone ?? [], label, atStep));
18439
+ return { ...elementRegions === void 0 ? {} : { elementRegions }, image: png };
18440
+ },
18441
+ presentationGrace,
18442
+ PRESENTATION_BOUND_MS
18443
+ );
16971
18444
  } catch (error2) {
16972
18445
  if (!(error2 instanceof CaptureGuardError)) throw error2;
16973
18446
  captureFailure ??= { code: error2.code, label: error2.label, reason: error2.reason };
@@ -17000,15 +18473,20 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17000
18473
  return { image: png };
17001
18474
  } catch (error) {
17002
18475
  if (!(error instanceof CaptureGuardError)) throw error;
17003
- await presentationGrace();
17004
18476
  try {
17005
- const retry = await captureVisualSurface(activePage, artifactPath);
17006
- if (retry !== void 0) {
17007
- const stats = assertCaptureNotBlank(retry, label);
17008
- if (stats.tone !== void 0) tone.push({ code: "TN_TONE", label, ...atStep === void 0 ? {} : { atStep }, ...stats.tone });
17009
- tone.push(...collectRegionalTone(retry, scenario.assert?.tone ?? [], label, atStep));
17010
- return { image: retry };
17011
- }
18477
+ const retry = await retakeWhileBlank(
18478
+ async () => {
18479
+ const shot = await captureVisualSurface(activePage, artifactPath);
18480
+ if (shot === void 0) return void 0;
18481
+ const stats = assertCaptureNotBlank(shot, label);
18482
+ if (stats.tone !== void 0) tone.push({ code: "TN_TONE", label, ...atStep === void 0 ? {} : { atStep }, ...stats.tone });
18483
+ tone.push(...collectRegionalTone(shot, scenario.assert?.tone ?? [], label, atStep));
18484
+ return shot;
18485
+ },
18486
+ presentationGrace,
18487
+ PRESENTATION_BOUND_MS
18488
+ );
18489
+ if (retry !== void 0) return { image: retry };
17012
18490
  } catch (error2) {
17013
18491
  if (!(error2 instanceof CaptureGuardError)) throw error2;
17014
18492
  captureFailure ??= { code: error2.code, label: error2.label, reason: error2.reason };
@@ -17054,6 +18532,16 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17054
18532
  if (activeConfig.cpuProfilePath !== void 0) {
17055
18533
  cpuProfile = await startBrowserCpuProfile(activePage, activeConfig.cpuProfilePath);
17056
18534
  }
18535
+ const footSlip = [];
18536
+ const footSlipAt = (label) => label === void 0 ? void 0 : scenario.assert?.footSlip?.find(({ atStep }) => atStep === label);
18537
+ const sightLineAssertion = scenario.assert?.sightLine;
18538
+ const sightLineEntity = sightLineAssertion?.entity ?? scenario.subject;
18539
+ const sightLine = sightLineAssertion === void 0 || sightLineEntity === void 0 ? void 0 : { entity: sightLineEntity, samples: [] };
18540
+ const drawnTicks = scenario.assert?.engineCost === void 0 || bridge === void 0 || activeConfig.liveClock === true || !bridge.description.capabilities.includes("runtime.fixedStep") ? void 0 : async (ticks) => {
18541
+ await advanceFixedStep(activePage, bridge, ticks, true);
18542
+ await samplePathPosition(bridge, pathEntity, pathPositions);
18543
+ await sampleSightLine(bridge, sightLine);
18544
+ };
17057
18545
  for (const [index, step] of scenario.steps.entries()) {
17058
18546
  const framebufferAssertion = scenario.assert?.framebufferCoverage;
17059
18547
  if (framebufferAssertion !== void 0 && step.label === framebufferAssertion.window.startStep) {
@@ -17106,7 +18594,17 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17106
18594
  }
17107
18595
  );
17108
18596
  completionWindow.setupSnapshot = setupSnapshot;
17109
- } : void 0
18597
+ } : footSlipAt(step.label) === void 0 ? drawnTicks : async (ticks) => {
18598
+ const assertion = footSlipAt(step.label);
18599
+ const entity = assertion.entity ?? scenario.subject;
18600
+ if (bridge === void 0 || entity === void 0 || activeConfig.liveClock === true || !bridge.description.capabilities.includes("runtime.fixedStep")) {
18601
+ throw new Error("TN_PLAYTEST_FOOT_SLIP_UNOBSERVED: footSlip needs a fixed-step bridge and a subject entity");
18602
+ }
18603
+ footSlip.push(await sampleFootSlip(activePage, bridge, ticks, step.label, entity, assertion.feet));
18604
+ await samplePathPosition(bridge, pathEntity, pathPositions);
18605
+ await sampleSightLine(bridge, sightLine);
18606
+ },
18607
+ sightLine
17110
18608
  );
17111
18609
  if (movementBaselineSnapshot === void 0 && movementNeedsBaseline && movementEntity !== void 0) {
17112
18610
  const candidate = stepSamples.afterStep ?? stepSamples.afterInput;
@@ -17150,6 +18648,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17150
18648
  if (position !== void 0) pathPositions.push(position);
17151
18649
  }
17152
18650
  const afterHud = await sampleHud(page, hudAssertions);
18651
+ const hudAudit = scenario.assert?.hudAudit === void 0 ? void 0 : await sampleHudAudit(page);
17153
18652
  const afterScreenshot = scenario.artifacts?.screenshots !== false && artifactFrames || wantsVisual || wantsFinalTone ? wantsVisual || wantsFinalTone ? await captureVisualPage(
17154
18653
  "after.png",
17155
18654
  scenario.artifacts?.screenshots === false ? void 0 : join(activeConfig.artifactDirectory, "after.png")
@@ -17184,9 +18683,16 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17184
18683
  setupApplication2,
17185
18684
  deviceMetrics,
17186
18685
  movementBaselineSnapshot,
17187
- startupOutcome === void 0 ? void 0 : { ...startupOutcome.startup, rule: startupOutcome.rule },
18686
+ startupOutcome === void 0 ? void 0 : {
18687
+ ...startupOutcome.startup,
18688
+ rule: startupOutcome.rule,
18689
+ ...startupCover === void 0 ? {} : { cover: startupCover }
18690
+ },
17188
18691
  void 0,
17189
- tone
18692
+ tone,
18693
+ footSlip.length === 0 ? void 0 : footSlip,
18694
+ sightLine === void 0 || sightLine.samples.length === 0 ? void 0 : sightLine,
18695
+ hudAudit
17190
18696
  );
17191
18697
  if (cpuWindows.length !== cpuLabels.length) throw new Error("TN_PLAYTEST_CPU_WINDOW_FAILED: missing requested CPU window");
17192
18698
  if (completionWindow !== void 0) {
@@ -17197,6 +18703,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17197
18703
  browserArgs: resolveBrowserArguments(browserConfig.browserArgs)
17198
18704
  };
17199
18705
  }
18706
+ if (options.gameThread !== void 0) report.gameThread = options.gameThread;
17200
18707
  report.acquisition = { requestUrls: [...requestUrls], ...cpuLabels.length === 0 ? {} : { cpuWindows }, ...completionWindow === void 0 ? {} : { completionWindow } };
17201
18708
  await writeObservationArtifacts(activeConfig.artifactDirectory, scenario.artifacts, {
17202
18709
  console: consoleEntries,
@@ -17209,6 +18716,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
17209
18716
  else await page.close();
17210
18717
  return addPreflightDiagnostic(report, preflight);
17211
18718
  } catch (error) {
18719
+ if (error instanceof WorkerGameRelaunch) throw error;
17212
18720
  try {
17213
18721
  if (!observationArtifactsWritten) await writeObservationArtifacts(activeConfig.artifactDirectory, scenario.artifacts, {
17214
18722
  console: consoleEntries,
@@ -17637,7 +19145,9 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
17637
19145
  // this the wait reads that as a slow loading gate and burns its whole deadline; with it
17638
19146
  // the report names the exit and carries the console tail that says why.
17639
19147
  hostAlive: () => target.driver.isAlive().catch(() => void 0),
17640
- pump: () => attached.advance(1)
19148
+ pump: async () => {
19149
+ await attached.advance(1);
19150
+ }
17641
19151
  });
17642
19152
  await throwIfAborted(target);
17643
19153
  for (let frame = 0; frame < scenario.warmupFrames; frame += 1) {
@@ -17673,7 +19183,7 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
17673
19183
  const before = await bridge.sample(sampleRequest);
17674
19184
  if (completionLabel !== void 0 && before.clock.mode !== "fixed-step") throw new Error("TN_PLAYTEST_COMPLETION_WINDOW_FAILED: prefix requires fixed-step clock");
17675
19185
  if (scenario.artifacts?.screenshots === "before-after" && config.captureArtifactScreenshots !== false) {
17676
- await captureDeviceScreenshot(target, join(config.artifactDirectory, "before.png"), tone, "before.png", void 0, renderOnly);
19186
+ await captureDeviceScreenshot(target, join(config.artifactDirectory, "before.png"), tone, "before.png", void 0, renderOnly, scenario.assert?.tone);
17677
19187
  }
17678
19188
  const pathEntity = scenario.assert?.movement?.pathLength === void 0 ? void 0 : scenario.assert.movement.entity ?? scenario.subject;
17679
19189
  const pathPositions = [];
@@ -17726,12 +19236,14 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
17726
19236
  throw new PlaytestBridgeError(playtestDiagnostic(
17727
19237
  "TN_PLAYTEST_OBSERVATION_UNAVAILABLE",
17728
19238
  `Resource wait for '${wait.id}.${wait.path}' has no timeout.`,
17729
- "Validate the scenario with timeoutMs as a positive integer no greater than 120000."
19239
+ "Validate the scenario with timeoutMs as a positive integer no greater than 300000."
17730
19240
  ));
17731
19241
  }
17732
19242
  const attachedBridge = bridge;
17733
19243
  afterInput = await waitForResource({
17734
- advance: () => attachedBridge.advance(1),
19244
+ advance: async () => {
19245
+ await attachedBridge.advance(1);
19246
+ },
17735
19247
  id: wait.id,
17736
19248
  path: wait.path,
17737
19249
  predicate: wait,
@@ -17832,7 +19344,9 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
17832
19344
  const pid = target.driver.processId;
17833
19345
  if (pid === void 0) throw new Error("TN_PLAYTEST_CPU_WINDOW_FAILED: native child PID unavailable");
17834
19346
  return { rootPid: pid, pid, tid: pid };
17835
- }, measuredBridge, () => measuredBridge.advance(1e3)));
19347
+ }, measuredBridge, async () => {
19348
+ await measuredBridge.advance(1e3);
19349
+ }));
17836
19350
  } finally {
17837
19351
  if (holdRender) await transport.call("_holdAutomaticRender", false);
17838
19352
  }
@@ -17859,7 +19373,7 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
17859
19373
  const wantsStepTone = step.label !== void 0 && scenario.assert?.tone?.some(({ atStep }) => atStep === step.label) === true;
17860
19374
  if (step.screenshot !== void 0 || wantsStepTone) {
17861
19375
  const label = step.screenshot === void 0 ? `tone-${index}.png` : `${safePart(step.screenshot)}.png`;
17862
- await captureDeviceScreenshot(target, join(config.artifactDirectory, label), tone, label, step.label, renderOnly);
19376
+ await captureDeviceScreenshot(target, join(config.artifactDirectory, label), tone, label, step.label, renderOnly, scenario.assert?.tone);
17863
19377
  }
17864
19378
  if (step.release && pressed !== void 0) {
17865
19379
  const released = typeof pressed === "string" ? [pressed] : [...pressed];
@@ -17908,7 +19422,7 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
17908
19422
  metrics?.stop();
17909
19423
  await metrics?.sampleNow("after").catch(() => void 0);
17910
19424
  if (scenario.artifacts?.screenshots !== false || scenario.assert?.tone?.some(({ atStep }) => atStep === void 0) === true) {
17911
- await captureDeviceScreenshot(target, join(config.artifactDirectory, "after.png"), tone, "after.png", void 0, renderOnly);
19425
+ await captureDeviceScreenshot(target, join(config.artifactDirectory, "after.png"), tone, "after.png", void 0, renderOnly, scenario.assert?.tone);
17912
19426
  }
17913
19427
  if (!await target.driver.isAlive()) {
17914
19428
  return failureReport(config, scenario, playtestDiagnostic(
@@ -18042,11 +19556,12 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
18042
19556
  if (cleanupErrors.length > 0) cleanupState.error = cleanupFailure(cleanupErrors);
18043
19557
  }
18044
19558
  }
18045
- async function captureDeviceScreenshot(target, path2, tone, label, atStep, renderOnly) {
19559
+ async function captureDeviceScreenshot(target, path2, tone, label, atStep, renderOnly, toneAssertions = []) {
18046
19560
  await target.driver.screenshot(path2, renderOnly);
18047
19561
  const png = await readFile(path2);
18048
19562
  const stats = target.name === "desktop" ? assertDesktopCaptureNotBlank(png, path2) : assertCaptureNotBlank(png, path2);
18049
19563
  if (stats.tone !== void 0) tone.push({ code: "TN_TONE", label, ...atStep === void 0 ? {} : { atStep }, ...stats.tone });
19564
+ tone.push(...collectRegionalTone(png, toneAssertions, label, atStep));
18050
19565
  }
18051
19566
  function deviceMetricsRecorder(target) {
18052
19567
  if (target.name !== "android") return void 0;
@@ -18632,6 +20147,7 @@ function deviceFailure(serial, error) {
18632
20147
  const detail = error instanceof Error ? error.message : String(error);
18633
20148
  return new Error(`TN_PLAYTEST_DEVICE_FAILED: Android Chrome device '${serial}' failed: ${detail}`);
18634
20149
  }
20150
+ init_captureEnvironment();
18635
20151
 
18636
20152
  // src/runner/desktop.ts
18637
20153
  init_capture();
@@ -18656,21 +20172,15 @@ var LocalDeviceMailbox = class {
18656
20172
  }
18657
20173
  }
18658
20174
  async remove(path2) {
18659
- for (let retry = 0; ; retry += 1) {
18660
- try {
18661
- await rm(path2, { force: true });
18662
- return;
18663
- } catch (error) {
18664
- if (retry >= 10 || !isTransientMailboxLock(error)) throw error;
18665
- await delay3(20);
18666
- }
18667
- }
20175
+ await retryMailboxLock(() => rm(path2, { force: true }));
18668
20176
  }
18669
20177
  async write(path2, contents) {
18670
20178
  await mkdir(dirname(path2), { recursive: true });
18671
20179
  const temporary = `${path2}.tmp`;
18672
- await writeFile(temporary, contents, "utf8");
18673
- await rename(temporary, path2);
20180
+ await retryMailboxLock(async () => {
20181
+ await writeFile(temporary, contents, "utf8");
20182
+ await rename(temporary, path2);
20183
+ });
18674
20184
  }
18675
20185
  };
18676
20186
  var DesktopPlaytestDriver = class {
@@ -18715,6 +20225,10 @@ var DesktopPlaytestDriver = class {
18715
20225
  ...process.env,
18716
20226
  ...process.platform === "linux" && process.env.SDL_VIDEODRIVER === void 0 ? { SDL_VIDEODRIVER: "x11" } : {},
18717
20227
  MYSTRAL_HEADLESS: "1",
20228
+ // A debug launch, because the run's own warning evaluator reads `TN_SCENE_WARNING` and the
20229
+ // engine prints it only where a developer asked for the dev surfaces. The shell's value must
20230
+ // not decide it: an inherited `DEV_MODE=0` would leave the check blind rather than red.
20231
+ DEV_MODE: "1",
18718
20232
  ...this.options.env,
18719
20233
  TN_PLAYTEST_MAILBOX_ROOT: this.mailboxRoot,
18720
20234
  // The host reads the request before it evaluates the game entry, the way the browser runner
@@ -18912,6 +20426,17 @@ function isProcessExited(child) {
18912
20426
  function delay3(milliseconds) {
18913
20427
  return new Promise((resolve13) => setTimeout(resolve13, milliseconds));
18914
20428
  }
20429
+ async function retryMailboxLock(operation) {
20430
+ for (let retry = 0; ; retry += 1) {
20431
+ try {
20432
+ await operation();
20433
+ return;
20434
+ } catch (error) {
20435
+ if (retry >= 100 || !isTransientMailboxLock(error)) throw error;
20436
+ await delay3(20);
20437
+ }
20438
+ }
20439
+ }
18915
20440
  function isTransientMailboxLock(error) {
18916
20441
  const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
18917
20442
  return code === "EPERM" || code === "EBUSY";
@@ -19284,7 +20809,9 @@ var XcrunIosDriver = class {
19284
20809
  async prepareSimulator(endpoint, mailboxRoot) {
19285
20810
  const device = this.device();
19286
20811
  await this.run(["simctl", "bootstatus", device, "-b"]);
20812
+ const previous = await this.registeredBundlePath(device);
19287
20813
  await this.run(["simctl", "install", device, this.options.appPath]);
20814
+ await this.awaitInstalledBundle(device, previous);
19288
20815
  const container = (await this.run([
19289
20816
  "simctl",
19290
20817
  "get_app_container",
@@ -19337,6 +20864,28 @@ var XcrunIosDriver = class {
19337
20864
  ]);
19338
20865
  this.pid = parseLaunchedPid(output);
19339
20866
  }
20867
+ // `simctl install` returns while the simulator still lists the replaced bundle, which it has
20868
+ // moved to `containermanagerd/Dead/`. A launch in that window starts the previous build: a CI
20869
+ // physics scenario ran the input smoke game from a Dead container and failed every assertion.
20870
+ // Every reinstall gets a new bundle container, so launch only once the listed path is new.
20871
+ async awaitInstalledBundle(device, previous) {
20872
+ const deadline = Date.now() + kIosInstallRegistrationMs;
20873
+ for (; ; ) {
20874
+ const listed = await this.run(["simctl", "listapps", device]);
20875
+ const path2 = parseListedBundlePath(listed, this.options.bundleId);
20876
+ if (path2 !== void 0 && path2 !== previous && !path2.includes("/Dead/")) return;
20877
+ if (Date.now() >= deadline) {
20878
+ const at = listed.indexOf(`"${this.options.bundleId}"`);
20879
+ throw new Error(
20880
+ `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)
20881
+ );
20882
+ }
20883
+ await new Promise((resolve13) => setTimeout(resolve13, kIosInstallPollMs));
20884
+ }
20885
+ }
20886
+ async registeredBundlePath(device) {
20887
+ return parseListedBundlePath(await this.run(["simctl", "listapps", device]), this.options.bundleId);
20888
+ }
19340
20889
  device() {
19341
20890
  return this.options.device ?? "booted";
19342
20891
  }
@@ -19344,6 +20893,14 @@ var XcrunIosDriver = class {
19344
20893
  return this.mailboxRoot === void 0 ? path2 : join(this.mailboxRoot, basename(path2));
19345
20894
  }
19346
20895
  };
20896
+ var kIosInstallRegistrationMs = 6e4;
20897
+ var kIosInstallPollMs = 250;
20898
+ function parseListedBundlePath(output, bundleId) {
20899
+ const key = new RegExp(`"${bundleId.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}"\\s*=\\s*\\{`, "u").exec(output);
20900
+ if (key === null) return void 0;
20901
+ const path2 = /\n\s*Path = (?:"([^"]*)"|([^;\s]+));/u.exec(output.slice(key.index));
20902
+ return path2?.[1] ?? path2?.[2];
20903
+ }
19347
20904
  function parseLaunchedPid(output) {
19348
20905
  const pid = /(?:pid\s+|:\s*)(\d+)\b/iu.exec(output)?.[1];
19349
20906
  if (pid === void 0) throw new Error(`iOS launch did not report a process id: ${output.trim()}`);