@threenative/playtest 0.3.6 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { writeFile, stat, mkdtemp, rm, mkdir, readFile, rename, access, unlink, open, readdir, copyFile, rmdir } from 'fs/promises';
3
- import { join, resolve, relative, dirname, isAbsolute, basename } from 'path';
4
2
  import { existsSync, readdirSync, rmSync, constants, readFileSync } from 'fs';
3
+ import { join, resolve, relative, dirname, isAbsolute, basename } from 'path';
5
4
  import { execFile, spawnSync, spawn } from 'child_process';
5
+ import { writeFile, stat, mkdtemp, rm, mkdir, readFile, access, unlink, rename, open, readdir, copyFile, rmdir } from 'fs/promises';
6
6
  import { tmpdir, homedir } from 'os';
7
7
  import { promisify } from 'util';
8
8
  import { PNG } from 'pngjs';
@@ -380,7 +380,7 @@ var PLAYTEST_ASSERTION_REGISTRY = [
380
380
  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 } }] },
381
381
  fields: [
382
382
  { description: "Before/after or baseline-image changed-pixel ratio bounds.", name: "frameDiff", type: "{ baselineImage?: project-relative PNG, minChangedPixelRatio?: number, maxChangedPixelRatio?: number }" },
383
- { 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 }" },
383
+ { 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 }" },
384
384
  { description: "Entity projected-pixel floor, optionally across all captured samples.", name: "entityVisible", type: "{ entity: string, minProjectedPixels: number, throughoutFrames?: boolean }" }
385
385
  ],
386
386
  cardinality: "array",
@@ -474,7 +474,7 @@ var PLAYTEST_ASSERTION_REGISTRY = [
474
474
  { description: "Substring expected in the observed value.", name: "textIncludes", type: "string" },
475
475
  { description: "Require before and after values to differ or remain equal.", name: "changed", type: "boolean" },
476
476
  { description: "Require the value assertion after every labeled scenario step.", name: "throughoutSteps", type: "boolean" },
477
- { description: "Expected values at named scenario-step samples.", name: "atSteps", type: "Array<{ label: string, equals?: json, textIncludes?: string }>" },
477
+ { description: "Expected values at named scenario-step samples.", name: "atSteps", type: "Array<{ label: string, equals?: json, lte?: number, textIncludes?: string }>" },
478
478
  { description: "Written reason for a held invariant whose initial value intentionally satisfies the assertion.", name: "allowTrivial", type: "triviality reason" },
479
479
  { 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 }>" }
480
480
  ],
@@ -610,7 +610,8 @@ var PLAYTEST_ASSERTION_REGISTRY = [
610
610
  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.",
611
611
  example: { performance: { maxPassDrawCalls: { shadow: 400 }, maxPhaseMsP95: { render: 12 }, minFps: 30 } },
612
612
  fields: [
613
- { description: "Maximum nearest-rank 95th-percentile frame time in milliseconds.", name: "maxFrameMsP95", type: "number" },
613
+ { 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" },
614
+ { 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" },
614
615
  { description: "Minimum sustained frames per second, from the median sampled frame.", name: "minFps", type: "number" },
615
616
  { description: "Per-phase millisecond ceilings at nearest-rank p95. Phases: hostGap, update, render, overlay, residual.", name: "maxPhaseMsP95", type: "{ [phase]: number }" },
616
617
  { description: "Maximum observed renderer draw-call count across every pass combined.", name: "maxDrawCalls", type: "number" },
@@ -764,6 +765,7 @@ var PLAYTEST_ASSERTION_REGISTRY = [
764
765
  fields: [
765
766
  { description: "Entity id. Defaults to scenario subject.", name: "entity", type: "string" },
766
767
  { description: "Animation clip id or name.", name: "clip", type: "string" },
768
+ { description: "Labeled step whose animation report is judged; default is the last sample.", name: "atStep", type: "string" },
767
769
  { description: "Require entering the animation state.", name: "entered", type: "boolean" },
768
770
  { description: "Require animation advancement evidence.", name: "advancedFrames", type: "number" },
769
771
  { description: "Require the observed clip to report its completion state.", name: "finished", type: "boolean" },
@@ -821,6 +823,79 @@ var PLAYTEST_ASSERTION_REGISTRY = [
821
823
  triviality: "not-applicable",
822
824
  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."
823
825
  },
826
+ {
827
+ cardinality: "array",
828
+ 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.",
829
+ example: { footSlip: [{ atStep: "run", feet: ["footL", "footR"], maxSlip: 0.35 }] },
830
+ fields: [
831
+ { 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" },
832
+ { description: "Exact Object3D names of the nodes at the soles, one per foot.", name: "feet", type: "Array<string>" },
833
+ { 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" },
834
+ { 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" },
835
+ { 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" },
836
+ { description: "The moving entity; defaults to the scenario subject.", name: "entity", type: "string" }
837
+ ],
838
+ kind: "footSlip",
839
+ observationPath: "footSlip",
840
+ requiredCapabilities: ["entity.observe", "scene.nodes"],
841
+ resultIdPrefix: "footSlip",
842
+ supportedOn: ["web"],
843
+ triviality: "not-applicable",
844
+ trivialityRationale: "The measurement needs the subject to cover ground during the step, so a standing subject fails as unmeasured instead of passing."
845
+ },
846
+ {
847
+ cardinality: "object",
848
+ 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.",
849
+ example: { sightLine: { maxBlockedRatio: 0.02 } },
850
+ fields: [
851
+ { description: "The entity whose world bounds centre the camera should see; defaults to the scenario subject.", name: "entity", type: "string" },
852
+ { 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" }
853
+ ],
854
+ kind: "sightLine",
855
+ observationPath: "sightLine",
856
+ requiredCapabilities: ["camera.observe", "entity.observe"],
857
+ resultIdPrefix: "sightLine",
858
+ supportedOn: ["web"],
859
+ triviality: "not-applicable",
860
+ 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."
861
+ },
862
+ {
863
+ cardinality: "object",
864
+ 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.",
865
+ example: { engineCost: { maxPerFrame: { bridgeCrossings: 2e3, childrenReads: 60 }, skipWindows: 1, source: "shooter after-value 1,024 per frame on 2026-10-27, about 2x headroom" } },
866
+ fields: [
867
+ { description: "Counter name to its bound on a window's per-frame mean.", name: "maxPerFrame", type: "{ [counter: string]: number }" },
868
+ { description: "Counter name to its bound on any single frame of a window.", name: "maxInFrame", type: "{ [counter: string]: number }" },
869
+ { description: "Windows the run must report; default 1.", name: "minWindows", type: "positive integer" },
870
+ { description: "Windows left unbounded first, the boot (loading, first builds); still and moving count after them. Default 0.", name: "skipWindows", type: "non-negative integer" },
871
+ { 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 } }" },
872
+ { 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 } }" },
873
+ { description: "Where the bounds came from: the measured after-values and the headroom on them.", name: "source", required: true, type: "string" }
874
+ ],
875
+ kind: "engineCost",
876
+ observationPath: "console",
877
+ requiredCapabilities: ["browser.console"],
878
+ resultIdPrefix: "engineCost.",
879
+ supportedOn: ["web"],
880
+ triviality: "not-applicable",
881
+ trivialityRationale: "The counters are measured across the run's frames; an initial value has no frames to count."
882
+ },
883
+ {
884
+ cardinality: "object",
885
+ 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.",
886
+ example: { hudAudit: { minContrast: 3, noDebugText: true } },
887
+ fields: [
888
+ { 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" },
889
+ { description: "Require that no text reads like developer copy. Only true is accepted.", name: "noDebugText", type: "true" }
890
+ ],
891
+ kind: "hudAudit",
892
+ observationPath: "hudAudit",
893
+ requiredCapabilities: ["browser.dom"],
894
+ resultIdPrefix: "hudAudit.",
895
+ supportedOn: ["web"],
896
+ triviality: "not-applicable",
897
+ 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."
898
+ },
824
899
  {
825
900
  cardinality: "array",
826
901
  description: "Relates a tick-stamped effect to the tick-stamped cause that must precede it \u2014 the 'because' a terminal state needs.",
@@ -854,7 +929,9 @@ var PLAYTEST_ASSERTION_REGISTRY = [
854
929
  fields: [
855
930
  { description: "Ceiling on when the start scene's enter() returned, in ms since navigation.", name: "maxEnteredMs", type: "number" },
856
931
  { description: "Ceiling on when first-use compilation settled or its budget expired, in ms since navigation.", name: "maxCompileSettledMs", type: "number" },
857
- { description: "Ceiling on when startup readiness resolved, in ms since navigation.", name: "maxReadyMs", type: "number" }
932
+ { description: "Ceiling on when startup readiness resolved, in ms since navigation.", name: "maxReadyMs", type: "number" },
933
+ { 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" },
934
+ { 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" }
858
935
  ],
859
936
  cardinality: "object",
860
937
  kind: "startup",
@@ -1168,6 +1245,37 @@ function format(value) {
1168
1245
  return value === null ? "unknown" : String(value);
1169
1246
  }
1170
1247
 
1248
+ // src/evaluators/perf-warnings.ts
1249
+ var SCENE_WARNING = "TN_SCENE_WARNING";
1250
+ var BRIDGE_WARNING = "TN_BRIDGE_WARNING";
1251
+ var HOT_CALL = "TN_HOT_CALL";
1252
+ var PROJECTION = "TN_RENDER_PROJECTION:";
1253
+ function perfWarnings(consoleLines) {
1254
+ const found = [];
1255
+ for (const line of consoleLines) {
1256
+ if (typeof line !== "string") continue;
1257
+ for (const marker of [SCENE_WARNING, BRIDGE_WARNING, HOT_CALL]) {
1258
+ const warning = line.indexOf(marker);
1259
+ if (warning !== -1) found.push(line.slice(warning).trim());
1260
+ }
1261
+ const at = line.indexOf(PROJECTION);
1262
+ if (at === -1) continue;
1263
+ const text = line.slice(at).trim();
1264
+ let report;
1265
+ try {
1266
+ report = JSON.parse(line.slice(at + PROJECTION.length));
1267
+ } catch {
1268
+ found.push(`${text} (unreadable)`);
1269
+ continue;
1270
+ }
1271
+ if (report.projecting !== false || report.reasonCode === "disabled") continue;
1272
+ if (report.reasonCode === "belowMeshFloor") continue;
1273
+ const cause = report.cause === void 0 ? "" : ` [cause ${report.cause.code ?? "?"}: ${report.cause.hint ?? "no hint"}]`;
1274
+ found.push(`${text}${cause}`);
1275
+ }
1276
+ return found;
1277
+ }
1278
+
1171
1279
  // src/evaluators/measures.ts
1172
1280
  function horizontalRadius(transform, direction) {
1173
1281
  const halfExtents = transform?.halfExtents ?? (transform?.scale === void 0 ? void 0 : transform.scale.map((value) => Math.abs(value) * 0.5));
@@ -1453,6 +1561,15 @@ function evaluateDiagnosticsPolicy(report, policy) {
1453
1561
  suggestion: "Inspect console.json and fix the first TN_V8_FRAME_FAILED error."
1454
1562
  });
1455
1563
  }
1564
+ const warnings = perfWarnings((report.observations?.console ?? []).map(({ text }) => text));
1565
+ if (warnings.length > 0) {
1566
+ diagnostics.push({
1567
+ code: "TN_PLAYTEST_PERF_WARNING",
1568
+ message: `${warnings.length} engine performance warning(s): ${warnings.slice(0, 3).join(" | ")}`,
1569
+ severity: "error",
1570
+ 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."
1571
+ });
1572
+ }
1456
1573
  const capturedConsoleErrors = consoleErrors(report.observations?.console ?? []);
1457
1574
  if (policy.noConsoleErrors && capturedConsoleErrors.length > 0) {
1458
1575
  diagnostics.push({
@@ -1825,12 +1942,17 @@ function strideReading(observed) {
1825
1942
  return {
1826
1943
  clipGroundSpeed: stride.clipGroundSpeed,
1827
1944
  groundSpeed: stride.groundSpeed,
1945
+ inPlace: stride.inPlace === true,
1828
1946
  overridden: stride.overridden,
1829
1947
  rate: stride.rate,
1830
1948
  synced: stride.synced
1831
1949
  };
1832
1950
  }
1833
1951
  var STRIDE_GROUND_SPEED_FLOOR = 1e-3;
1952
+ function strideHasNoFootPlant(reading) {
1953
+ return reading.inPlace && Math.abs(reading.clipGroundSpeed) <= STRIDE_GROUND_SPEED_FLOOR && Math.abs(reading.groundSpeed) > STRIDE_GROUND_SPEED_FLOOR;
1954
+ }
1955
+ var NO_FOOT_PLANT_DETAIL = "no foot plant found: stride sync is off";
1834
1956
  function appliedStrideRate(reading) {
1835
1957
  return reading.synced ? reading.rate : 1;
1836
1958
  }
@@ -1849,6 +1971,8 @@ function strideFailure(assertion, observed) {
1849
1971
  code: "TN_PLAYTEST_STRIDE_UNOBSERVED",
1850
1972
  detail: "the runtime reported no stride for this clip, so neither the feet nor the ground were measured"
1851
1973
  };
1974
+ if (assertion.strideSynced !== false && strideHasNoFootPlant(reading))
1975
+ return { code: "TN_PLAYTEST_STRIDE_NO_FOOT_PLANT", detail: NO_FOOT_PLANT_DETAIL };
1852
1976
  if (assertion.strideSynced !== void 0 && reading.synced !== assertion.strideSynced)
1853
1977
  return {
1854
1978
  code: "TN_PLAYTEST_STRIDE_NOT_SYNCED",
@@ -1959,6 +2083,240 @@ function assertJsonSafe(value, path2 = "$") {
1959
2083
  }
1960
2084
  throw new TypeError(`${path2} must be JSON-safe.`);
1961
2085
  }
2086
+ var DEFAULT_XVFB_SCREEN = "1600x900x24";
2087
+ var HOST_DISPLAY_ENV = "TN_PLAYTEST_HOST_DISPLAY";
2088
+ var STRIPPED_WAYLAND_VARS = ["WAYLAND_DISPLAY", "WAYLAND_SOCKET", "XDG_SESSION_TYPE"];
2089
+ function decideDisplayStrategy(input) {
2090
+ if (input.platform !== "linux") return { kind: "host" };
2091
+ const privateXvfb = {
2092
+ kind: "private-xvfb",
2093
+ screen: input.env.TN_XVFB_SCREEN ?? DEFAULT_XVFB_SCREEN
2094
+ };
2095
+ if (!hostDisplayRequested(input.env)) return privateXvfb;
2096
+ const display = input.env.DISPLAY;
2097
+ if (display === void 0 || display.length === 0) {
2098
+ throw new Error("TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: the requested host display requires DISPLAY.");
2099
+ }
2100
+ const available = input.displaySocketExists?.(display) ?? x11DisplayIsUsable(display, input.env);
2101
+ if (!available) {
2102
+ throw new Error(`TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: cannot connect to requested DISPLAY=${display}. Refusing to substitute a private Xvfb.`);
2103
+ }
2104
+ return { display, kind: "existing" };
2105
+ }
2106
+ function hostDisplayRequested(env) {
2107
+ const value = env[HOST_DISPLAY_ENV];
2108
+ return value === "1" || value?.toLowerCase() === "true";
2109
+ }
2110
+ function x11DisplayIsUsable(display, env) {
2111
+ const probe = spawnSync("xdpyinfo", ["-display", display], { env, stdio: "ignore", timeout: 2e3 });
2112
+ if (probe.error) {
2113
+ throw new Error(`TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: cannot verify DISPLAY=${display}: xdpyinfo ${probe.error.message}.`);
2114
+ }
2115
+ return probe.status === 0;
2116
+ }
2117
+ function childEnvForDisplay(env, display) {
2118
+ const child = { ...env };
2119
+ for (const name of STRIPPED_WAYLAND_VARS) delete child[name];
2120
+ child.DISPLAY = display;
2121
+ return child;
2122
+ }
2123
+ function runNeedsPixels(config, scenario) {
2124
+ if (config.headless !== true) return true;
2125
+ const takesScreenshot = scenario.artifacts?.screenshots !== false || scenario.steps.some(({ screenshot }) => screenshot !== void 0);
2126
+ const evaluatesVisual = (scenario.assert?.visual?.length ?? 0) > 0 || (scenario.assert?.tone?.length ?? 0) > 0;
2127
+ return takesScreenshot || evaluatesVisual || scenario.assert?.framebufferCoverage !== void 0;
2128
+ }
2129
+ async function provideDisplay(options = {}) {
2130
+ const env = options.env ?? process.env;
2131
+ const platform = options.platform ?? process.platform;
2132
+ const strategy = decideDisplayStrategy({
2133
+ displaySocketExists: options.displaySocketExists,
2134
+ env,
2135
+ platform
2136
+ });
2137
+ if (strategy.kind === "host") {
2138
+ return {
2139
+ compositor: void 0,
2140
+ display: void 0,
2141
+ env: { ...env },
2142
+ release: async () => void 0,
2143
+ strategy
2144
+ };
2145
+ }
2146
+ if (strategy.kind === "existing") {
2147
+ return {
2148
+ compositor: void 0,
2149
+ display: strategy.display,
2150
+ env: childEnvForDisplay(env, strategy.display),
2151
+ release: async () => void 0,
2152
+ strategy
2153
+ };
2154
+ }
2155
+ const commandExists = options.commandExists ?? defaultCommandExists;
2156
+ if (!commandExists("Xvfb")) {
2157
+ throw new Error(
2158
+ "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."
2159
+ );
2160
+ }
2161
+ const spawnProcess = options.spawnProcess ?? spawn;
2162
+ const xvfb = spawnProcess("Xvfb", [
2163
+ "-displayfd",
2164
+ "3",
2165
+ "-nolisten",
2166
+ "tcp",
2167
+ // COMPOSITE and SHAPE are what a compositing manager needs before it can blend anything, and
2168
+ // the native desktop runtime refuses to attach its UI overlay to a display without one. Xvfb
2169
+ // does not enable them by default, so every native UI run on a private display reported
2170
+ // `TN_UI_OVERLAY:{"attached":false,"reason":"no compositing manager is running"}` — including
2171
+ // the starter template's own shipped native-playtests/react-hud scenario, which failed out of
2172
+ // the box on a freshly scaffolded project. A browser run does not care either way.
2173
+ "+extension",
2174
+ "COMPOSITE",
2175
+ "+extension",
2176
+ "SHAPE",
2177
+ "-screen",
2178
+ "0",
2179
+ strategy.screen
2180
+ ], { stdio: ["ignore", "ignore", "pipe", "pipe"] });
2181
+ xvfb.on?.("error", () => void 0);
2182
+ try {
2183
+ const number = await readXvfbDisplayNumber(xvfb);
2184
+ const display = `:${number}`;
2185
+ const compositor = await startCompositor(display, { commandExists, env, spawnProcess });
2186
+ return {
2187
+ compositor: compositor?.name,
2188
+ display,
2189
+ env: childEnvForDisplay(env, display),
2190
+ release: async () => {
2191
+ if (compositor !== void 0) await stopChild(compositor.child);
2192
+ await stopChild(xvfb);
2193
+ },
2194
+ strategy
2195
+ };
2196
+ } catch (error) {
2197
+ await stopChild(xvfb);
2198
+ throw error;
2199
+ }
2200
+ }
2201
+ var COMPOSITORS = [
2202
+ { args: ["-n"], name: "xcompmgr" },
2203
+ { args: [], name: "picom" },
2204
+ { args: [], name: "compton" }
2205
+ ];
2206
+ var COMPOSITOR_SETTLE_MS = 250;
2207
+ async function startCompositor(display, options) {
2208
+ const choice = COMPOSITORS.find(({ name }) => options.commandExists(name));
2209
+ if (choice === void 0) return void 0;
2210
+ const child = options.spawnProcess(choice.name, [...choice.args], {
2211
+ env: { ...options.env, DISPLAY: display },
2212
+ stdio: "ignore"
2213
+ });
2214
+ let spawnFailed = false;
2215
+ child.on?.("error", () => {
2216
+ spawnFailed = true;
2217
+ });
2218
+ await new Promise((settle) => setTimeout(settle, COMPOSITOR_SETTLE_MS));
2219
+ if (spawnFailed) return void 0;
2220
+ if ((child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null) return void 0;
2221
+ return { child, name: choice.name };
2222
+ }
2223
+ var XVFB_DISPLAY_TIMEOUT_MS = 3e4;
2224
+ async function readXvfbDisplayNumber(xvfb) {
2225
+ const report = xvfb.stdio[3];
2226
+ if (report === null || report === void 0 || typeof report.on !== "function") {
2227
+ throw new Error("Xvfb was spawned without a display-report descriptor to read.");
2228
+ }
2229
+ const stream = report;
2230
+ return new Promise((resolveDisplay, rejectDisplay) => {
2231
+ let settled = false;
2232
+ const finish = (settle) => {
2233
+ if (settled) return;
2234
+ settled = true;
2235
+ clearTimeout(timer);
2236
+ stream.removeListener("data", onData);
2237
+ stream.removeListener("close", onClose);
2238
+ settle();
2239
+ };
2240
+ const onData = (chunk) => {
2241
+ const number = Number.parseInt(String(chunk).trim(), 10);
2242
+ if (Number.isInteger(number) && number >= 0) finish(() => resolveDisplay(number));
2243
+ };
2244
+ const onClose = () => finish(() => rejectDisplay(new Error("Xvfb exited before it reported a display.")));
2245
+ const timer = setTimeout(() => finish(() => {
2246
+ rejectDisplay(new Error(`Xvfb did not report a display within ${XVFB_DISPLAY_TIMEOUT_MS}ms.`));
2247
+ }), XVFB_DISPLAY_TIMEOUT_MS);
2248
+ stream.on("data", onData);
2249
+ stream.on("close", onClose);
2250
+ });
2251
+ }
2252
+ async function stopChild(child) {
2253
+ const exitedAlready = () => (child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null;
2254
+ if (exitedAlready()) return;
2255
+ child.kill("SIGTERM");
2256
+ const started = Date.now();
2257
+ while (Date.now() - started < 1e3 && !exitedAlready()) {
2258
+ await new Promise((resolveWait) => setTimeout(resolveWait, 25));
2259
+ }
2260
+ if (!exitedAlready()) child.kill("SIGKILL");
2261
+ }
2262
+ function defaultCommandExists(command) {
2263
+ const paths = (process.env.PATH ?? "").split(":").filter((segment) => segment.length > 0);
2264
+ return paths.some((directory) => existsSync(join(directory, command)));
2265
+ }
2266
+
2267
+ // src/evaluators/frame-cost.ts
2268
+ var FRAME_BUDGET = "TN_FRAME_BUDGET:";
2269
+ function frameDisplay(env = process.env, platform = process.platform) {
2270
+ return platform === "linux" && !hostDisplayRequested(env) ? "virtual" : "real";
2271
+ }
2272
+ function foreignGpuProcesses(ownPid = process.pid, procRoot = "/proc", platform = process.platform) {
2273
+ if (platform !== "linux") return [];
2274
+ const read = (pid, file) => {
2275
+ try {
2276
+ return readFileSync(join(procRoot, pid, file), "utf8");
2277
+ } catch {
2278
+ return void 0;
2279
+ }
2280
+ };
2281
+ const parentOf = (pid) => {
2282
+ const stat4 = read(String(pid), "stat");
2283
+ const ppid = stat4 === void 0 ? void 0 : Number(stat4.slice(stat4.lastIndexOf(")") + 2).split(" ")[1]);
2284
+ return ppid === void 0 || !Number.isSafeInteger(ppid) ? void 0 : ppid;
2285
+ };
2286
+ const ours = (pid) => {
2287
+ for (let current = pid, hops = 0; current !== void 0 && current > 1 && hops < 64; hops++) {
2288
+ if (current === ownPid) return true;
2289
+ current = parentOf(current);
2290
+ }
2291
+ return false;
2292
+ };
2293
+ return readdirSync(procRoot).filter((entry) => {
2294
+ const argv = /^\d+$/u.test(entry) ? (read(entry, "cmdline") ?? "").split("\0") : [];
2295
+ return argv.includes("--type=gpu-process") && (argv[0] ?? "").includes("ms-playwright");
2296
+ }).map(Number).filter((pid) => !ours(pid)).sort((a, b) => a - b);
2297
+ }
2298
+ var MIN_GPU_SAMPLES = 3;
2299
+ function gpuWindows(consoleLines) {
2300
+ const windows = [];
2301
+ let samples;
2302
+ for (const line of consoleLines) {
2303
+ if (typeof line !== "string") continue;
2304
+ const at = line.indexOf(FRAME_BUDGET);
2305
+ if (at === -1) continue;
2306
+ let report;
2307
+ try {
2308
+ report = JSON.parse(line.slice(at + FRAME_BUDGET.length));
2309
+ } catch {
2310
+ continue;
2311
+ }
2312
+ const p95 = report.gpu?.p95;
2313
+ if (typeof p95 === "number" && Number.isFinite(p95) && (typeof report.gpu?.samples !== "number" || report.gpu.samples > 0)) {
2314
+ windows.push(p95);
2315
+ samples = typeof report.gpu?.samples === "number" ? report.gpu.samples : void 0;
2316
+ }
2317
+ }
2318
+ return windows.length === 0 ? { windows } : { p95: windows[windows.length - 1], ...samples === void 0 ? {} : { samples }, windows };
2319
+ }
1962
2320
 
1963
2321
  // src/evaluators/render-evidence.ts
1964
2322
  function projectedPixelsForEntity(snapshot, entity, viewport) {
@@ -1977,7 +2335,7 @@ function countMatchingEntries(effectLog, tokens) {
1977
2335
  return tokens.every((token) => text.includes(token));
1978
2336
  }).length;
1979
2337
  }
1980
- function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2338
+ function evaluatePerformanceAssertion(assertion, series, sourcePath, lane) {
1981
2339
  const samples = series ?? [];
1982
2340
  const validSamples = samples.length > 0 && samples.every(isRuntimeDiagnosticsSample);
1983
2341
  const observed = validSamples ? samples : [];
@@ -2018,13 +2376,17 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2018
2376
  });
2019
2377
  };
2020
2378
  if (assertion.maxFrameMsP95 !== void 0) {
2021
- addBound(
2022
- "performance.maxFrameMsP95",
2023
- assertion.maxFrameMsP95,
2024
- frameMsP95,
2025
- "ms",
2026
- samplesPass && frameMsP95 !== void 0 && frameMsP95 <= assertion.maxFrameMsP95
2027
- );
2379
+ if (lane === void 0) {
2380
+ addBound(
2381
+ "performance.maxFrameMsP95",
2382
+ assertion.maxFrameMsP95,
2383
+ frameMsP95,
2384
+ "ms",
2385
+ samplesPass && frameMsP95 !== void 0 && frameMsP95 <= assertion.maxFrameMsP95
2386
+ );
2387
+ } else {
2388
+ emitFrameBound(assertion.maxFrameMsP95, frameMsP95, observed, samples.length, samplesPass, lane, results, diagnostics, path2, sourcePath);
2389
+ }
2028
2390
  }
2029
2391
  if (assertion.maxDrawCalls !== void 0) {
2030
2392
  addBound(
@@ -2036,17 +2398,26 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2036
2398
  );
2037
2399
  }
2038
2400
  if (assertion.minFps !== void 0) {
2039
- const exact = fpsFromFrameTimes(frameTimes);
2040
- const observed2 = exact === void 0 ? void 0 : Math.floor(exact * 100) / 100;
2401
+ const onXvfb = lane?.display === "virtual" && lane.target !== "android" && lane.target !== "ios";
2402
+ const costP95 = onXvfb ? frameCost(observed, samples.length, lane).costP95 : void 0;
2403
+ const virtual = costP95 !== void 0 && costP95 > 0;
2404
+ const exact = virtual ? 1e3 / costP95 : fpsFromFrameTimes(frameTimes);
2405
+ const observedFps = exact === void 0 ? void 0 : Math.floor(exact * 100) / 100;
2041
2406
  const pass = samplesPass && exact !== void 0 && exact >= assertion.minFps;
2042
2407
  results.push({
2043
- details: { actual: observed2 ?? null, expected: assertion.minFps, sampleCount: samples.length, unit: "fps" },
2408
+ details: {
2409
+ actual: observedFps ?? null,
2410
+ expected: assertion.minFps,
2411
+ sampleCount: samples.length,
2412
+ unit: "fps",
2413
+ ...virtual ? { basis: "frame-cost", interval: { gated: false, p95: frameMsP95 ?? null, reason: XVFB_CADENCE } } : {}
2414
+ },
2044
2415
  id: "performance.minFps",
2045
2416
  pass
2046
2417
  });
2047
2418
  if (!pass) diagnostics.push({
2048
2419
  code: "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
2049
- message: `performance.minFps expected at least ${assertion.minFps} fps, observed ${observed2 ?? "unavailable"}.`,
2420
+ message: `performance.minFps expected at least ${assertion.minFps} fps, observed ${observedFps ?? "unavailable"}${virtual ? " from frame cost on a virtual display" : ""}.`,
2050
2421
  observedRuntimePath: path2,
2051
2422
  severity: "error",
2052
2423
  sourcePath,
@@ -2111,14 +2482,66 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2111
2482
  addPassBound("triangles", kind, ceiling);
2112
2483
  return { assertions: results, diagnostics };
2113
2484
  }
2114
- function isRuntimeDiagnosticsSample(value) {
2115
- if (!isRecord(value) || typeof value.frameMs !== "number" || !Number.isFinite(value.frameMs) || value.frameMs <= 0) {
2116
- return false;
2117
- }
2118
- return (value.drawCalls === void 0 || typeof value.drawCalls === "number" && Number.isFinite(value.drawCalls) && value.drawCalls >= 0) && (value.triangles === void 0 || typeof value.triangles === "number" && Number.isFinite(value.triangles) && value.triangles >= 0) && isFramePhaseSplit(value.phases) && isFramePassSplit(value.passes);
2119
- }
2120
- function isFramePassSplit(value) {
2121
- if (value === void 0) return true;
2485
+ var HITCH_MS = 2e3;
2486
+ var XVFB_CADENCE = "display cadence, not gated: the runner's private Xvfb paces frames on its own timer, not the game's cost";
2487
+ function frameCost(observed, sampleCount, lane) {
2488
+ const cpu = observed.flatMap(({ phases }) => phases === void 0 || typeof phases.update !== "number" || typeof phases.render !== "number" ? [] : [phases.update + phases.render]);
2489
+ const hitches = observed.filter(({ frameMs, phases }) => phases === void 0 && frameMs >= HITCH_MS).length;
2490
+ const cpuP95 = cpu.length > 0 && cpu.length + hitches === sampleCount ? nearestRank(cpu, 0.95) : void 0;
2491
+ const costP95 = cpuP95 === void 0 || lane.gpuP95 === void 0 ? void 0 : Math.max(cpuP95, lane.gpuP95);
2492
+ return { costP95, cpuP95, hitches };
2493
+ }
2494
+ function emitFrameBound(ceiling, intervalP95, observed, sampleCount, samplesPass, lane, results, diagnostics, path2, sourcePath) {
2495
+ const { costP95, cpuP95, hitches } = frameCost(observed, sampleCount, lane);
2496
+ const missing = [
2497
+ ...cpuP95 === void 0 ? ["the CPU frame split (phases.update and phases.render)"] : [],
2498
+ ...lane.gpuP95 === void 0 ? ["the GPU time (a TN_FRAME_BUDGET window with a gpu reading)"] : []
2499
+ ];
2500
+ const virtual = lane.display === "virtual";
2501
+ const costPass = costP95 !== void 0 && costP95 <= ceiling;
2502
+ const intervalPass = virtual || intervalP95 !== void 0 && intervalP95 <= ceiling;
2503
+ const thinGpu = lane.gpuP95 !== void 0 && !(lane.gpuSamples !== void 0 && lane.gpuSamples >= MIN_GPU_SAMPLES);
2504
+ const pass = samplesPass && costPass && intervalPass && !thinGpu;
2505
+ const round2 = (value) => value === void 0 ? null : Math.round(value * 100) / 100;
2506
+ results.push({
2507
+ details: {
2508
+ actual: round2(virtual || !costPass ? costP95 : intervalP95),
2509
+ cost: { cpuP95: round2(cpuP95), gpuP95: round2(lane.gpuP95), gpuSamples: lane.gpuSamples ?? null, hitchFrames: hitches, p95: round2(costP95) },
2510
+ display: lane.display,
2511
+ expected: ceiling,
2512
+ interval: virtual ? { gated: false, p95: round2(intervalP95), reason: XVFB_CADENCE } : { gated: true, p95: round2(intervalP95) },
2513
+ sampleCount,
2514
+ unit: "ms"
2515
+ },
2516
+ id: "performance.maxFrameMsP95",
2517
+ pass
2518
+ });
2519
+ if (pass) return;
2520
+ const foreign = lane.foreignGpu ?? [];
2521
+ const contended = missing.length === 0 && !costPass && foreign.length > 0;
2522
+ const detail = missing.length > 0 ? `cannot be judged: the run did not measure ${missing.join(" or ")}` : !costPass ? `cost p95 ${round2(costP95)} ms (CPU ${round2(cpuP95)}, GPU ${round2(lane.gpuP95)}) is over ${ceiling} ms${contended ? ` while ${foreign.length} other GPU process${foreign.length === 1 ? "" : "es"} ran (${foreign.join(", ")})` : ""}` : `rAF interval p95 ${round2(intervalP95)} ms on a real display is over ${ceiling} ms`;
2523
+ const fewSamples = missing.length === 0 && costPass && thinGpu;
2524
+ diagnostics.push({
2525
+ code: fewSamples ? "TN_PLAYTEST_PERF_FEW_GPU_SAMPLES" : "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
2526
+ message: `performance.maxFrameMsP95 ${fewSamples ? fewGpuSamples(lane.gpuSamples) : detail}.`,
2527
+ observedRuntimePath: path2,
2528
+ severity: "error",
2529
+ sourcePath,
2530
+ 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."
2531
+ });
2532
+ }
2533
+ function fewGpuSamples(samples) {
2534
+ const held = samples === void 0 ? "reports no sample count" : `holds ${samples} GPU sample${samples === 1 ? "" : "s"}`;
2535
+ return `cannot be judged: the latest GPU window ${held}, under the minimum of ${MIN_GPU_SAMPLES}`;
2536
+ }
2537
+ function isRuntimeDiagnosticsSample(value) {
2538
+ if (!isRecord(value) || typeof value.frameMs !== "number" || !Number.isFinite(value.frameMs) || value.frameMs <= 0) {
2539
+ return false;
2540
+ }
2541
+ return (value.drawCalls === void 0 || typeof value.drawCalls === "number" && Number.isFinite(value.drawCalls) && value.drawCalls >= 0) && (value.triangles === void 0 || typeof value.triangles === "number" && Number.isFinite(value.triangles) && value.triangles >= 0) && isFramePhaseSplit(value.phases) && isFramePassSplit(value.passes);
2542
+ }
2543
+ function isFramePassSplit(value) {
2544
+ if (value === void 0) return true;
2122
2545
  if (!Array.isArray(value)) return false;
2123
2546
  return value.every(
2124
2547
  (pass) => isRecord(pass) && PLAYTEST_FRAME_PASS_KINDS.includes(pass.kind) && typeof pass.draws === "number" && Number.isFinite(pass.draws) && pass.draws >= 0 && typeof pass.triangles === "number" && Number.isFinite(pass.triangles) && pass.triangles >= 0
@@ -2429,6 +2852,17 @@ function emitEvidenceFamilies(ctx) {
2429
2852
  const pass = observed !== void 0 && observed.nonblankPixelRatio >= minimum;
2430
2853
  assertions.push({ id: `visual.${index}.region`, pass, details: { after: pass, expected: { equals: true }, minimum, observed: observed?.nonblankPixelRatio } });
2431
2854
  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." });
2855
+ if (staticRegion.minSharpness !== void 0) {
2856
+ const sharpness = observed?.sharpness;
2857
+ const sharpPass = sharpness !== void 0 && sharpness >= staticRegion.minSharpness;
2858
+ assertions.push({ id: `visual.${index}.region.sharpness`, pass: sharpPass, details: { minimum: staticRegion.minSharpness, observed: sharpness ?? null } });
2859
+ if (!sharpPass) diagnostics.push({
2860
+ code: "TN_PLAYTEST_REGION_BLURRED",
2861
+ 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).`,
2862
+ severity: "error",
2863
+ 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."
2864
+ });
2865
+ }
2432
2866
  if (staticRegion.minDarkPixelRatio !== void 0) {
2433
2867
  const darkPass = observed?.darkPixelRatio !== void 0 && observed.darkPixelRatio >= staticRegion.minDarkPixelRatio;
2434
2868
  assertions.push({
@@ -2491,12 +2925,14 @@ function emitMovementEvidence(ctx) {
2491
2925
  scenarioAssertions.diagnostics,
2492
2926
  input.report.target
2493
2927
  );
2928
+ const warningTexts = perfWarnings((input.report.observations?.console ?? []).map(({ text }) => text));
2494
2929
  const policyDiagnostics = evaluateDiagnosticsPolicy(input.report, diagnosticsPolicy);
2495
2930
  diagnostics.push(...policyDiagnostics);
2496
2931
  assertions.push({
2497
2932
  details: {
2498
2933
  consoleErrors: consoleErrors(input.report.observations?.console ?? []).length,
2499
2934
  networkErrors: input.report.observations?.network.length ?? 0,
2935
+ ...warningTexts.length === 0 ? {} : { perfWarnings: warningTexts },
2500
2936
  policy: diagnosticsPolicy,
2501
2937
  runtimeDiagnostics: runtimeDiagnostics(input.report.observations?.runtimeDiagnostics).length
2502
2938
  },
@@ -2907,7 +3343,8 @@ function emitMovementEvidence(ctx) {
2907
3343
  }
2908
3344
  for (const assertion of scenarioAssertions.animation ?? []) {
2909
3345
  const entity = assertion.entity ?? input.scenario.subject ?? input.report.entity;
2910
- const runtime = runtimeAnimationObservations(input.report.observations?.runtimeObservations);
3346
+ const stepAnimation = runtimeGameplayAtStep(input.report.observations?.runtimeObservations, assertion.atStep)?.animation;
3347
+ const runtime = assertion.atStep === void 0 ? runtimeAnimationObservations(input.report.observations?.runtimeObservations) : isRecord(stepAnimation) ? stepAnimation : void 0;
2911
3348
  if (runtime !== void 0) {
2912
3349
  const observed = isRecord(runtime[entity]) ? runtime[entity] : void 0;
2913
3350
  const clip = typeof observed?.clip === "string" ? observed.clip : void 0;
@@ -3270,19 +3707,206 @@ function emitParity(ctx) {
3270
3707
  }
3271
3708
  }
3272
3709
 
3710
+ // src/runner/browser.ts
3711
+ var WEBGPU_BROWSER_ARGS = [
3712
+ "--ozone-platform=x11",
3713
+ "--enable-unsafe-webgpu",
3714
+ "--disable-gpu-sandbox",
3715
+ "--ignore-gpu-blocklist",
3716
+ // Keep Vulkan available on both hardware and software adapters.
3717
+ "--enable-features=Vulkan"
3718
+ // No forced ANGLE/Vulkan (--use-angle=vulkan --use-vulkan --disable-vulkan-surface): on a KDE
3719
+ // Xwayland host display it blacked out the sky while the same NVIDIA adapter drew it without them.
3720
+ ];
3721
+ var PERFORMANCE_BROWSER_ARGS = [
3722
+ "--disable-frame-rate-limit",
3723
+ "--disable-gpu-vsync"
3724
+ ];
3725
+ function measurementBrowserArgs(performance2, completion, display, gameThread = "page") {
3726
+ const args = completion || performance2 && display === "virtual" ? PERFORMANCE_BROWSER_ARGS : [];
3727
+ return gameThread === "worker" ? args.filter((argument) => argument !== "--disable-frame-rate-limit") : args;
3728
+ }
3729
+ function resolveBrowserArguments(browserArgs) {
3730
+ return [...browserArgs ?? []];
3731
+ }
3732
+ var SOFTWARE_ADAPTER = /swiftshader|llvmpipe|lavapipe|softwarerasterizer|software adapter|basic render/i;
3733
+ function softwareAdapterName(adapter) {
3734
+ if (adapter === void 0) return void 0;
3735
+ for (const value of Object.values(adapter)) {
3736
+ if (typeof value === "string" && SOFTWARE_ADAPTER.test(value)) return value;
3737
+ }
3738
+ return void 0;
3739
+ }
3740
+ function reconcileBrowserPointers(previous, next) {
3741
+ const normalized = new Map(next.map((pointer) => [pointer.id, {
3742
+ buttons: pointer.buttons ?? 1,
3743
+ id: pointer.id,
3744
+ x: pointer.x,
3745
+ y: pointer.y
3746
+ }]));
3747
+ const previousPrimary = previous.keys().next().value;
3748
+ const nextPrimary = normalized.keys().next().value;
3749
+ const changes = [];
3750
+ for (const pointer of previous.values()) {
3751
+ if (!normalized.has(pointer.id)) {
3752
+ changes.push({ isPrimary: pointer.id === previousPrimary, pointer: { ...pointer, buttons: 0 }, type: "pointerup" });
3753
+ }
3754
+ }
3755
+ for (const pointer of normalized.values()) {
3756
+ const old = previous.get(pointer.id);
3757
+ if (old === void 0) {
3758
+ changes.push({ isPrimary: pointer.id === nextPrimary, pointer, type: "pointerdown" });
3759
+ } else if (old.x !== pointer.x || old.y !== pointer.y || old.buttons !== pointer.buttons) {
3760
+ changes.push({ isPrimary: pointer.id === nextPrimary, pointer, type: "pointermove" });
3761
+ }
3762
+ }
3763
+ return changes;
3764
+ }
3765
+
3766
+ // src/evaluators/adapter-class.ts
3767
+ function classifyAdapter(report) {
3768
+ const capture = report.capture;
3769
+ if (capture === void 0 || capture.rendererKind !== "webgpu") return {};
3770
+ if (adapterIdentity(capture.adapter) === void 0) return {};
3771
+ const software = softwareAdapterName(capture.adapter);
3772
+ if (software !== void 0) return { adapterClass: "software", softwareAdapter: software };
3773
+ const gpuFamily = gpuFamilyOf(capture.adapter);
3774
+ return gpuFamily === void 0 ? { adapterClass: "hardware" } : { adapterClass: "hardware", gpuFamily };
3775
+ }
3776
+ var ADAPTER_IDENTITY_KEYS = ["architecture", "description", "device", "vendor"];
3777
+ function adapterIdentity(adapter) {
3778
+ if (adapter === void 0) return void 0;
3779
+ for (const key of ADAPTER_IDENTITY_KEYS) {
3780
+ const value = adapter[key];
3781
+ if (typeof value === "string" && value.trim() !== "") return value;
3782
+ }
3783
+ return void 0;
3784
+ }
3785
+ var MALI_MODEL = /\bmali[\s_-]*g?[\s-]*(\d{2,3})/i;
3786
+ var ADRENO_MODEL = /\badreno\W*(?:tm\W*)?(\d)(\d\d|xx)/i;
3787
+ var AMD_INTEGRATED = /radeon(?:\(tm\))?\s+(?:graphics|\d{3}m)\b/i;
3788
+ var INTEL_DISCRETE = /\barc\b|xe2?-hpg|battlemage|alchemist/i;
3789
+ var FAMILY_RULES = [
3790
+ ({ architecture, description, device }) => {
3791
+ const number = [description, device, architecture].map((value) => MALI_MODEL.exec(value)?.[1]).find((value) => value !== void 0);
3792
+ if (number === void 0) return void 0;
3793
+ const model = Number(number);
3794
+ if (model >= 710) return "mobile-high";
3795
+ return model < 57 || model === 71 || model === 72 ? "mobile-low" : "mobile-mid";
3796
+ },
3797
+ ({ architecture, vendor }) => {
3798
+ if (!/\barm\b/i.test(vendor)) return void 0;
3799
+ if (/midgard|bifrost/i.test(architecture)) return "mobile-low";
3800
+ if (/valhall/i.test(architecture)) return "mobile-mid";
3801
+ return /5th-?gen|immortalis/i.test(architecture) ? "mobile-high" : void 0;
3802
+ },
3803
+ ({ architecture, description, device }) => {
3804
+ const match = [description, device, architecture].map((value) => ADRENO_MODEL.exec(value)).find((value) => value !== null && value !== void 0);
3805
+ if (match === null || match === void 0) return void 0;
3806
+ const generation = Number(match[1]);
3807
+ if (generation <= 4) return "mobile-low";
3808
+ if (generation === 5) return "mobile-mid";
3809
+ if (generation === 6) return match[2] !== "xx" && Number(match[2]) >= 30 ? "mobile-high" : "mobile-mid";
3810
+ return "mobile-high";
3811
+ },
3812
+ ({ architecture, description, device, vendor }) => /nvidia/i.test(vendor) && ![architecture, description, device].some((value) => /tegra/i.test(value)) ? "discrete" : void 0,
3813
+ ({ architecture, description, device, vendor }) => {
3814
+ if (!/intel/i.test(vendor)) return void 0;
3815
+ return [architecture, description, device].some((value) => INTEL_DISCRETE.test(value)) ? "discrete" : "integrated";
3816
+ },
3817
+ // An APU and a card share an architecture name, so an AMD adapter that names no iGPU is `discrete`.
3818
+ ({ description, vendor }) => /\b(?:amd|ati)\b/i.test(vendor) ? AMD_INTEGRATED.test(description) ? "integrated" : "discrete" : void 0
3819
+ ];
3820
+ function gpuFamilyOf(adapter) {
3821
+ if (adapter === void 0) return void 0;
3822
+ const field = (key) => {
3823
+ const value = adapter[key];
3824
+ return typeof value === "string" ? value : "";
3825
+ };
3826
+ const fields = {
3827
+ architecture: field("architecture"),
3828
+ description: field("description"),
3829
+ device: field("device"),
3830
+ vendor: field("vendor")
3831
+ };
3832
+ for (const rule of FAMILY_RULES) {
3833
+ const family = rule(fields);
3834
+ if (family !== void 0) return family;
3835
+ }
3836
+ return void 0;
3837
+ }
3838
+ function adapterFieldsFromIdentity(identity) {
3839
+ if (typeof identity !== "string") return void 0;
3840
+ const prefix = "webgpu:";
3841
+ if (!identity.startsWith(prefix)) return void 0;
3842
+ const fields = /* @__PURE__ */ Object.create(null);
3843
+ for (const pair of identity.slice(prefix.length).split("|")) {
3844
+ const separator = pair.indexOf("=");
3845
+ if (separator <= 0) return void 0;
3846
+ const key = pair.slice(0, separator);
3847
+ if (!ADAPTER_IDENTITY_KEYS.includes(key) || Object.hasOwn(fields, key)) {
3848
+ return void 0;
3849
+ }
3850
+ let value;
3851
+ try {
3852
+ value = decodeURIComponent(pair.slice(separator + 1));
3853
+ } catch {
3854
+ return void 0;
3855
+ }
3856
+ if (value.trim() === "") return void 0;
3857
+ fields[key] = value;
3858
+ }
3859
+ if (Object.keys(fields).length === 0) return void 0;
3860
+ return fields;
3861
+ }
3862
+ function nativeCaptureProvenance(census, target, viewport) {
3863
+ if (census === void 0 || census === null || typeof census !== "object" || Array.isArray(census)) return void 0;
3864
+ const adapterRecord = census.adapter;
3865
+ if (adapterRecord === void 0 || adapterRecord === null || typeof adapterRecord !== "object" || Array.isArray(adapterRecord)) return void 0;
3866
+ const adapter = adapterFieldsFromIdentity(adapterRecord.identity);
3867
+ if (adapter === void 0) return void 0;
3868
+ return {
3869
+ adapter,
3870
+ // A native launch carries no browser command line; there is no argument list to report and
3871
+ // inventing one would be a flag nobody can check.
3872
+ browserArgs: [],
3873
+ captureMethod: "device.screenshot",
3874
+ rendererKind: "webgpu",
3875
+ target,
3876
+ viewport
3877
+ };
3878
+ }
3879
+
3273
3880
  // src/evaluators/perf-signals-world.ts
3881
+ function gpuLane(consoleTexts) {
3882
+ const { p95, samples } = gpuWindows(consoleTexts);
3883
+ return p95 === void 0 ? {} : { gpuP95: p95, ...samples === void 0 ? {} : { gpuSamples: samples } };
3884
+ }
3274
3885
  function emitPerfSignalsWorld(ctx) {
3275
3886
  const { assertions, diagnostics } = ctx;
3276
3887
  const { input, scenarioAssertions } = ctx;
3277
3888
  emitTerrainResidency(input.report.observations?.components?.terrain, assertions, diagnostics);
3278
3889
  if (scenarioAssertions.performance !== void 0) {
3890
+ const budget = frameBudget(scenarioAssertions.performance.maxFrameMsP95, classifyAdapter(input.report), scenarioAssertions.performance.maxFrameMsReason);
3279
3891
  const result = evaluatePerformanceAssertion(
3280
- scenarioAssertions.performance,
3892
+ budget.maxFrameMsP95 === void 0 ? scenarioAssertions.performance : { ...scenarioAssertions.performance, maxFrameMsP95: budget.maxFrameMsP95 },
3281
3893
  input.report.observations?.performanceSeries,
3282
- input.scenario.sourcePath
3894
+ input.scenario.sourcePath,
3895
+ { display: frameDisplay(), target: input.report.target, foreignGpu: foreignGpuProcesses(), ...gpuLane((input.report.observations?.console ?? []).map(({ text }) => text)) }
3283
3896
  );
3284
- assertions.push(...result.assertions);
3897
+ assertions.push(...result.assertions.map((row) => row.id === "performance.samples" || row.id === "performance.maxFrameMsP95" ? { ...row, details: { ...row.details, frameBudget: budget } } : row));
3285
3898
  diagnostics.push(...result.diagnostics);
3899
+ if (budget.unmeasurable === true) {
3900
+ assertions.push({ details: { frameBudget: budget }, id: "performance.maxFrameMsP95", pass: false });
3901
+ diagnostics.push({
3902
+ code: "TN_PLAYTEST_PERFORMANCE_UNMEASURABLE",
3903
+ message: `performance.maxFrameMsP95 cannot be judged: ${budget.reason}.`,
3904
+ observedRuntimePath: `${input.scenario.sourcePath ?? "playtest"}/observations.json/performanceSeries`,
3905
+ severity: "error",
3906
+ sourcePath: input.scenario.sourcePath,
3907
+ suggestion: "Run the scenario on a hardware GPU, or set maxFrameMsP95 with a maxFrameMsReason that names the adapter."
3908
+ });
3909
+ }
3286
3910
  }
3287
3911
  for (const assertion of scenarioAssertions.resources ?? []) {
3288
3912
  if (assertion.anyOf !== void 0) {
@@ -3326,7 +3950,7 @@ function emitPerfSignalsWorld(ctx) {
3326
3950
  const samples = assertion.atSteps.map((expected) => {
3327
3951
  const sample = (input.report.observations?.resourceSeries ?? []).find((candidate) => candidate.label === expected.label);
3328
3952
  const value = readPath(sample?.snapshots[assertion.id], assertion.path);
3329
- const pass2 = sample !== void 0 && (!Object.hasOwn(expected, "equals") || jsonEqual(value, expected.equals)) && (expected.textIncludes === void 0 || String(textValue(value)).includes(expected.textIncludes));
3953
+ 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));
3330
3954
  return { expected, pass: pass2, value };
3331
3955
  });
3332
3956
  const pass = samples.every((sample) => sample.pass);
@@ -3411,6 +4035,20 @@ function emitTerrainResidency(component, assertions, diagnostics) {
3411
4035
  suggestion: "Expose TerrainTiles.debug() through the terrain entity and inspect the residency counters."
3412
4036
  });
3413
4037
  }
4038
+ var FRAME_BUDGET_MS = 16.7;
4039
+ function frameBudget(explicit, adapter, reason) {
4040
+ const identity = {
4041
+ ...adapter.adapterClass === void 0 ? {} : { adapterClass: adapter.adapterClass },
4042
+ ...adapter.gpuFamily === void 0 ? {} : { gpuFamily: adapter.gpuFamily }
4043
+ };
4044
+ if (explicit !== void 0) {
4045
+ return { ...identity, maxFrameMsP95: explicit, reason: `maxFrameMsP95 set in the scenario overrides ${FRAME_BUDGET_MS} ms${reason === void 0 ? "" : `: ${reason}`}`, source: "scenario" };
4046
+ }
4047
+ if (adapter.adapterClass === "software") {
4048
+ return { ...identity, reason: `software adapter ${adapter.softwareAdapter ?? ""} is unmeasurable: it cannot carry a frame rate`.replace(" ", " "), source: "adapter", unmeasurable: true };
4049
+ }
4050
+ return { ...identity, maxFrameMsP95: FRAME_BUDGET_MS, reason: `one 60 Hz frame (${FRAME_BUDGET_MS} ms) on every tier`, source: "adapter" };
4051
+ }
3414
4052
 
3415
4053
  // src/evaluators/world-gameplay.ts
3416
4054
  function emitWorldGameplay(ctx) {
@@ -3936,173 +4574,6 @@ function emitWorldTopology(value, assertions, diagnostics) {
3936
4574
  }
3937
4575
  }
3938
4576
 
3939
- // src/runner/browser.ts
3940
- var WEBGPU_BROWSER_ARGS = [
3941
- "--ozone-platform=x11",
3942
- "--enable-unsafe-webgpu",
3943
- "--disable-gpu-sandbox",
3944
- "--ignore-gpu-blocklist",
3945
- // Keep Vulkan available on both hardware and software adapters.
3946
- "--enable-features=Vulkan",
3947
- // Forced ANGLE/Vulkan selects NVIDIA locally but breaks hosted software adapters, especially headed.
3948
- // Apply that workaround only when the caller explicitly requests the host display.
3949
- ...typeof process !== "undefined" && process.env.TN_PLAYTEST_HOST_DISPLAY === "1" ? ["--use-angle=vulkan", "--use-vulkan", "--disable-vulkan-surface"] : []
3950
- ];
3951
- var PERFORMANCE_BROWSER_ARGS = [
3952
- "--disable-frame-rate-limit",
3953
- "--disable-gpu-vsync"
3954
- ];
3955
- function resolveBrowserArguments(browserArgs) {
3956
- return [...browserArgs ?? []];
3957
- }
3958
- var SOFTWARE_ADAPTER = /swiftshader|llvmpipe|lavapipe|softwarerasterizer|software adapter|basic render/i;
3959
- function softwareAdapterName(adapter) {
3960
- if (adapter === void 0) return void 0;
3961
- for (const value of Object.values(adapter)) {
3962
- if (typeof value === "string" && SOFTWARE_ADAPTER.test(value)) return value;
3963
- }
3964
- return void 0;
3965
- }
3966
- function reconcileBrowserPointers(previous, next) {
3967
- const normalized = new Map(next.map((pointer) => [pointer.id, {
3968
- buttons: pointer.buttons ?? 1,
3969
- id: pointer.id,
3970
- x: pointer.x,
3971
- y: pointer.y
3972
- }]));
3973
- const previousPrimary = previous.keys().next().value;
3974
- const nextPrimary = normalized.keys().next().value;
3975
- const changes = [];
3976
- for (const pointer of previous.values()) {
3977
- if (!normalized.has(pointer.id)) {
3978
- changes.push({ isPrimary: pointer.id === previousPrimary, pointer: { ...pointer, buttons: 0 }, type: "pointerup" });
3979
- }
3980
- }
3981
- for (const pointer of normalized.values()) {
3982
- const old = previous.get(pointer.id);
3983
- if (old === void 0) {
3984
- changes.push({ isPrimary: pointer.id === nextPrimary, pointer, type: "pointerdown" });
3985
- } else if (old.x !== pointer.x || old.y !== pointer.y || old.buttons !== pointer.buttons) {
3986
- changes.push({ isPrimary: pointer.id === nextPrimary, pointer, type: "pointermove" });
3987
- }
3988
- }
3989
- return changes;
3990
- }
3991
-
3992
- // src/evaluators/adapter-class.ts
3993
- function classifyAdapter(report) {
3994
- const capture = report.capture;
3995
- if (capture === void 0 || capture.rendererKind !== "webgpu") return {};
3996
- if (adapterIdentity(capture.adapter) === void 0) return {};
3997
- const software = softwareAdapterName(capture.adapter);
3998
- if (software !== void 0) return { adapterClass: "software", softwareAdapter: software };
3999
- const gpuFamily = gpuFamilyOf(capture.adapter);
4000
- return gpuFamily === void 0 ? { adapterClass: "hardware" } : { adapterClass: "hardware", gpuFamily };
4001
- }
4002
- var ADAPTER_IDENTITY_KEYS = ["architecture", "description", "device", "vendor"];
4003
- function adapterIdentity(adapter) {
4004
- if (adapter === void 0) return void 0;
4005
- for (const key of ADAPTER_IDENTITY_KEYS) {
4006
- const value = adapter[key];
4007
- if (typeof value === "string" && value.trim() !== "") return value;
4008
- }
4009
- return void 0;
4010
- }
4011
- var MALI_MODEL = /\bmali[\s_-]*g?[\s-]*(\d{2,3})/i;
4012
- var ADRENO_MODEL = /\badreno\W*(?:tm\W*)?(\d)(\d\d|xx)/i;
4013
- var AMD_INTEGRATED = /radeon(?:\(tm\))?\s+(?:graphics|\d{3}m)\b/i;
4014
- var INTEL_DISCRETE = /\barc\b|xe2?-hpg|battlemage|alchemist/i;
4015
- var FAMILY_RULES = [
4016
- ({ architecture, description, device }) => {
4017
- const number = [description, device, architecture].map((value) => MALI_MODEL.exec(value)?.[1]).find((value) => value !== void 0);
4018
- if (number === void 0) return void 0;
4019
- const model = Number(number);
4020
- if (model >= 710) return "mobile-high";
4021
- return model < 57 || model === 71 || model === 72 ? "mobile-low" : "mobile-mid";
4022
- },
4023
- ({ architecture, vendor }) => {
4024
- if (!/\barm\b/i.test(vendor)) return void 0;
4025
- if (/midgard|bifrost/i.test(architecture)) return "mobile-low";
4026
- if (/valhall/i.test(architecture)) return "mobile-mid";
4027
- return /5th-?gen|immortalis/i.test(architecture) ? "mobile-high" : void 0;
4028
- },
4029
- ({ architecture, description, device }) => {
4030
- const match = [description, device, architecture].map((value) => ADRENO_MODEL.exec(value)).find((value) => value !== null && value !== void 0);
4031
- if (match === null || match === void 0) return void 0;
4032
- const generation = Number(match[1]);
4033
- if (generation <= 4) return "mobile-low";
4034
- if (generation === 5) return "mobile-mid";
4035
- if (generation === 6) return match[2] !== "xx" && Number(match[2]) >= 30 ? "mobile-high" : "mobile-mid";
4036
- return "mobile-high";
4037
- },
4038
- ({ architecture, description, device, vendor }) => /nvidia/i.test(vendor) && ![architecture, description, device].some((value) => /tegra/i.test(value)) ? "discrete" : void 0,
4039
- ({ architecture, description, device, vendor }) => {
4040
- if (!/intel/i.test(vendor)) return void 0;
4041
- return [architecture, description, device].some((value) => INTEL_DISCRETE.test(value)) ? "discrete" : "integrated";
4042
- },
4043
- // An APU and a card share an architecture name, so an AMD adapter that names no iGPU is `discrete`.
4044
- ({ description, vendor }) => /\b(?:amd|ati)\b/i.test(vendor) ? AMD_INTEGRATED.test(description) ? "integrated" : "discrete" : void 0
4045
- ];
4046
- function gpuFamilyOf(adapter) {
4047
- if (adapter === void 0) return void 0;
4048
- const field = (key) => {
4049
- const value = adapter[key];
4050
- return typeof value === "string" ? value : "";
4051
- };
4052
- const fields = {
4053
- architecture: field("architecture"),
4054
- description: field("description"),
4055
- device: field("device"),
4056
- vendor: field("vendor")
4057
- };
4058
- for (const rule of FAMILY_RULES) {
4059
- const family = rule(fields);
4060
- if (family !== void 0) return family;
4061
- }
4062
- return void 0;
4063
- }
4064
- function adapterFieldsFromIdentity(identity) {
4065
- if (typeof identity !== "string") return void 0;
4066
- const prefix = "webgpu:";
4067
- if (!identity.startsWith(prefix)) return void 0;
4068
- const fields = /* @__PURE__ */ Object.create(null);
4069
- for (const pair of identity.slice(prefix.length).split("|")) {
4070
- const separator = pair.indexOf("=");
4071
- if (separator <= 0) return void 0;
4072
- const key = pair.slice(0, separator);
4073
- if (!ADAPTER_IDENTITY_KEYS.includes(key) || Object.hasOwn(fields, key)) {
4074
- return void 0;
4075
- }
4076
- let value;
4077
- try {
4078
- value = decodeURIComponent(pair.slice(separator + 1));
4079
- } catch {
4080
- return void 0;
4081
- }
4082
- if (value.trim() === "") return void 0;
4083
- fields[key] = value;
4084
- }
4085
- if (Object.keys(fields).length === 0) return void 0;
4086
- return fields;
4087
- }
4088
- function nativeCaptureProvenance(census, target, viewport) {
4089
- if (census === void 0 || census === null || typeof census !== "object" || Array.isArray(census)) return void 0;
4090
- const adapterRecord = census.adapter;
4091
- if (adapterRecord === void 0 || adapterRecord === null || typeof adapterRecord !== "object" || Array.isArray(adapterRecord)) return void 0;
4092
- const adapter = adapterFieldsFromIdentity(adapterRecord.identity);
4093
- if (adapter === void 0) return void 0;
4094
- return {
4095
- adapter,
4096
- // A native launch carries no browser command line; there is no argument list to report and
4097
- // inventing one would be a flag nobody can check.
4098
- browserArgs: [],
4099
- captureMethod: "device.screenshot",
4100
- rendererKind: "webgpu",
4101
- target,
4102
- viewport
4103
- };
4104
- }
4105
-
4106
4577
  // src/evaluators/render-chain.ts
4107
4578
  function emitRenderChain(ctx) {
4108
4579
  const assertion = ctx.scenarioAssertions.renderChain;
@@ -4524,6 +4995,344 @@ function emitPerNode(ctx, id, index, bound, observation, sampled, expected, read
4524
4995
  });
4525
4996
  }
4526
4997
 
4998
+ // src/evaluators/foot-slip.ts
4999
+ var FOOT_SLIP_MIN_TRAVEL_M = 0.5;
5000
+ var FOOT_SLIP_CONTACT_BAND = 0.25;
5001
+ var MIN_CONTACT_PAIRS = 4;
5002
+ var DEFAULT_STEP_SECONDS = 1 / 60;
5003
+ function measureFootSlip(observation, stepSeconds = DEFAULT_STEP_SECONDS) {
5004
+ const { samples } = observation;
5005
+ let travel = 0;
5006
+ for (let index = 1; index < samples.length; index += 1) {
5007
+ const before = samples[index - 1].body;
5008
+ const after = samples[index].body;
5009
+ if (before !== null && after !== null) travel += Math.hypot(after[0] - before[0], after[2] - before[2]);
5010
+ }
5011
+ if (samples.length < 2 || samples.some(({ body }) => body === null))
5012
+ return { feet: [], travel, unobserved: `the subject '${observation.entity}' was not reported on every tick` };
5013
+ const missing = observation.feet.filter((_name, foot) => samples.some((sample) => sample.feet[foot] === null));
5014
+ if (missing.length > 0)
5015
+ 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` };
5016
+ if (travel < FOOT_SLIP_MIN_TRAVEL_M)
5017
+ 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` };
5018
+ const feet = observation.feet.map((name, foot) => {
5019
+ const heights = samples.map((sample) => sample.feet[foot][1] - sample.body[1]);
5020
+ const low = Math.min(...heights);
5021
+ const lift = Math.max(...heights) - low;
5022
+ const planted = heights.map((height) => height <= low + FOOT_SLIP_CONTACT_BAND * lift);
5023
+ let footTravel = 0;
5024
+ let bodyTravel = 0;
5025
+ let contactPairs = 0;
5026
+ for (let index = 1; index < samples.length; index += 1) {
5027
+ if (!planted[index - 1] || !planted[index]) continue;
5028
+ const [fx0, , fz0] = samples[index - 1].feet[foot];
5029
+ const [fx1, , fz1] = samples[index].feet[foot];
5030
+ const [bx0, , bz0] = samples[index - 1].body;
5031
+ const [bx1, , bz1] = samples[index].body;
5032
+ footTravel += Math.hypot(fx1 - fx0, fz1 - fz0);
5033
+ bodyTravel += Math.hypot(bx1 - bx0, bz1 - bz0);
5034
+ contactPairs += 1;
5035
+ }
5036
+ return {
5037
+ contactPairs,
5038
+ lift,
5039
+ name,
5040
+ ...contactPairs < MIN_CONTACT_PAIRS || bodyTravel <= 0 ? {} : { slip: footTravel / bodyTravel, speed: footTravel / (contactPairs * stepSeconds) }
5041
+ };
5042
+ });
5043
+ return { feet, travel };
5044
+ }
5045
+ function emitFootSlip(ctx) {
5046
+ const assertions = ctx.scenarioAssertions.footSlip;
5047
+ if (assertions === void 0 || assertions.length === 0) return;
5048
+ assertions.forEach((assertion, index) => {
5049
+ const id = `footSlip[${index}]`;
5050
+ const observation = ctx.input.report.observations?.footSlip?.find(({ label }) => label === assertion.atStep);
5051
+ const measure = observation === void 0 ? void 0 : measureFootSlip(observation, assertion.stepSeconds);
5052
+ const unmeasured = measure?.feet.find(({ slip }) => slip === void 0);
5053
+ 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`);
5054
+ if (reason !== void 0) {
5055
+ ctx.assertions.push({ details: { atStep: assertion.atStep, reason, ...measure === void 0 ? {} : { travel: measure.travel } }, id: `${id}.observed`, pass: false });
5056
+ ctx.diagnostics.push({
5057
+ code: "TN_PLAYTEST_FOOT_SLIP_UNOBSERVED",
5058
+ message: `footSlip at '${assertion.atStep}' was not measured: ${reason}.`,
5059
+ observedRuntimePath: "observations.json/footSlip",
5060
+ severity: "error",
5061
+ 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."
5062
+ });
5063
+ return;
5064
+ }
5065
+ const animation = runtimeGameplaySamples(ctx.input.report.observations?.runtimeObservations).find(({ label }) => label === assertion.atStep)?.gameplay.animation;
5066
+ const stride = isRecord(animation) ? strideReading(animation[observation.entity]) : void 0;
5067
+ if (stride !== void 0 && strideHasNoFootPlant(stride)) {
5068
+ ctx.assertions.push({ details: { atStep: assertion.atStep, reason: NO_FOOT_PLANT_DETAIL, stride, travel: measure.travel }, id: `${id}.observed`, pass: false });
5069
+ ctx.diagnostics.push({
5070
+ code: "TN_PLAYTEST_STRIDE_NO_FOOT_PLANT",
5071
+ message: `footSlip at '${assertion.atStep}' failed closed: ${NO_FOOT_PLANT_DETAIL}.`,
5072
+ observedRuntimePath: "observations.json/runtimeObservations",
5073
+ severity: "error",
5074
+ 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."
5075
+ });
5076
+ return;
5077
+ }
5078
+ const worst = Math.max(...measure.feet.map(({ slip }) => slip));
5079
+ const worstSpeed = Math.max(...measure.feet.map(({ speed }) => speed));
5080
+ const slipPass = assertion.maxSlip === void 0 || worst <= assertion.maxSlip;
5081
+ const speedPass = assertion.maxSlideSpeed === void 0 || worstSpeed <= assertion.maxSlideSpeed;
5082
+ ctx.assertions.push({
5083
+ details: {
5084
+ atStep: assertion.atStep,
5085
+ expected: { maxSlideSpeed: assertion.maxSlideSpeed, maxSlip: assertion.maxSlip },
5086
+ feet: measure.feet,
5087
+ travel: measure.travel,
5088
+ worst,
5089
+ worstSpeed
5090
+ },
5091
+ id: `${id}.slip`,
5092
+ pass: slipPass && speedPass
5093
+ });
5094
+ if (!slipPass)
5095
+ ctx.diagnostics.push({
5096
+ code: "TN_PLAYTEST_FOOT_SLIP",
5097
+ message: `A planted foot travelled ${worst.toFixed(2)} m per metre of body travel at '${assertion.atStep}', ceiling ${assertion.maxSlip}.`,
5098
+ observedRuntimePath: "observations.json/footSlip",
5099
+ severity: "error",
5100
+ 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."
5101
+ });
5102
+ if (!speedPass)
5103
+ ctx.diagnostics.push({
5104
+ code: "TN_PLAYTEST_FOOT_SLIP",
5105
+ message: `A planted foot slid at ${worstSpeed.toFixed(2)} m/s at '${assertion.atStep}', ceiling ${assertion.maxSlideSpeed} m/s.`,
5106
+ observedRuntimePath: "observations.json/footSlip",
5107
+ severity: "error",
5108
+ 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."
5109
+ });
5110
+ });
5111
+ }
5112
+
5113
+ // src/evaluators/sight-line.ts
5114
+ var MAX_BLOCKER_NAMES = 5;
5115
+ function topBlockers(blockers) {
5116
+ const counts = /* @__PURE__ */ new Map();
5117
+ for (const name of blockers) counts.set(name, (counts.get(name) ?? 0) + 1);
5118
+ return [...counts.entries()].sort(([leftName, leftCount], [rightName, rightCount]) => rightCount - leftCount || leftName.localeCompare(rightName)).slice(0, MAX_BLOCKER_NAMES).map(([name]) => name);
5119
+ }
5120
+ function emitSightLine(ctx) {
5121
+ const assertion = ctx.scenarioAssertions.sightLine;
5122
+ if (assertion === void 0) return;
5123
+ const observation = ctx.input.report.observations?.sightLine;
5124
+ const samples = observation?.samples ?? [];
5125
+ if (samples.length === 0) {
5126
+ ctx.assertions.push({ details: { samples: 0 }, id: "sightLine.observed", pass: false });
5127
+ ctx.diagnostics.push({
5128
+ code: "TN_PLAYTEST_SIGHT_LINE_UNOBSERVED",
5129
+ message: "A sightLine assertion was evaluated against a run that sampled no camera-to-subject sight line.",
5130
+ observedRuntimePath: "observations.json/sightLine",
5131
+ severity: "error",
5132
+ suggestion: "Run on the browser target and make sure the scenario advances at least one step whose subject is registered with the bridge."
5133
+ });
5134
+ return;
5135
+ }
5136
+ const blockedCount = samples.filter(({ blocked }) => blocked).length;
5137
+ const ratio = blockedCount / samples.length;
5138
+ const pass = ratio <= assertion.maxBlockedRatio;
5139
+ const blockers = topBlockers(samples.flatMap((sample) => sample.blockers));
5140
+ ctx.assertions.push({
5141
+ details: { blocked: blockedCount, blockers, ratio, samples: samples.length },
5142
+ id: "sightLine",
5143
+ pass
5144
+ });
5145
+ if (!pass) {
5146
+ ctx.diagnostics.push({
5147
+ code: "TN_PLAYTEST_SIGHT_LINE_BLOCKED",
5148
+ message: `Solid geometry blocked the camera's view of '${observation.entity}' on ${blockedCount} of ${samples.length} samples (${(ratio * 100).toFixed(1)}%), ceiling ${assertion.maxBlockedRatio}.`,
5149
+ observedRuntimePath: "observations.json/sightLine",
5150
+ severity: "error",
5151
+ 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."
5152
+ });
5153
+ }
5154
+ }
5155
+
5156
+ // src/evaluators/hud-audit.ts
5157
+ var MAX_OFFENDERS = 5;
5158
+ var JUDGED_BACKGROUND_ALPHA = 0.5;
5159
+ var DEVELOPER_TEXT = /\b(debug|todo|fixme|lorem ipsum|placeholder|probe|raycast|hitbox|wall ray)\b/iu;
5160
+ var UNRESOLVED_TEXT = /\b(undefined|null|NaN)\b/u;
5161
+ var COERCED_OBJECT = /\[object /u;
5162
+ function channelLuminance(channel) {
5163
+ const value = channel / 255;
5164
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
5165
+ }
5166
+ function relativeLuminance([red, green, blue]) {
5167
+ return 0.2126 * channelLuminance(red) + 0.7152 * channelLuminance(green) + 0.0722 * channelLuminance(blue);
5168
+ }
5169
+ function contrastRatio(foreground, background) {
5170
+ const alpha = Math.min(Math.max(foreground[3], 0), 1);
5171
+ const composited = [
5172
+ foreground[0] * alpha + background[0] * (1 - alpha),
5173
+ foreground[1] * alpha + background[1] * (1 - alpha),
5174
+ foreground[2] * alpha + background[2] * (1 - alpha),
5175
+ 1
5176
+ ];
5177
+ const first = relativeLuminance(composited);
5178
+ const second = relativeLuminance(background);
5179
+ return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
5180
+ }
5181
+ function readsAsDeveloperText(text) {
5182
+ return DEVELOPER_TEXT.test(text) || UNRESOLVED_TEXT.test(text) || COERCED_OBJECT.test(text);
5183
+ }
5184
+ function offenders(items) {
5185
+ return items.slice(0, MAX_OFFENDERS).map(({ selector, text }) => ({ selector, text }));
5186
+ }
5187
+ function emitHudAudit(ctx) {
5188
+ const assertion = ctx.scenarioAssertions.hudAudit;
5189
+ if (assertion === void 0) return;
5190
+ const items = ctx.input.report.observations?.hudAudit?.items ?? [];
5191
+ if (items.length === 0) {
5192
+ ctx.assertions.push({ details: { items: 0 }, id: "hudAudit.observed", pass: false });
5193
+ ctx.diagnostics.push({
5194
+ code: "TN_PLAYTEST_HUD_AUDIT_UNOBSERVED",
5195
+ message: "A hudAudit assertion was evaluated against a run that reported no visible page text.",
5196
+ observedRuntimePath: "observations.json/hudAudit",
5197
+ severity: "error",
5198
+ suggestion: "Run on the browser target and make sure the page draws player-facing text in the DOM, outside a canvas."
5199
+ });
5200
+ return;
5201
+ }
5202
+ if (assertion.noDebugText === true) {
5203
+ const found = items.filter(({ text }) => readsAsDeveloperText(text));
5204
+ const pass = found.length === 0;
5205
+ ctx.assertions.push({
5206
+ details: { checked: items.length, offenders: offenders(found) },
5207
+ id: "hudAudit.debugText",
5208
+ pass
5209
+ });
5210
+ if (!pass) {
5211
+ ctx.diagnostics.push({
5212
+ code: "TN_PLAYTEST_HUD_DEBUG_TEXT",
5213
+ 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(", ")}.`,
5214
+ observedRuntimePath: "observations.json/hudAudit/items",
5215
+ severity: "error",
5216
+ suggestion: "Replace debug, TODO, placeholder and unresolved values with the copy the player should read, then rerun the scenario."
5217
+ });
5218
+ }
5219
+ }
5220
+ if (assertion.minContrast !== void 0) {
5221
+ const judged = items.filter(({ background }) => background[3] >= JUDGED_BACKGROUND_ALPHA);
5222
+ const unjudged = items.length - judged.length;
5223
+ 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);
5224
+ const pass = worst.every(({ ratio }) => ratio >= assertion.minContrast);
5225
+ ctx.assertions.push({
5226
+ details: { judged: judged.length, minContrast: assertion.minContrast, unjudged, worst },
5227
+ id: "hudAudit.contrast",
5228
+ pass
5229
+ });
5230
+ if (!pass) {
5231
+ ctx.diagnostics.push({
5232
+ code: "TN_PLAYTEST_HUD_CONTRAST",
5233
+ 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(", ")}.`,
5234
+ observedRuntimePath: "observations.json/hudAudit/items",
5235
+ severity: "error",
5236
+ suggestion: "Raise the text colour's contrast against its backing plate, or darken the plate, until every judged item reaches the floor."
5237
+ });
5238
+ }
5239
+ }
5240
+ }
5241
+
5242
+ // src/evaluators/engine-cost.ts
5243
+ var FRAME_BUDGET_MARKER = "TN_FRAME_BUDGET:";
5244
+ var BRIDGE_CENSUS_MARKER = "TN_BRIDGE_CENSUS:";
5245
+ function engineCostWindows(lines) {
5246
+ const windows = [];
5247
+ let top;
5248
+ for (const line of lines) {
5249
+ if (typeof line !== "string") continue;
5250
+ const census = line.indexOf(BRIDGE_CENSUS_MARKER);
5251
+ if (census !== -1) {
5252
+ try {
5253
+ top = JSON.parse(line.slice(census + BRIDGE_CENSUS_MARKER.length)).top;
5254
+ } catch {
5255
+ top = void 0;
5256
+ }
5257
+ continue;
5258
+ }
5259
+ const at = line.indexOf(FRAME_BUDGET_MARKER);
5260
+ if (at === -1) continue;
5261
+ try {
5262
+ const report = JSON.parse(line.slice(at + FRAME_BUDGET_MARKER.length));
5263
+ const engine = report.counters?.engine;
5264
+ if (engine === void 0) continue;
5265
+ if (engine === null || typeof engine !== "object" || Array.isArray(engine)) throw new Error("invalid engine counters");
5266
+ const series = {
5267
+ ...engine,
5268
+ ...report.counters?.bridgeCrossings === void 0 ? {} : { bridgeCrossings: report.counters.bridgeCrossings }
5269
+ };
5270
+ for (const summary of Object.values(series)) {
5271
+ if (summary === null || typeof summary !== "object" || !Number.isFinite(summary.mean) || summary.mean < 0 || !Number.isFinite(summary.max) || summary.max < 0 || !Number.isSafeInteger(summary.samples) || summary.samples < 1) throw new Error("unmeasured engine counter");
5272
+ }
5273
+ const pick = (field) => Object.fromEntries(Object.entries(series).map(([name, summary]) => [name, summary[field]]));
5274
+ windows.push({ maxFrame: pick("max"), perFrame: pick("mean"), top, ...report.window === void 0 ? {} : { window: report.window } });
5275
+ } catch {
5276
+ windows.push(void 0);
5277
+ }
5278
+ }
5279
+ return windows;
5280
+ }
5281
+ function topCaller(window2) {
5282
+ const top = window2.top?.[0];
5283
+ return top === void 0 ? "no census before this window" : `${top.name ?? "?"} ${top.perFrame ?? "?"}/frame from ${top.caller ?? "unknown"}`;
5284
+ }
5285
+ function emitEngineCost(ctx) {
5286
+ const assertion = ctx.scenarioAssertions.engineCost;
5287
+ if (assertion === void 0) return;
5288
+ const windows = engineCostWindows((ctx.input.report.observations?.console ?? []).map(({ text }) => text));
5289
+ const stillWindows = assertion.still?.windows ?? 0;
5290
+ const skipped = assertion.skipWindows ?? 0;
5291
+ const needed = Math.max(assertion.minWindows ?? 1, skipped + stillWindows + (assertion.moving === void 0 ? 0 : 1));
5292
+ const readable = windows.filter((window2) => window2 !== void 0);
5293
+ const observed = readable.length >= needed && readable.length === windows.length;
5294
+ ctx.assertions.push({ details: { windows: windows.length, unreadable: windows.length - readable.length, needed }, id: "engineCost.observed", pass: observed });
5295
+ if (!observed) {
5296
+ ctx.diagnostics.push({
5297
+ code: "TN_PLAYTEST_ENGINE_COST_UNOBSERVED",
5298
+ message: `engineCost needs ${needed} readable TN_FRAME_BUDGET window(s) with counters.engine; the run printed ${windows.length}, ${windows.length - readable.length} unreadable.`,
5299
+ observedRuntimePath: "observations.json/console",
5300
+ severity: "error",
5301
+ 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."
5302
+ });
5303
+ return;
5304
+ }
5305
+ const bounded = readable.slice(skipped);
5306
+ for (const [kind, table, scope, windows2] of [
5307
+ ["perFrame", assertion.maxPerFrame, "maxPerFrame", bounded],
5308
+ ["maxFrame", assertion.maxInFrame, "maxInFrame", bounded],
5309
+ ["perFrame", assertion.still?.maxPerFrame, "still.maxPerFrame", bounded.slice(0, stillWindows)],
5310
+ ["perFrame", assertion.moving?.maxPerFrame, "moving.maxPerFrame", bounded.slice(stillWindows)],
5311
+ ["maxFrame", assertion.moving?.maxInFrame, "moving.maxInFrame", bounded.slice(stillWindows)]
5312
+ ]) {
5313
+ for (const [name, bound] of Object.entries(table ?? {})) {
5314
+ const values = windows2.map((window2) => window2[kind]?.[name]);
5315
+ const missing = values.findIndex((value2) => typeof value2 !== "number" || !Number.isFinite(value2));
5316
+ const worst = windows2.reduce(
5317
+ (top, window2) => (window2[kind]?.[name] ?? -1) > (top?.[kind]?.[name] ?? -1) ? window2 : top,
5318
+ void 0
5319
+ );
5320
+ const value = worst?.[kind]?.[name] ?? Number.NaN;
5321
+ const pass = missing === -1 && value <= bound;
5322
+ const id = `engineCost.${scope}.${name}`;
5323
+ ctx.assertions.push({ details: { bound, value, window: worst?.window, source: assertion.source }, id, pass });
5324
+ if (pass) continue;
5325
+ ctx.diagnostics.push({
5326
+ code: "TN_PLAYTEST_ENGINE_COST_OVER_BOUND",
5327
+ 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)}.`,
5328
+ observedRuntimePath: "observations.json/console",
5329
+ severity: "error",
5330
+ 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."
5331
+ });
5332
+ }
5333
+ }
5334
+ }
5335
+
4527
5336
  // src/runner/sceneRoom.ts
4528
5337
  var LIT_MATERIAL_PATTERN = /standard|physical|lambert|phong|toon/iu;
4529
5338
  function summariseRoom(scene) {
@@ -4645,12 +5454,47 @@ function emitScene(ctx) {
4645
5454
  }
4646
5455
 
4647
5456
  // src/evaluators/startup.ts
5457
+ var MB = 1e6;
5458
+ var mb = (bytes) => `${(bytes / MB).toFixed(1)} MB`;
5459
+ function emitOffscreenBytes(ctx) {
5460
+ const ceiling = ctx.scenarioAssertions.startup?.maxOffscreenBytes;
5461
+ const observed = ctx.input.report.observations?.startup?.offscreenBytes;
5462
+ const unsized = observed !== void 0 && observed.awaitedBytes === 0 && observed.unsizedFiles > 0;
5463
+ if (ceiling !== void 0) {
5464
+ const measured = observed !== void 0 && !unsized;
5465
+ const pass = measured && observed.offscreenBytes <= ceiling;
5466
+ ctx.assertions.push({
5467
+ details: { expected: ceiling, observed: measured ? observed.offscreenBytes : void 0 },
5468
+ id: "startup.offscreenBytes",
5469
+ pass
5470
+ });
5471
+ if (!pass) {
5472
+ ctx.diagnostics.push({
5473
+ code: measured ? "TN_PLAYTEST_STARTUP_OFFSCREEN_BYTES" : "TN_PLAYTEST_STARTUP_UNOBSERVABLE",
5474
+ 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.`,
5475
+ observedRuntimePath: "observations.json/startup/offscreenBytes",
5476
+ severity: "error",
5477
+ 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."
5478
+ });
5479
+ return;
5480
+ }
5481
+ }
5482
+ if (observed?.warn !== true) return;
5483
+ ctx.diagnostics.push({
5484
+ code: "TN_PLAYTEST_STARTUP_OFFSCREEN_BYTES",
5485
+ 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(", ")}).`,
5486
+ observedRuntimePath: "observations.json/startup/offscreenBytes",
5487
+ severity: "warning",
5488
+ suggestion: observed.fix
5489
+ });
5490
+ }
4648
5491
  var MILESTONES = {
4649
5492
  maxCompileSettledMs: "compileSettledMs",
4650
5493
  maxEnteredMs: "enteredMs",
4651
5494
  maxReadyMs: "readyMs"
4652
5495
  };
4653
5496
  function emitStartup(ctx) {
5497
+ emitOffscreenBytes(ctx);
4654
5498
  const assertion = ctx.scenarioAssertions.startup;
4655
5499
  if (assertion === void 0) return;
4656
5500
  const timeline = ctx.input.report.observations?.startup?.timeline;
@@ -4673,6 +5517,28 @@ function emitStartup(ctx) {
4673
5517
  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."
4674
5518
  });
4675
5519
  }
5520
+ if (assertion.steadyCover === true) emitSteadyCover(ctx);
5521
+ }
5522
+ function emitSteadyCover(ctx) {
5523
+ const cover = ctx.input.report.observations?.startup?.cover;
5524
+ const observed = cover !== void 0 && cover.frames > 0 && cover.worldMs !== void 0;
5525
+ const uiOverCover = cover?.uiOverCover ?? [];
5526
+ const pass = observed && cover.differing.length === 0 && uiOverCover.length === 0;
5527
+ ctx.assertions.push({
5528
+ 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 },
5529
+ id: "startup.steadyCover",
5530
+ pass
5531
+ });
5532
+ if (pass) return;
5533
+ const first = cover?.differing[0];
5534
+ const ui = uiOverCover[0];
5535
+ ctx.diagnostics.push({
5536
+ code: !observed ? "TN_PLAYTEST_STARTUP_COVER_UNOBSERVED" : first === void 0 && ui !== void 0 ? "TN_PLAYTEST_STARTUP_UI_OVER_COVER" : "TN_PLAYTEST_STARTUP_COVER_BROKEN",
5537
+ 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.",
5538
+ observedRuntimePath: "observations.json/startup/cover",
5539
+ severity: "error",
5540
+ 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."
5541
+ });
4676
5542
  }
4677
5543
 
4678
5544
  // src/runner/pipeline-summary.ts
@@ -5880,6 +6746,10 @@ function evaluateRichPlaytestAssertions(input) {
5880
6746
  emitPipelineCensus(ctx);
5881
6747
  emitScene(ctx);
5882
6748
  emitSceneNodes(ctx);
6749
+ emitFootSlip(ctx);
6750
+ emitSightLine(ctx);
6751
+ emitHudAudit(ctx);
6752
+ emitEngineCost(ctx);
5883
6753
  if (scenarioAssertions.geometry !== void 0) {
5884
6754
  const observed = input.report.observations?.geometry;
5885
6755
  const status = observed?.status;
@@ -6385,6 +7255,7 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
6385
7255
  }),
6386
7256
  "performance": Object.freeze({
6387
7257
  "maxFrameMsP95": (value) => typeof value === "number" && Number.isFinite(value),
7258
+ "maxFrameMsReason": (value) => typeof value === "string" && value.trim() !== "",
6388
7259
  "minFps": (value) => typeof value === "number" && Number.isFinite(value),
6389
7260
  "maxPhaseMsP95": (value) => isRecord2(value),
6390
7261
  "maxDrawCalls": (value) => typeof value === "number" && Number.isFinite(value),
@@ -6442,6 +7313,7 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
6442
7313
  "animation": Object.freeze({
6443
7314
  "entity": (value) => typeof value === "string" && value.trim() !== "",
6444
7315
  "clip": (value) => typeof value === "string" && value.trim() !== "",
7316
+ "atStep": (value) => typeof value === "string" && value.trim() !== "",
6445
7317
  "entered": (value) => typeof value === "boolean",
6446
7318
  "advancedFrames": (value) => typeof value === "number" && Number.isFinite(value),
6447
7319
  "finished": (value) => typeof value === "boolean",
@@ -6466,6 +7338,31 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
6466
7338
  "maxCount": (value) => typeof value === "number" && Number.isFinite(value),
6467
7339
  "minTriangles": (value) => typeof value === "number" && Number.isFinite(value)
6468
7340
  }),
7341
+ "footSlip": Object.freeze({
7342
+ "atStep": (value) => typeof value === "string" && value.trim() !== "",
7343
+ "feet": (value) => Array.isArray(value),
7344
+ "maxSlip": (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
7345
+ "maxSlideSpeed": (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
7346
+ "stepSeconds": (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
7347
+ "entity": (value) => typeof value === "string" && value.trim() !== ""
7348
+ }),
7349
+ "sightLine": Object.freeze({
7350
+ "entity": (value) => typeof value === "string" && value.trim() !== "",
7351
+ "maxBlockedRatio": (value) => typeof value === "number" && Number.isFinite(value)
7352
+ }),
7353
+ "engineCost": Object.freeze({
7354
+ "maxPerFrame": (value) => isRecord2(value),
7355
+ "maxInFrame": (value) => isRecord2(value),
7356
+ "minWindows": (value) => typeof value === "number" && Number.isInteger(value) && value > 0,
7357
+ "skipWindows": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
7358
+ "still": (value) => isRecord2(value),
7359
+ "moving": (value) => isRecord2(value),
7360
+ "source": (value) => typeof value === "string" && value.trim() !== ""
7361
+ }),
7362
+ "hudAudit": Object.freeze({
7363
+ "minContrast": (value) => typeof value === "number" && Number.isFinite(value),
7364
+ "noDebugText": (value) => value === true
7365
+ }),
6469
7366
  "causedBy": Object.freeze({
6470
7367
  "cause": (value) => isRecord2(value),
6471
7368
  "effect": (value) => isRecord2(value),
@@ -6475,7 +7372,9 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
6475
7372
  "startup": Object.freeze({
6476
7373
  "maxEnteredMs": (value) => typeof value === "number" && Number.isFinite(value),
6477
7374
  "maxCompileSettledMs": (value) => typeof value === "number" && Number.isFinite(value),
6478
- "maxReadyMs": (value) => typeof value === "number" && Number.isFinite(value)
7375
+ "maxReadyMs": (value) => typeof value === "number" && Number.isFinite(value),
7376
+ "maxOffscreenBytes": (value) => typeof value === "number" && Number.isFinite(value),
7377
+ "steadyCover": (value) => typeof value === "boolean"
6479
7378
  }),
6480
7379
  "pipelineCensus": Object.freeze({
6481
7380
  "maxNodeBuildsAfterWarmUpSettled": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
@@ -6507,6 +7406,9 @@ function validateVisualAssertion(value, scenarioPath, objectPath) {
6507
7406
  if (authoredEdge !== void 0) {
6508
7407
  throw invalidScenario(scenarioPath, `'${objectPath}.region.${authoredEdge}' cannot be combined with an element-bound region; the element supplies its bounds.`);
6509
7408
  }
7409
+ if (hasKey(regionRecord, "minSharpness")) {
7410
+ throw invalidScenario(scenarioPath, `'${objectPath}.region.minSharpness' measures the rendered frame; bound a static x/y/width/height region instead of an element.`);
7411
+ }
6510
7412
  region = {
6511
7413
  element,
6512
7414
  ...present("maxDarkPixelRatio", optionalRatio(regionRecord, "maxDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
@@ -6525,6 +7427,7 @@ function validateVisualAssertion(value, scenarioPath, objectPath) {
6525
7427
  }
6526
7428
  region = {
6527
7429
  ...edges,
7430
+ ...present("minSharpness", optionalPositiveNumber(regionRecord, "minSharpness", scenarioPath, `${objectPath}.region`)),
6528
7431
  ...present("maxDarkPixelRatio", optionalRatio(regionRecord, "maxDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
6529
7432
  ...present("maxLuminance", optionalRatio(regionRecord, "maxLuminance", scenarioPath, `${objectPath}.region`)),
6530
7433
  ...present("minDarkPixelRatio", optionalRatio(regionRecord, "minDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
@@ -6726,18 +7629,30 @@ function validateDeviceMetricsAssertion(value, scenarioPath, objectPath) {
6726
7629
  }
6727
7630
  return assertion;
6728
7631
  }
7632
+ var LEGACY_SCAFFOLD_FRAME_MS = 33;
7633
+ var 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.";
6729
7634
  function validatePerformanceAssertion(value, scenarioPath, objectPath) {
6730
7635
  const record4 = requireRecord(value, scenarioPath, objectPath);
6731
- rejectUnknownKeys(record4, ["maxDrawCalls", "maxFrameMsP95", "maxPassDrawCalls", "maxPassTriangles", "maxPhaseMsP95", "maxTriangles", "minFps"], scenarioPath, objectPath);
7636
+ rejectUnknownKeys(record4, ["maxDrawCalls", "maxFrameMsP95", "maxFrameMsReason", "maxPassDrawCalls", "maxPassTriangles", "maxPhaseMsP95", "maxTriangles", "minFps"], scenarioPath, objectPath);
6732
7637
  const assertion = {
6733
7638
  ...present("maxDrawCalls", optionalNonNegativeNumber(record4, "maxDrawCalls", scenarioPath, objectPath)),
6734
7639
  ...present("maxFrameMsP95", optionalNonNegativeNumber(record4, "maxFrameMsP95", scenarioPath, objectPath)),
7640
+ ...present("maxFrameMsReason", optionalString(record4, "maxFrameMsReason", scenarioPath, objectPath)),
6735
7641
  ...present("maxPassDrawCalls", validatePassBudget(record4.maxPassDrawCalls, scenarioPath, `${objectPath}.maxPassDrawCalls`)),
6736
7642
  ...present("maxPassTriangles", validatePassBudget(record4.maxPassTriangles, scenarioPath, `${objectPath}.maxPassTriangles`)),
6737
7643
  ...present("maxPhaseMsP95", validatePhaseBudget(record4.maxPhaseMsP95, scenarioPath, `${objectPath}.maxPhaseMsP95`)),
6738
7644
  ...present("maxTriangles", optionalNonNegativeNumber(record4, "maxTriangles", scenarioPath, objectPath)),
6739
7645
  ...present("minFps", optionalNonNegativeNumber(record4, "minFps", scenarioPath, objectPath))
6740
7646
  };
7647
+ if (assertion.maxFrameMsP95 === LEGACY_SCAFFOLD_FRAME_MS && record4.maxFrameMsReason === void 0) {
7648
+ return { ...assertion, maxFrameMsReason: LEGACY_SCAFFOLD_FRAME_REASON };
7649
+ }
7650
+ if (assertion.maxFrameMsP95 !== void 0 && assertion.maxFrameMsP95 > 16.7 && (assertion.maxFrameMsReason ?? "").trim() === "") {
7651
+ throw invalidScenario(
7652
+ scenarioPath,
7653
+ `'${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.`
7654
+ );
7655
+ }
6741
7656
  if (Object.keys(assertion).length === 0) {
6742
7657
  throw invalidScenario(
6743
7658
  scenarioPath,
@@ -6899,8 +7814,21 @@ function validateStartupAssertion(value, scenarioPath, objectPath) {
6899
7814
  }
6900
7815
  result[key] = ceiling;
6901
7816
  }
7817
+ const bytes = record4.maxOffscreenBytes;
7818
+ if (bytes !== void 0) {
7819
+ if (typeof bytes !== "number" || !Number.isInteger(bytes) || bytes < 0) {
7820
+ throw invalidScenario(scenarioPath, `'${objectPath}.maxOffscreenBytes' must be a non-negative integer number of bytes, received ${describeValue(bytes)}.`);
7821
+ }
7822
+ result.maxOffscreenBytes = bytes;
7823
+ }
7824
+ if (record4.steadyCover !== void 0) {
7825
+ if (record4.steadyCover !== true) {
7826
+ throw invalidScenario(scenarioPath, `'${objectPath}.steadyCover' must be true, received ${describeValue(record4.steadyCover)}; leave it out to skip the check.`);
7827
+ }
7828
+ result.steadyCover = true;
7829
+ }
6902
7830
  if (Object.keys(result).length === 0) {
6903
- throw invalidScenario(scenarioPath, `'${objectPath}' must set at least one of ${STARTUP_CEILINGS.join(", ")}; an empty startup assertion observes nothing.`);
7831
+ throw invalidScenario(scenarioPath, `'${objectPath}' must set at least one of ${[...STARTUP_CEILINGS, "maxOffscreenBytes", "steadyCover"].join(", ")}; an empty startup assertion observes nothing.`);
6904
7832
  }
6905
7833
  return result;
6906
7834
  }
@@ -7209,12 +8137,116 @@ function validateSceneNodesAssertion(value, scenarioPath, objectPath) {
7209
8137
  );
7210
8138
  return result;
7211
8139
  }
8140
+ function validateFootSlipAssertion(value, scenarioPath, objectPath) {
8141
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8142
+ rejectUnknownKeys(record4, ["atStep", "entity", "feet", "maxSlideSpeed", "maxSlip", "stepSeconds"], scenarioPath, objectPath);
8143
+ const feet = record4.feet;
8144
+ if (!Array.isArray(feet) || feet.length === 0 || feet.some((foot) => typeof foot !== "string" || foot.trim() === "") || new Set(feet).size !== feet.length)
8145
+ throw invalidScenario(scenarioPath, `${objectPath}.feet must be a non-empty array of unique node names; got ${describeValue(feet)}.`);
8146
+ const maxSlip = optionalPositiveNumber(record4, "maxSlip", scenarioPath, objectPath);
8147
+ const maxSlideSpeed = optionalPositiveNumber(record4, "maxSlideSpeed", scenarioPath, objectPath);
8148
+ if (maxSlip === void 0 && maxSlideSpeed === void 0)
8149
+ throw invalidScenario(scenarioPath, `${objectPath}.maxSlip or ${objectPath}.maxSlideSpeed is required; a slip measure with no ceiling bounds nothing.`);
8150
+ return {
8151
+ atStep: requireString(record4, "atStep", scenarioPath, objectPath),
8152
+ ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
8153
+ feet,
8154
+ ...present("maxSlideSpeed", maxSlideSpeed),
8155
+ ...present("maxSlip", maxSlip),
8156
+ ...present("stepSeconds", optionalPositiveNumber(record4, "stepSeconds", scenarioPath, objectPath))
8157
+ };
8158
+ }
8159
+ function validateSightLineAssertion(value, scenarioPath, objectPath) {
8160
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8161
+ rejectUnknownKeys(record4, ["entity", "maxBlockedRatio"], scenarioPath, objectPath);
8162
+ const maxBlockedRatio = optionalRatio(record4, "maxBlockedRatio", scenarioPath, objectPath);
8163
+ if (maxBlockedRatio === void 0) throw invalidScenario(scenarioPath, `${objectPath}.maxBlockedRatio is required; a sight line with no allowed blocked share bounds nothing.`);
8164
+ return {
8165
+ ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
8166
+ maxBlockedRatio
8167
+ };
8168
+ }
8169
+ function validateEngineCostAssertion(value, scenarioPath, objectPath) {
8170
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8171
+ rejectUnknownKeys(record4, ["maxInFrame", "maxPerFrame", "minWindows", "moving", "skipWindows", "source", "still"], scenarioPath, objectPath);
8172
+ const bounds = (key, owner = record4, at = objectPath) => {
8173
+ if (!hasKey(owner, key)) return void 0;
8174
+ const table = requireRecord(owner[key], scenarioPath, `${at}.${key}`);
8175
+ const names = Object.keys(table);
8176
+ if (names.length === 0) throw invalidScenario(scenarioPath, `'${at}.${key}' names no counter.`);
8177
+ for (const name of names) {
8178
+ const bound = table[name];
8179
+ if (typeof bound !== "number" || !Number.isFinite(bound) || bound < 0)
8180
+ throw invalidScenario(scenarioPath, `'${at}.${key}.${name}' must be a non-negative number, received ${describeValue(bound)}.`);
8181
+ }
8182
+ return table;
8183
+ };
8184
+ const maxPerFrame = bounds("maxPerFrame");
8185
+ const maxInFrame = bounds("maxInFrame");
8186
+ let still;
8187
+ if (hasKey(record4, "still")) {
8188
+ const at = `${objectPath}.still`;
8189
+ const stillRecord = requireRecord(record4.still, scenarioPath, at);
8190
+ rejectUnknownKeys(stillRecord, ["maxPerFrame", "windows"], scenarioPath, at);
8191
+ const windows = optionalPositiveInteger(stillRecord, "windows", scenarioPath, at);
8192
+ const stillBounds = bounds("maxPerFrame", stillRecord, at);
8193
+ if (windows === void 0 || stillBounds === void 0)
8194
+ throw invalidScenario(scenarioPath, `${at} needs 'windows' and 'maxPerFrame'.`);
8195
+ still = { maxPerFrame: stillBounds, windows };
8196
+ }
8197
+ let moving;
8198
+ if (hasKey(record4, "moving")) {
8199
+ const at = `${objectPath}.moving`;
8200
+ const movingRecord = requireRecord(record4.moving, scenarioPath, at);
8201
+ rejectUnknownKeys(movingRecord, ["maxInFrame", "maxPerFrame"], scenarioPath, at);
8202
+ if (still === void 0) throw invalidScenario(scenarioPath, `${at} needs 'still': the moving windows are the ones after it.`);
8203
+ const movingPerFrame = bounds("maxPerFrame", movingRecord, at);
8204
+ const movingInFrame = bounds("maxInFrame", movingRecord, at);
8205
+ if (movingPerFrame === void 0 && movingInFrame === void 0)
8206
+ throw invalidScenario(scenarioPath, `${at} must bound at least one counter.`);
8207
+ moving = { ...present("maxPerFrame", movingPerFrame), ...present("maxInFrame", movingInFrame) };
8208
+ }
8209
+ if (maxPerFrame === void 0 && maxInFrame === void 0 && still === void 0 && moving === void 0)
8210
+ throw invalidScenario(scenarioPath, `${objectPath} must bound at least one counter in 'maxPerFrame', 'maxInFrame', 'still' or 'moving'.`);
8211
+ const source = requireString(record4, "source", scenarioPath, objectPath);
8212
+ if (source.trim().length < 12)
8213
+ throw invalidScenario(scenarioPath, `'${objectPath}.source' must say where the bounds came from.`);
8214
+ return {
8215
+ ...present("maxPerFrame", maxPerFrame),
8216
+ ...present("maxInFrame", maxInFrame),
8217
+ ...present("minWindows", optionalPositiveInteger(record4, "minWindows", scenarioPath, objectPath)),
8218
+ ...present("skipWindows", optionalNonNegativeInteger(record4, "skipWindows", scenarioPath, objectPath)),
8219
+ source,
8220
+ ...present("still", still),
8221
+ ...present("moving", moving)
8222
+ };
8223
+ }
8224
+ function validateHudAuditAssertion(value, scenarioPath, objectPath) {
8225
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8226
+ rejectUnknownKeys(record4, ["minContrast", "noDebugText"], scenarioPath, objectPath);
8227
+ const noDebugText = optionalBoolean(record4, "noDebugText", scenarioPath, objectPath);
8228
+ if (noDebugText === false) {
8229
+ throw invalidScenario(scenarioPath, `'${objectPath}.noDebugText' may only be true; remove the key to stop scanning for developer text.`);
8230
+ }
8231
+ const minContrast = optionalNumber2(record4, "minContrast", scenarioPath, objectPath);
8232
+ if (minContrast !== void 0 && (minContrast < 1 || minContrast > 21)) {
8233
+ throw invalidScenario(scenarioPath, `'${objectPath}.minContrast' must be between 1 and 21, received ${describeValue(minContrast)}.`);
8234
+ }
8235
+ if (noDebugText === void 0 && minContrast === void 0) {
8236
+ throw invalidScenario(scenarioPath, `${objectPath} must declare at least one of 'minContrast' or 'noDebugText'.`);
8237
+ }
8238
+ return {
8239
+ ...present("minContrast", minContrast),
8240
+ ...noDebugText === void 0 ? {} : { noDebugText: true }
8241
+ };
8242
+ }
7212
8243
  function validateAnimationAssertion(value, scenarioPath, objectPath) {
7213
8244
  const record4 = requireRecord(value, scenarioPath, objectPath);
7214
- rejectUnknownKeys(record4, ["advancedFrames", "allowTrivial", "clip", "entered", "entity", "finished", "maxFootSlide", "strideSynced"], scenarioPath, objectPath);
8245
+ rejectUnknownKeys(record4, ["advancedFrames", "allowTrivial", "atStep", "clip", "entered", "entity", "finished", "maxFootSlide", "strideSynced"], scenarioPath, objectPath);
7215
8246
  return {
7216
8247
  ...present("advancedFrames", optionalNumber2(record4, "advancedFrames", scenarioPath, objectPath)),
7217
8248
  ...present("allowTrivial", optionalTrivialityReason(record4, "allowTrivial", scenarioPath, objectPath)),
8249
+ ...present("atStep", optionalString(record4, "atStep", scenarioPath, objectPath)),
7218
8250
  ...present("clip", optionalString(record4, "clip", scenarioPath, objectPath)),
7219
8251
  ...present("entered", optionalBoolean(record4, "entered", scenarioPath, objectPath)),
7220
8252
  ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
@@ -7244,12 +8276,14 @@ function validatePathAssertion(value, scenarioPath, objectPath) {
7244
8276
  const atSteps = Array.isArray(record4.atSteps) ? record4.atSteps.map((step, index) => {
7245
8277
  const stepPath = `${objectPath}.atSteps[${index}]`;
7246
8278
  const entry = requireRecord(step, scenarioPath, stepPath);
7247
- if (!hasKey(entry, "equals") && entry.textIncludes === void 0) {
7248
- throw invalidScenario(scenarioPath, `'${stepPath}' must set equals or textIncludes; a labeled step with no expectation passes on any value.`);
8279
+ const stepLte = optionalNumber2(entry, "lte", scenarioPath, stepPath);
8280
+ if (!hasKey(entry, "equals") && entry.textIncludes === void 0 && stepLte === void 0) {
8281
+ throw invalidScenario(scenarioPath, `'${stepPath}' must set equals, lte or textIncludes; a labeled step with no expectation passes on any value.`);
7249
8282
  }
7250
8283
  return {
7251
8284
  ...hasKey(entry, "equals") ? { equals: entry.equals } : {},
7252
8285
  label: requireString(entry, "label", scenarioPath, stepPath),
8286
+ ...present("lte", stepLte),
7253
8287
  ...present("textIncludes", optionalString(entry, "textIncludes", scenarioPath, stepPath))
7254
8288
  };
7255
8289
  }) : void 0;
@@ -7406,7 +8440,7 @@ function validateNestedAssertionKeys(kind, value, scenarioPath, suffix) {
7406
8440
  if (Array.isArray(value.atSteps)) {
7407
8441
  value.atSteps.forEach((step, index) => {
7408
8442
  if (isRecord3(step)) {
7409
- rejectUnknownKeys(step, kind === "components" ? ["equals", "label"] : ["equals", "label", "textIncludes"], scenarioPath, `assert.${kind}${suffix}.atSteps[${index}]`);
8443
+ rejectUnknownKeys(step, kind === "components" ? ["equals", "label"] : ["equals", "label", "lte", "textIncludes"], scenarioPath, `assert.${kind}${suffix}.atSteps[${index}]`);
7410
8444
  }
7411
8445
  });
7412
8446
  }
@@ -7415,7 +8449,7 @@ function validateNestedAssertionKeys(kind, value, scenarioPath, suffix) {
7415
8449
  const fields = {
7416
8450
  entityVisible: ["entity", "minProjectedPixels", "throughoutFrames"],
7417
8451
  frameDiff: ["baselineImage", "maxChangedPixelRatio", "minChangedPixelRatio"],
7418
- region: ["element", "height", "maxDarkPixelRatio", "maxLuminance", "minDarkPixelRatio", "minNonblankPixelRatio", "width", "x", "y"]
8452
+ region: ["element", "height", "maxDarkPixelRatio", "maxLuminance", "minDarkPixelRatio", "minNonblankPixelRatio", "minSharpness", "width", "x", "y"]
7419
8453
  };
7420
8454
  for (const [field, keys] of Object.entries(fields)) {
7421
8455
  if (isRecord3(value[field])) {
@@ -7484,8 +8518,10 @@ var PLAYTEST_ROOT_KEYS = [
7484
8518
  "assert",
7485
8519
  "awaitStartup",
7486
8520
  "bootFailure",
8521
+ "clock",
7487
8522
  "inputDelivery",
7488
8523
  "name",
8524
+ "network",
7489
8525
  "parity",
7490
8526
  "reducedMotion",
7491
8527
  "schemaVersion",
@@ -7528,12 +8564,25 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7528
8564
  if (value.bootFailure !== void 0 && target !== "web") {
7529
8565
  throw invalidScenario(scenarioPath, "Scenario bootFailure is browser-only and requires target 'web'.");
7530
8566
  }
8567
+ if (value.clock !== void 0 && value.clock !== "wall-clock") {
8568
+ throw invalidScenario(scenarioPath, "Scenario clock must be 'wall-clock' when present.");
8569
+ }
8570
+ if (value.clock !== void 0 && target !== "web") {
8571
+ throw invalidScenario(scenarioPath, "Scenario clock is browser-only and requires target 'web'.");
8572
+ }
7531
8573
  if (value.reducedMotion !== void 0 && value.reducedMotion !== "reduce") {
7532
8574
  throw invalidScenario(scenarioPath, "Scenario reducedMotion must be 'reduce' when present.");
7533
8575
  }
7534
8576
  if (value.reducedMotion !== void 0 && target !== "web") {
7535
8577
  throw invalidScenario(scenarioPath, "Scenario reducedMotion is browser-only and requires target 'web'.");
7536
8578
  }
8579
+ if (value.network !== void 0 && !isRecord3(value.network)) {
8580
+ throw invalidScenario(scenarioPath, "Scenario network must be an object with downloadKbps and latencyMs.");
8581
+ }
8582
+ const network = value.network === void 0 ? void 0 : validateNetworkProfile(value.network, scenarioPath);
8583
+ if (network !== void 0 && target !== "web") {
8584
+ throw invalidScenario(scenarioPath, "Scenario network is browser-only and requires target 'web'.");
8585
+ }
7537
8586
  const inputDelivery = value.inputDelivery ?? "deterministic";
7538
8587
  if (inputDelivery !== "deterministic" && inputDelivery !== "focused-dom") {
7539
8588
  throw invalidScenario(scenarioPath, "Scenario inputDelivery must be deterministic or focused-dom.");
@@ -7548,7 +8597,7 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7548
8597
  throw invalidScenario(scenarioPath, "Scenario subject must be a non-empty entity id when present.");
7549
8598
  }
7550
8599
  const subject = typeof value.subject === "string" ? value.subject : void 0;
7551
- const steps = value.steps.map((step, index) => validateStep(step, scenarioPath, index));
8600
+ const steps = value.steps.flatMap((step, index) => isRecord3(step) && step.kind === "explore" ? expandExploreStep(step, scenarioPath, index) : [step]).map((step, index) => validateStep(step, scenarioPath, index));
7552
8601
  if (steps.some(({ kind }) => kind === "aimAt") && subject === void 0) {
7553
8602
  throw invalidScenario(scenarioPath, "A step with kind 'aimAt' aims the subject player start; declare scenario.subject or replace the step.");
7554
8603
  }
@@ -7560,8 +8609,10 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7560
8609
  ...assertions === void 0 ? {} : { assert: assertions },
7561
8610
  ...typeof value.awaitStartup === "boolean" ? { awaitStartup: value.awaitStartup } : {},
7562
8611
  ...value.bootFailure === "renderer-no-adapter" ? { bootFailure: value.bootFailure } : {},
8612
+ ...value.clock === "wall-clock" ? { clock: value.clock } : {},
7563
8613
  inputDelivery,
7564
8614
  name,
8615
+ ...network === void 0 ? {} : { network },
7565
8616
  ...value.parity === void 0 ? {} : { parity: validateParityConfig(requireRecord(value.parity, scenarioPath, "parity"), scenarioPath) },
7566
8617
  ...value.reducedMotion === "reduce" ? { reducedMotion: value.reducedMotion } : {},
7567
8618
  schemaVersion: 1,
@@ -7575,6 +8626,55 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7575
8626
  warmupFrames: optionalNonNegativeInteger(value, "warmupFrames", scenarioPath, "scenario") ?? 0
7576
8627
  };
7577
8628
  }
8629
+ function expandExploreStep(value, scenarioPath, index) {
8630
+ rejectUnknownKeys(value, ["actions", "kind", "label", "move", "pointer", "seed", "ticks"], scenarioPath, `steps[${index}]`);
8631
+ const keys = (field) => {
8632
+ const list = value[field];
8633
+ if (list === void 0 && field === "actions") return [];
8634
+ if (!Array.isArray(list) || list.length === 0 || list.some((key) => typeof key !== "string" || key.trim() === "") || new Set(list).size !== list.length) {
8635
+ throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' must define ${field} as a non-empty array of unique key names.`);
8636
+ }
8637
+ return list;
8638
+ };
8639
+ if (!Number.isSafeInteger(value.seed)) throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' must define seed as an integer.`);
8640
+ const ticks = positiveInteger2(value.ticks);
8641
+ if (ticks === void 0) throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' must define ticks as a positive integer.`);
8642
+ if (value.pointer !== void 0 && typeof value.pointer !== "boolean") throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' pointer must be a boolean.`);
8643
+ 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.`);
8644
+ const move = keys("move");
8645
+ const actions = keys("actions");
8646
+ let state = value.seed >>> 0;
8647
+ const random = () => {
8648
+ state = state + 1831565813 >>> 0;
8649
+ let t = state;
8650
+ t = Math.imul(t ^ t >>> 15, t | 1);
8651
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
8652
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
8653
+ };
8654
+ const pick = (list) => list[Math.floor(random() * list.length)];
8655
+ const steps = [];
8656
+ let heading = pick(move);
8657
+ for (let left = ticks; left > 0; ) {
8658
+ const holdTicks = Math.min(left, 10 + Math.floor(random() * 50));
8659
+ if (random() < 0.2) heading = pick(move);
8660
+ const press = /* @__PURE__ */ new Set([heading]);
8661
+ if (move.length > 1 && random() < 0.35) press.add(pick(move));
8662
+ if (actions.length > 0 && random() < 0.5) {
8663
+ press.add(pick(actions));
8664
+ if (random() < 0.25) press.add(pick(actions));
8665
+ }
8666
+ steps.push({
8667
+ holdTicks,
8668
+ kind: "input",
8669
+ press: [...press],
8670
+ ...value.pointer === true ? { pointerPosition: { x: random(), y: random() } } : {},
8671
+ release: true
8672
+ });
8673
+ left -= holdTicks;
8674
+ }
8675
+ if (typeof value.label === "string") steps[steps.length - 1].label = value.label;
8676
+ return steps;
8677
+ }
7578
8678
  function validateArtifacts(value, scenarioPath) {
7579
8679
  rejectUnknownKeys(value, ["console", "contactSheet", "effectLog", "network", "runtimeTrace", "screenshots"], scenarioPath, "artifacts");
7580
8680
  for (const key of ["console", "contactSheet", "network", "runtimeTrace"]) {
@@ -7657,6 +8757,21 @@ function validateParityTargets(value, scenarioPath, objectPath) {
7657
8757
  return target;
7658
8758
  });
7659
8759
  }
8760
+ function validateNetworkProfile(value, scenarioPath) {
8761
+ rejectUnknownKeys(value, ["downloadKbps", "latencyMs"], scenarioPath, "network");
8762
+ const downloadKbps = value.downloadKbps;
8763
+ if (typeof downloadKbps !== "number" || !Number.isFinite(downloadKbps) || downloadKbps <= 0) {
8764
+ throw invalidScenario(
8765
+ scenarioPath,
8766
+ "Scenario network.downloadKbps must be a positive number of kilobits per second."
8767
+ );
8768
+ }
8769
+ const latencyMs = value.latencyMs;
8770
+ if (typeof latencyMs !== "number" || !Number.isFinite(latencyMs) || latencyMs < 0) {
8771
+ throw invalidScenario(scenarioPath, "Scenario network.latencyMs must be a non-negative number.");
8772
+ }
8773
+ return { downloadKbps, latencyMs };
8774
+ }
7660
8775
  function validateSetup(value, scenarioPath, subject) {
7661
8776
  rejectUnknownKeys(value, ["aim", "entities", "place", "resources", "spawn"], scenarioPath, "setup");
7662
8777
  const spawn8 = validateSpawnRequest(value.spawn, scenarioPath);
@@ -7818,7 +8933,7 @@ var PLAYTEST_STEP_KEYS = [
7818
8933
  "wheel",
7819
8934
  "window"
7820
8935
  ];
7821
- var MAX_RESOURCE_WAIT_TIMEOUT_MS = 12e4;
8936
+ var MAX_RESOURCE_WAIT_TIMEOUT_MS = 3e5;
7822
8937
  function validateStep(value, scenarioPath, index) {
7823
8938
  if (!isRecord3(value)) {
7824
8939
  throw invalidStep(scenarioPath, `Scenario step ${index} must be a JSON object.`);
@@ -7895,7 +9010,7 @@ function validateStep(value, scenarioPath, index) {
7895
9010
  const waitTicks = positiveInteger2(value.waitTicks);
7896
9011
  const kind = value.kind === "aimAt" ? "aimAt" : value.kind === "click" ? "click" : value.kind === "lifecycle" ? "lifecycle" : value.kind === "wait" ? "wait" : value.kind === "input" ? "input" : void 0;
7897
9012
  if (value.kind !== void 0 && kind === void 0) {
7898
- throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'input', 'lifecycle', or 'wait'.`);
9013
+ throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'explore', 'input', 'lifecycle', or 'wait'.`);
7899
9014
  }
7900
9015
  const at = validateClickTarget(value.at, scenarioPath, index);
7901
9016
  const target = validateAimTarget(value.target, scenarioPath, index);
@@ -8223,6 +9338,14 @@ function validateStepLabels(steps, assertions, scenarioPath) {
8223
9338
  for (const [index, assertion] of (assertions.tone ?? []).entries()) {
8224
9339
  requireLabel(assertion.atStep, `assert.tone[${index}].atStep`);
8225
9340
  }
9341
+ for (const [index, assertion] of (assertions.animation ?? []).entries()) {
9342
+ requireLabel(assertion.atStep, `assert.animation[${index}].atStep`);
9343
+ }
9344
+ for (const [index, assertion] of (assertions.footSlip ?? []).entries()) {
9345
+ requireLabel(assertion.atStep, `assert.footSlip[${index}].atStep`);
9346
+ if (assertions.footSlip.findIndex(({ atStep }) => atStep === assertion.atStep) !== index)
9347
+ throw invalidScenario(scenarioPath, `Assertion 'assert.footSlip[${index}]' repeats atStep '${assertion.atStep}'; list every foot in one assertion.`);
9348
+ }
8226
9349
  for (const [index, assertion] of (assertions.signals ?? []).entries()) {
8227
9350
  requireLabel(assertion.atStep, `assert.signals[${index}].atStep`);
8228
9351
  }
@@ -8263,6 +9386,9 @@ function validateAssertions(value, scenarioPath) {
8263
9386
  if (Array.isArray(value.signals) && value.signals.length === 0) {
8264
9387
  throw invalidScenario(scenarioPath, "Assertion 'assert.signals' must contain at least one signal assertion.");
8265
9388
  }
9389
+ if (Array.isArray(value.footSlip) && value.footSlip.length === 0) {
9390
+ throw invalidScenario(scenarioPath, "Assertion 'assert.footSlip' must contain at least one foot-slip assertion.");
9391
+ }
8266
9392
  if (Array.isArray(value.tone) && value.tone.length === 0) {
8267
9393
  throw invalidScenario(scenarioPath, "Assertion 'assert.tone' must contain at least one tone assertion.");
8268
9394
  }
@@ -8278,7 +9404,7 @@ function validateAssertions(value, scenarioPath) {
8278
9404
  );
8279
9405
  }
8280
9406
  const diagnostics = isRecord3(value.diagnostics) ? value.diagnostics : void 0;
8281
- const performance = isRecord3(value.performance) ? validatePerformanceAssertion(value.performance, scenarioPath, "assert.performance") : void 0;
9407
+ const performance2 = isRecord3(value.performance) ? validatePerformanceAssertion(value.performance, scenarioPath, "assert.performance") : void 0;
8282
9408
  const deviceMetrics = value.deviceMetrics === void 0 ? void 0 : validateDeviceMetricsAssertion(value.deviceMetrics, scenarioPath, "assert.deviceMetrics");
8283
9409
  const parity = value.parity === void 0 ? void 0 : validateParityAssertion(value.parity, scenarioPath, "assert.parity");
8284
9410
  const framebufferCoverage = isRecord3(value.framebufferCoverage) ? validateFramebufferCoverageAssertion(
@@ -8337,7 +9463,7 @@ function validateAssertions(value, scenarioPath) {
8337
9463
  ...Array.isArray(value.hud) ? {
8338
9464
  hud: value.hud.map((entry, index) => validatePathAssertion(entry, scenarioPath, `assert.hud[${index}]`))
8339
9465
  } : {},
8340
- ...performance === void 0 ? {} : { performance },
9466
+ ...performance2 === void 0 ? {} : { performance: performance2 },
8341
9467
  ...renderChain === void 0 ? {} : { renderChain },
8342
9468
  ...startup === void 0 ? {} : { startup },
8343
9469
  ...pipelineCensus === void 0 ? {} : { pipelineCensus },
@@ -8346,6 +9472,12 @@ function validateAssertions(value, scenarioPath) {
8346
9472
  ...hasKey(value, "causedBy") ? {
8347
9473
  causedBy: requireArray(value, "causedBy", scenarioPath, "assert.causedBy").map((entry, index) => validateCausedByAssertion(entry, scenarioPath, `assert.causedBy[${index}]`))
8348
9474
  } : {},
9475
+ ...hasKey(value, "footSlip") ? {
9476
+ footSlip: requireArray(value, "footSlip", scenarioPath, "assert.footSlip").map((entry, index) => validateFootSlipAssertion(entry, scenarioPath, `assert.footSlip[${index}]`))
9477
+ } : {},
9478
+ ...hasKey(value, "sightLine") ? { sightLine: validateSightLineAssertion(value.sightLine, scenarioPath, "assert.sightLine") } : {},
9479
+ ...hasKey(value, "hudAudit") ? { hudAudit: validateHudAuditAssertion(value.hudAudit, scenarioPath, "assert.hudAudit") } : {},
9480
+ ...hasKey(value, "engineCost") ? { engineCost: validateEngineCostAssertion(value.engineCost, scenarioPath, "assert.engineCost") } : {},
8349
9481
  ...hasKey(value, "sceneNodes") ? {
8350
9482
  sceneNodes: requireArray(value, "sceneNodes", scenarioPath, "assert.sceneNodes").map((entry, index) => validateSceneNodesAssertion(entry, scenarioPath, `assert.sceneNodes[${index}]`))
8351
9483
  } : {},
@@ -8866,7 +9998,7 @@ var STANDALONE_PLAYTEST_OBSERVATION_FIELDS = [
8866
9998
  "startup",
8867
9999
  "visual"
8868
10000
  ];
8869
- var HOST_PLAYTEST_OBSERVATION_FIELDS = ["deviceLifecycle", "deviceMetrics", "tone"];
10001
+ var HOST_PLAYTEST_OBSERVATION_FIELDS = ["deviceLifecycle", "deviceMetrics", "footSlip", "hudAudit", "sightLine", "tone"];
8870
10002
 
8871
10003
  // src/runner/setup-confirmation.ts
8872
10004
  function unconfirmed(requested, confirmation) {
@@ -9249,7 +10381,8 @@ async function connectPlaytestBridgeTransport(transport, scenario, timeoutMs = b
9249
10381
  }
9250
10382
  return {
9251
10383
  advance: async (ticks, options) => {
9252
- await transport.call("advance", ticks, advanceTimeoutMs(ticks), options);
10384
+ const result = await transport.call("advance", ticks, advanceTimeoutMs(ticks), options);
10385
+ return typeof result?.ticks === "number" ? result.ticks : void 0;
9253
10386
  },
9254
10387
  applySetup: async (request) => {
9255
10388
  assertBoundedPayload(request);
@@ -9324,244 +10457,80 @@ function unavailableObservation(scenario) {
9324
10457
  }
9325
10458
  }
9326
10459
  const movement = scenario.assert?.movement;
9327
- if (movement !== void 0) {
9328
- const effectLogAssertion = movement.notFacing !== void 0 ? "movement.notFacing" : movement.notFacingPosition !== void 0 ? "movement.notFacingPosition" : movement.facesMovementWithinDegrees !== void 0 ? "movement.facesMovementWithinDegrees" : movement.minResolvedAxisDelta !== void 0 ? "movement.minResolvedAxisDelta" : void 0;
9329
- if (effectLogAssertion !== void 0) {
9330
- return {
9331
- assertion: effectLogAssertion,
9332
- path: "effectLog",
9333
- reason: "The standalone runner does not produce an effect log."
9334
- };
9335
- }
9336
- }
9337
- return void 0;
9338
- }
9339
- function requiredObservationPaths(scenario, kind, defaultPath) {
9340
- const movementStep = scenario.assert?.movement?.reachesPositionWithin?.atStep;
9341
- if (kind === "movement" && movementStep !== void 0 && scenario.steps.at(-1)?.label !== movementStep) {
9342
- return ["effectLogSeries"];
9343
- }
9344
- if (kind === "contacts" && scenario.assert?.contacts?.some(({ atStep }) => atStep !== void 0) === true) {
9345
- return ["physicsDebugSeries"];
9346
- }
9347
- return [defaultPath];
9348
- }
9349
- function assertBoundedPayload(value) {
9350
- assertJsonSafe(value);
9351
- if (jsonByteLength(value) > PLAYTEST_PROTOCOL_LIMITS.maxPayloadBytes) {
9352
- throw new PlaytestBridgeError(playtestDiagnostic(
9353
- "TN_PLAYTEST_PAYLOAD_TOO_LARGE",
9354
- `Bridge payload exceeds ${PLAYTEST_PROTOCOL_LIMITS.maxPayloadBytes} bytes.`,
9355
- "Request fewer entities or return smaller provider observations."
9356
- ));
9357
- }
9358
- }
9359
- async function bridgeCall(page, method, argument, timeoutMs = PLAYTEST_PROTOCOL_LIMITS.operationTimeoutMs, options) {
9360
- let timeout;
9361
- try {
9362
- return await Promise.race([
9363
- page.evaluate(
9364
- async ({ argument: argument2, globalName, method: method2, options: options2 }) => {
9365
- const bridge = globalThis[globalName];
9366
- const operation = bridge?.[method2];
9367
- if (typeof operation !== "function") {
9368
- throw new Error(`Bridge operation '${method2}' is unavailable.`);
9369
- }
9370
- return operation.call(bridge, argument2, options2);
9371
- },
9372
- { argument, globalName: PLAYTEST_BRIDGE_GLOBAL, method, options }
9373
- ),
9374
- new Promise((_resolve, reject) => {
9375
- timeout = setTimeout(() => reject(new PlaytestBridgeError(playtestDiagnostic(
9376
- "TN_PLAYTEST_OPERATION_TIMEOUT",
9377
- `Bridge operation '${method}' exceeded ${timeoutMs}ms.`,
9378
- "Bound the provider work or return a smaller observation payload."
9379
- ))), timeoutMs);
9380
- })
9381
- ]);
9382
- } finally {
9383
- if (timeout !== void 0) clearTimeout(timeout);
9384
- }
9385
- }
9386
- var DEFAULT_XVFB_SCREEN = "1600x900x24";
9387
- var HOST_DISPLAY_ENV = "TN_PLAYTEST_HOST_DISPLAY";
9388
- var STRIPPED_WAYLAND_VARS = ["WAYLAND_DISPLAY", "WAYLAND_SOCKET", "XDG_SESSION_TYPE"];
9389
- function decideDisplayStrategy(input) {
9390
- if (input.platform !== "linux") return { kind: "host" };
9391
- const privateXvfb = {
9392
- kind: "private-xvfb",
9393
- screen: input.env.TN_XVFB_SCREEN ?? DEFAULT_XVFB_SCREEN
9394
- };
9395
- if (!hostDisplayRequested(input.env)) return privateXvfb;
9396
- const display = input.env.DISPLAY;
9397
- if (display === void 0 || display.length === 0) {
9398
- throw new Error("TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: the requested host display requires DISPLAY.");
9399
- }
9400
- const available = input.displaySocketExists?.(display) ?? x11DisplayIsUsable(display, input.env);
9401
- if (!available) {
9402
- throw new Error(`TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: cannot connect to requested DISPLAY=${display}. Refusing to substitute a private Xvfb.`);
9403
- }
9404
- return { display, kind: "existing" };
9405
- }
9406
- function hostDisplayRequested(env) {
9407
- const value = env[HOST_DISPLAY_ENV];
9408
- return value === "1" || value?.toLowerCase() === "true";
9409
- }
9410
- function x11DisplayIsUsable(display, env) {
9411
- const probe = spawnSync("xdpyinfo", ["-display", display], { env, stdio: "ignore", timeout: 2e3 });
9412
- if (probe.error) {
9413
- throw new Error(`TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE: cannot verify DISPLAY=${display}: xdpyinfo ${probe.error.message}.`);
9414
- }
9415
- return probe.status === 0;
9416
- }
9417
- function childEnvForDisplay(env, display) {
9418
- const child = { ...env };
9419
- for (const name of STRIPPED_WAYLAND_VARS) delete child[name];
9420
- child.DISPLAY = display;
9421
- return child;
9422
- }
9423
- function runNeedsPixels(config, scenario) {
9424
- if (config.headless !== true) return true;
9425
- const takesScreenshot = scenario.artifacts?.screenshots !== false || scenario.steps.some(({ screenshot }) => screenshot !== void 0);
9426
- const evaluatesVisual = (scenario.assert?.visual?.length ?? 0) > 0 || (scenario.assert?.tone?.length ?? 0) > 0;
9427
- return takesScreenshot || evaluatesVisual || scenario.assert?.framebufferCoverage !== void 0;
9428
- }
9429
- async function provideDisplay(options = {}) {
9430
- const env = options.env ?? process.env;
9431
- const platform = options.platform ?? process.platform;
9432
- const strategy = decideDisplayStrategy({
9433
- displaySocketExists: options.displaySocketExists,
9434
- env,
9435
- platform
9436
- });
9437
- if (strategy.kind === "host") {
9438
- return {
9439
- compositor: void 0,
9440
- display: void 0,
9441
- env: { ...env },
9442
- release: async () => void 0,
9443
- strategy
9444
- };
9445
- }
9446
- if (strategy.kind === "existing") {
9447
- return {
9448
- compositor: void 0,
9449
- display: strategy.display,
9450
- env: childEnvForDisplay(env, strategy.display),
9451
- release: async () => void 0,
9452
- strategy
9453
- };
9454
- }
9455
- const commandExists = options.commandExists ?? defaultCommandExists;
9456
- if (!commandExists("Xvfb")) {
9457
- throw new Error(
9458
- "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."
9459
- );
9460
- }
9461
- const spawnProcess = options.spawnProcess ?? spawn;
9462
- const xvfb = spawnProcess("Xvfb", [
9463
- "-displayfd",
9464
- "3",
9465
- "-nolisten",
9466
- "tcp",
9467
- // COMPOSITE and SHAPE are what a compositing manager needs before it can blend anything, and
9468
- // the native desktop runtime refuses to attach its UI overlay to a display without one. Xvfb
9469
- // does not enable them by default, so every native UI run on a private display reported
9470
- // `TN_UI_OVERLAY:{"attached":false,"reason":"no compositing manager is running"}` — including
9471
- // the starter template's own shipped native-playtests/react-hud scenario, which failed out of
9472
- // the box on a freshly scaffolded project. A browser run does not care either way.
9473
- "+extension",
9474
- "COMPOSITE",
9475
- "+extension",
9476
- "SHAPE",
9477
- "-screen",
9478
- "0",
9479
- strategy.screen
9480
- ], { stdio: ["ignore", "ignore", "pipe", "pipe"] });
9481
- xvfb.on?.("error", () => void 0);
9482
- try {
9483
- const number = await readXvfbDisplayNumber(xvfb);
9484
- const display = `:${number}`;
9485
- const compositor = await startCompositor(display, { commandExists, env, spawnProcess });
9486
- return {
9487
- compositor: compositor?.name,
9488
- display,
9489
- env: childEnvForDisplay(env, display),
9490
- release: async () => {
9491
- if (compositor !== void 0) await stopChild(compositor.child);
9492
- await stopChild(xvfb);
9493
- },
9494
- strategy
9495
- };
9496
- } catch (error) {
9497
- await stopChild(xvfb);
9498
- throw error;
10460
+ if (movement !== void 0) {
10461
+ const effectLogAssertion = movement.notFacing !== void 0 ? "movement.notFacing" : movement.notFacingPosition !== void 0 ? "movement.notFacingPosition" : movement.facesMovementWithinDegrees !== void 0 ? "movement.facesMovementWithinDegrees" : movement.minResolvedAxisDelta !== void 0 ? "movement.minResolvedAxisDelta" : void 0;
10462
+ if (effectLogAssertion !== void 0) {
10463
+ return {
10464
+ assertion: effectLogAssertion,
10465
+ path: "effectLog",
10466
+ reason: "The standalone runner does not produce an effect log."
10467
+ };
10468
+ }
9499
10469
  }
10470
+ return void 0;
9500
10471
  }
9501
- var COMPOSITORS = [
9502
- { args: ["-n"], name: "xcompmgr" },
9503
- { args: [], name: "picom" },
9504
- { args: [], name: "compton" }
9505
- ];
9506
- var COMPOSITOR_SETTLE_MS = 250;
9507
- async function startCompositor(display, options) {
9508
- const choice = COMPOSITORS.find(({ name }) => options.commandExists(name));
9509
- if (choice === void 0) return void 0;
9510
- const child = options.spawnProcess(choice.name, [...choice.args], {
9511
- env: { ...options.env, DISPLAY: display },
9512
- stdio: "ignore"
9513
- });
9514
- let spawnFailed = false;
9515
- child.on?.("error", () => {
9516
- spawnFailed = true;
9517
- });
9518
- await new Promise((settle) => setTimeout(settle, COMPOSITOR_SETTLE_MS));
9519
- if (spawnFailed) return void 0;
9520
- if ((child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null) return void 0;
9521
- return { child, name: choice.name };
9522
- }
9523
- var XVFB_DISPLAY_TIMEOUT_MS = 3e4;
9524
- async function readXvfbDisplayNumber(xvfb) {
9525
- const report = xvfb.stdio[3];
9526
- if (report === null || report === void 0 || typeof report.on !== "function") {
9527
- throw new Error("Xvfb was spawned without a display-report descriptor to read.");
10472
+ function requiredObservationPaths(scenario, kind, defaultPath) {
10473
+ const movementStep = scenario.assert?.movement?.reachesPositionWithin?.atStep;
10474
+ if (kind === "movement" && movementStep !== void 0 && scenario.steps.at(-1)?.label !== movementStep) {
10475
+ return ["effectLogSeries"];
9528
10476
  }
9529
- const stream = report;
9530
- return new Promise((resolveDisplay, rejectDisplay) => {
9531
- let settled = false;
9532
- const finish = (settle) => {
9533
- if (settled) return;
9534
- settled = true;
9535
- clearTimeout(timer);
9536
- stream.removeListener("data", onData);
9537
- stream.removeListener("close", onClose);
9538
- settle();
9539
- };
9540
- const onData = (chunk) => {
9541
- const number = Number.parseInt(String(chunk).trim(), 10);
9542
- if (Number.isInteger(number) && number >= 0) finish(() => resolveDisplay(number));
9543
- };
9544
- const onClose = () => finish(() => rejectDisplay(new Error("Xvfb exited before it reported a display.")));
9545
- const timer = setTimeout(() => finish(() => {
9546
- rejectDisplay(new Error(`Xvfb did not report a display within ${XVFB_DISPLAY_TIMEOUT_MS}ms.`));
9547
- }), XVFB_DISPLAY_TIMEOUT_MS);
9548
- stream.on("data", onData);
9549
- stream.on("close", onClose);
9550
- });
10477
+ if (kind === "contacts" && scenario.assert?.contacts?.some(({ atStep }) => atStep !== void 0) === true) {
10478
+ return ["physicsDebugSeries"];
10479
+ }
10480
+ return [defaultPath];
9551
10481
  }
9552
- async function stopChild(child) {
9553
- const exitedAlready = () => (child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null;
9554
- if (exitedAlready()) return;
9555
- child.kill("SIGTERM");
9556
- const started = Date.now();
9557
- while (Date.now() - started < 1e3 && !exitedAlready()) {
9558
- await new Promise((resolveWait) => setTimeout(resolveWait, 25));
10482
+ function assertBoundedPayload(value) {
10483
+ assertJsonSafe(value);
10484
+ if (jsonByteLength(value) > PLAYTEST_PROTOCOL_LIMITS.maxPayloadBytes) {
10485
+ throw new PlaytestBridgeError(playtestDiagnostic(
10486
+ "TN_PLAYTEST_PAYLOAD_TOO_LARGE",
10487
+ `Bridge payload exceeds ${PLAYTEST_PROTOCOL_LIMITS.maxPayloadBytes} bytes.`,
10488
+ "Request fewer entities or return smaller provider observations."
10489
+ ));
9559
10490
  }
9560
- if (!exitedAlready()) child.kill("SIGKILL");
9561
10491
  }
9562
- function defaultCommandExists(command) {
9563
- const paths = (process.env.PATH ?? "").split(":").filter((segment) => segment.length > 0);
9564
- return paths.some((directory) => existsSync(join(directory, command)));
10492
+ var PENDING_BRIDGE_OPERATIONS_GLOBAL = "__THREENATIVE_PLAYTEST_PENDING_OPERATIONS__";
10493
+ async function bridgeCall(page, method, argument, timeoutMs = PLAYTEST_PROTOCOL_LIMITS.operationTimeoutMs, options) {
10494
+ let timeout;
10495
+ try {
10496
+ return await Promise.race([
10497
+ page.evaluate(
10498
+ ({ argument: argument2, globalName, method: method2, options: options2, pendingOperationsGlobal }) => {
10499
+ const bridge = globalThis[globalName];
10500
+ const operation = bridge?.[method2];
10501
+ if (typeof operation !== "function") {
10502
+ throw new Error(`Bridge operation '${method2}' is unavailable.`);
10503
+ }
10504
+ const result = operation.call(bridge, argument2, options2);
10505
+ if (result === null || typeof result !== "object" && typeof result !== "function") return result;
10506
+ if (typeof result.then !== "function") return result;
10507
+ const host = globalThis;
10508
+ const pending = host[pendingOperationsGlobal] ?? /* @__PURE__ */ new Set();
10509
+ host[pendingOperationsGlobal] = pending;
10510
+ pending.add(result);
10511
+ const forget = () => pending.delete(result);
10512
+ void result.then(forget, forget);
10513
+ return result;
10514
+ },
10515
+ {
10516
+ argument,
10517
+ globalName: PLAYTEST_BRIDGE_GLOBAL,
10518
+ method,
10519
+ options,
10520
+ pendingOperationsGlobal: PENDING_BRIDGE_OPERATIONS_GLOBAL
10521
+ }
10522
+ ),
10523
+ new Promise((_resolve, reject) => {
10524
+ timeout = setTimeout(() => reject(new PlaytestBridgeError(playtestDiagnostic(
10525
+ "TN_PLAYTEST_OPERATION_TIMEOUT",
10526
+ `Bridge operation '${method}' exceeded ${timeoutMs}ms.`,
10527
+ "Bound the provider work or return a smaller observation payload."
10528
+ ))), timeoutMs);
10529
+ })
10530
+ ]);
10531
+ } finally {
10532
+ if (timeout !== void 0) clearTimeout(timeout);
10533
+ }
9565
10534
  }
9566
10535
  var execFileAsync = promisify(execFile);
9567
10536
  function hostCssUiExtras() {
@@ -9793,6 +10762,7 @@ var AdbAndroidDriver = class _AdbAndroidDriver {
9793
10762
  lastError = error.message;
9794
10763
  if (isAdbRefusal(lastError) || attempt === LOGCAT_ATTEMPTS) break;
9795
10764
  await this.adb(["wait-for-device"]).catch(() => void 0);
10765
+ await delay(LOGCAT_RETRY_MS);
9796
10766
  }
9797
10767
  }
9798
10768
  if (output === void 0) throw failedLogcat(args.join(" "), lastError);
@@ -10022,9 +10992,8 @@ ${excerpt}`
10022
10992
  return stdout;
10023
10993
  } catch (error) {
10024
10994
  const detail = error;
10025
- throw new Error(
10026
- `adb ${args.join(" ")} failed: ${detail.stderr || detail.stdout || detail.message}`
10027
- );
10995
+ const silent = `${detail.message.trim()} (exit ${String(detail.code)}, signal ${String(detail.signal)})`;
10996
+ throw new Error(`adb ${args.join(" ")} failed: ${detail.stderr || detail.stdout || silent}`);
10028
10997
  }
10029
10998
  }
10030
10999
  async waitForScreenRecorder() {
@@ -10092,7 +11061,9 @@ function parseAndroidConsoleEntries(output, app) {
10092
11061
  `(?:^|[^\\w.])${app.packageName.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}(?=[:/\\s,})]|$)`,
10093
11062
  "u"
10094
11063
  );
10095
- return output.split(/\r?\n/u).filter((line) => !/^[VDIWEF]\/(?:SurfaceSyncGroup|TransitionController)\(/u.test(line)).filter((line) => {
11064
+ return output.split(/\r?\n/u).filter(
11065
+ (line) => !/^[VDIWEF]\/(?:SurfaceSyncGroup|TransitionController|AppHibernationService)\(/u.test(line)
11066
+ ).filter((line) => {
10096
11067
  if (app === void 0) return /Mystral|THREENATIVE|chromium/u.test(line);
10097
11068
  if (app.pids.size === 0) return line.trim().length > 0;
10098
11069
  const pid = /^[VDIWEF]\/[^\n(]+\(\s*(\d+)\)/u.exec(line)?.[1];
@@ -10107,7 +11078,8 @@ function isPlatformWebViewNoise(text) {
10107
11078
  return !/:CONSOLE\(|Mystral|THREENATIVE/u.test(text);
10108
11079
  }
10109
11080
  var TOUCH_AXIS_MAX = 32767;
10110
- var LOGCAT_ATTEMPTS = 2;
11081
+ var LOGCAT_ATTEMPTS = 4;
11082
+ var LOGCAT_RETRY_MS = 1e3;
10111
11083
  var LOGCAT_ERROR_LIMIT = 2e3;
10112
11084
  function parseAndroidTouchViewport(output) {
10113
11085
  const match = /Viewport\s+INTERNAL:\s*displayId=0,[\s\S]*?(?:orientation=(\d+),\s*)?logicalFrame=\[\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*(-?\d+)\s*\],\s*physicalFrame=\[\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*(-?\d+)\s*\],\s*deviceSize=\[\s*(\d+),\s*(\d+)\s*\]/u.exec(output);
@@ -11112,6 +12084,82 @@ function containsPaintedPixels(screenshot) {
11112
12084
  }
11113
12085
  return false;
11114
12086
  }
12087
+ async function sampleHudAudit(page) {
12088
+ return page.evaluate(() => {
12089
+ const MAX_ITEMS = 400;
12090
+ const MAX_TEXT = 120;
12091
+ const parseColour = (value) => {
12092
+ const match = /^rgba?\((.+)\)$/u.exec(value.trim());
12093
+ if (match !== null) {
12094
+ const parts = match[1].split(/[\s,/]+/u).filter((part) => part !== "");
12095
+ const channels = parts.slice(0, 3).map((part) => Number.parseFloat(part));
12096
+ const alphaText = parts[3];
12097
+ const alpha = alphaText === void 0 ? 1 : Number.parseFloat(alphaText);
12098
+ const normalizedAlpha = alpha > 1 ? alpha / 255 : alpha;
12099
+ if (channels.length === 3 && channels.every((channel) => Number.isFinite(channel)) && Number.isFinite(normalizedAlpha)) {
12100
+ return [channels[0], channels[1], channels[2], Math.min(Math.max(normalizedAlpha, 0), 1)];
12101
+ }
12102
+ }
12103
+ const canvas = document.createElement("canvas");
12104
+ canvas.width = 1;
12105
+ canvas.height = 1;
12106
+ const context = canvas.getContext("2d", { willReadFrequently: true });
12107
+ if (context === null) return [0, 0, 0, 1];
12108
+ context.clearRect(0, 0, 1, 1);
12109
+ context.fillStyle = value;
12110
+ context.fillRect(0, 0, 1, 1);
12111
+ const data = context.getImageData(0, 0, 1, 1).data;
12112
+ return [data[0], data[1], data[2], data[3] / 255];
12113
+ };
12114
+ const backing = (element) => {
12115
+ let accumulated = [0, 0, 0, 0];
12116
+ for (let current = element; current !== null; current = current.parentElement) {
12117
+ const [r, g, b, a] = parseColour(window.getComputedStyle(current).backgroundColor);
12118
+ if (a > 0 && accumulated[3] < 0.99) {
12119
+ const near = accumulated[3];
12120
+ const total = near + a * (1 - near);
12121
+ if (total > 0) {
12122
+ accumulated = [
12123
+ (accumulated[0] * near + r * a * (1 - near)) / total,
12124
+ (accumulated[1] * near + g * a * (1 - near)) / total,
12125
+ (accumulated[2] * near + b * a * (1 - near)) / total,
12126
+ total
12127
+ ];
12128
+ }
12129
+ }
12130
+ if (accumulated[3] >= 0.99 || current === document.documentElement) break;
12131
+ }
12132
+ return accumulated;
12133
+ };
12134
+ const items = [];
12135
+ for (const element of document.body.querySelectorAll("*")) {
12136
+ if (items.length === MAX_ITEMS) break;
12137
+ if (element.closest("script, style, canvas, noscript") !== null) continue;
12138
+ let ownText = "";
12139
+ for (const node of element.childNodes) {
12140
+ if (node.nodeType === 3) ownText += node.textContent ?? "";
12141
+ }
12142
+ const text = ownText.replace(/\s+/gu, " ").trim();
12143
+ if (text === "") continue;
12144
+ const style = window.getComputedStyle(element);
12145
+ if (style.display === "none" || style.visibility !== "visible") continue;
12146
+ const opacity = Number.parseFloat(style.opacity);
12147
+ if (!Number.isFinite(opacity) || opacity <= 0) continue;
12148
+ const rect = element.getBoundingClientRect();
12149
+ if (rect.width <= 0 || rect.height <= 0) continue;
12150
+ if (rect.right <= 0 || rect.bottom <= 0 || rect.left >= window.innerWidth || rect.top >= window.innerHeight) continue;
12151
+ const classes = Array.from(element.classList).slice(0, 2).map((name) => `.${name}`).join("");
12152
+ items.push({
12153
+ background: backing(element),
12154
+ color: parseColour(style.color),
12155
+ fontSizePx: Number.parseFloat(style.fontSize),
12156
+ selector: `${element.tagName.toLowerCase()}${element.id === "" ? "" : `#${element.id}`}${classes}`,
12157
+ text: text.slice(0, MAX_TEXT)
12158
+ });
12159
+ }
12160
+ return { items };
12161
+ });
12162
+ }
11115
12163
  async function sampleHud(page, assertions) {
11116
12164
  if (assertions.length === 0) return {};
11117
12165
  const snapshots = await page.evaluate((requestedAssertions) => Object.fromEntries(requestedAssertions.flatMap(({ id, path: path2 }) => {
@@ -11667,9 +12715,50 @@ function regionMetrics(png, region) {
11667
12715
  if (luminance <= maximumLuminance) dark += 1;
11668
12716
  }
11669
12717
  }
11670
- return { darkPixelRatio: dark / pixels, nonblankPixelRatio: nonblank / pixels };
12718
+ return {
12719
+ darkPixelRatio: dark / pixels,
12720
+ nonblankPixelRatio: nonblank / pixels,
12721
+ ...region.minSharpness === void 0 ? {} : { sharpness: regionSharpness(png, x0, y0, x1, y1) }
12722
+ };
12723
+ }
12724
+ function regionSharpness(png, x0, y0, x1, y1) {
12725
+ const width = x1 - x0;
12726
+ const height = y1 - y0;
12727
+ const luma = new Float64Array(width * height);
12728
+ for (let y = 0; y < height; y += 1) {
12729
+ for (let x = 0; x < width; x += 1) {
12730
+ const offset = ((y0 + y) * png.width + x0 + x) * 4;
12731
+ luma[y * width + x] = 0.2126 * png.data[offset] + 0.7152 * png.data[offset + 1] + 0.0722 * png.data[offset + 2];
12732
+ }
12733
+ }
12734
+ const halfWidth = Math.floor(width / 2);
12735
+ const halfHeight = Math.floor(height / 2);
12736
+ const half = new Float64Array(halfWidth * halfHeight);
12737
+ for (let y = 0; y < halfHeight; y += 1) {
12738
+ for (let x = 0; x < halfWidth; x += 1) {
12739
+ const at = 2 * y * width + 2 * x;
12740
+ half[y * halfWidth + x] = (luma[at] + luma[at + 1] + luma[at + width] + luma[at + width + 1]) / 4;
12741
+ }
12742
+ }
12743
+ const coarse = laplacianVariance(half, halfWidth, halfHeight);
12744
+ return coarse === 0 ? 0 : laplacianVariance(luma, width, height) / coarse;
12745
+ }
12746
+ function laplacianVariance(luma, width, height) {
12747
+ let sum = 0;
12748
+ let squares = 0;
12749
+ let count = 0;
12750
+ for (let y = 1; y < height - 1; y += 1) {
12751
+ for (let x = 1; x < width - 1; x += 1) {
12752
+ const at = y * width + x;
12753
+ const value = luma[at - 1] + luma[at + 1] + luma[at - width] + luma[at + width] - 4 * luma[at];
12754
+ sum += value;
12755
+ squares += value * value;
12756
+ count += 1;
12757
+ }
12758
+ }
12759
+ return count === 0 ? 0 : squares / count - (sum / count) ** 2;
11671
12760
  }
11672
- async function runStep(page, bridge, step, viewport, pathEntity, pathPositions, inputState, movementSampleRequest, finalStep, subject, liveClock = false, cpuWindow, completionWindow) {
12761
+ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions, inputState, movementSampleRequest, finalStep, subject, liveClock = false, cpuWindow, stepWindow, sightLine) {
11673
12762
  if (step.waitForResource !== void 0) {
11674
12763
  if (bridge === void 0 || movementSampleRequest === void 0) {
11675
12764
  throw new PlaytestBridgeError(playtestDiagnostic(
@@ -11685,7 +12774,7 @@ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions,
11685
12774
  throw new PlaytestBridgeError(playtestDiagnostic(
11686
12775
  "TN_PLAYTEST_OBSERVATION_UNAVAILABLE",
11687
12776
  `Resource wait for '${wait.id}.${wait.path}' has no timeout.`,
11688
- "Validate the scenario with timeoutMs as a positive integer no greater than 120000."
12777
+ "Validate the scenario with timeoutMs as a positive integer no greater than 300000."
11689
12778
  ));
11690
12779
  }
11691
12780
  const after = await waitForResource({
@@ -11765,8 +12854,8 @@ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions,
11765
12854
  "Advertise runtime.fixedStep from the bridge so ticks are deterministic, or author the step in waitFrames/holdFrames, which are display frames and say so."
11766
12855
  ));
11767
12856
  }
11768
- if (completionWindow !== void 0) {
11769
- await completionWindow();
12857
+ if (stepWindow !== void 0) {
12858
+ await stepWindow(ticks);
11770
12859
  } else if (cpuWindow !== void 0) {
11771
12860
  if (step.kind !== "wait" || step.waitTicks !== 1e3 || ticks < 1e3 || !fixedStep || bridge === void 0 || liveClock) {
11772
12861
  throw new Error("TN_PLAYTEST_CPU_WINDOW_FAILED: measurement requires a fixed-step 1000-tick WAIT");
@@ -11775,16 +12864,19 @@ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions,
11775
12864
  await cpuWindow(() => advanceFixedStep(page, bridge, 1e3, true));
11776
12865
  await waitFrames(page, 1);
11777
12866
  await samplePathPosition(bridge, pathEntity, pathPositions);
12867
+ await sampleSightLine(bridge, sightLine);
11778
12868
  } else if (ticks > 0 && fixedStep) {
11779
12869
  const sampleTicks = 10;
11780
12870
  for (let index = 0; index < ticks; index += sampleTicks) {
11781
12871
  const batch = Math.min(sampleTicks, ticks - index);
11782
12872
  await advanceFixedStep(page, bridge, batch);
11783
12873
  await samplePathPosition(bridge, pathEntity, pathPositions);
12874
+ await sampleSightLine(bridge, sightLine);
11784
12875
  }
11785
12876
  } else {
11786
12877
  await waitFrames(page, Math.max(frames, ticks, 1));
11787
12878
  await samplePathPosition(bridge, pathEntity, pathPositions);
12879
+ await sampleSightLine(bridge, sightLine);
11788
12880
  }
11789
12881
  const afterInput = bridge === void 0 || movementSampleRequest === void 0 ? void 0 : await bridge.sample(movementSampleRequest);
11790
12882
  let afterStep = afterInput;
@@ -11933,11 +13025,11 @@ async function executeAimAtStep(bridge, step, subject) {
11933
13025
  async function advanceFixedStep(page, bridge, ticks, render = false) {
11934
13026
  if (!Number.isInteger(ticks) || ticks <= 0)
11935
13027
  throw new Error("advance ticks must be a positive integer.");
11936
- for (let tick = 0; tick < ticks; tick += 1) {
13028
+ for (let tick = 0; tick < ticks; ) {
11937
13029
  for (let attempt = 0; ; attempt += 1) {
11938
13030
  try {
11939
- if (render) await bridge.advance(1, { render: true });
11940
- else await bridge.advance(1);
13031
+ const advanced = render ? await bridge.advance(1, { render: true }) : await bridge.advance(1);
13032
+ tick += typeof advanced === "number" && advanced > 1 ? advanced : 1;
11941
13033
  break;
11942
13034
  } catch (error) {
11943
13035
  if (!(error instanceof Error) || !error.message.includes(STOPPED_LOOP_ERROR) || attempt >= MAX_FIXED_STEP_STARTUP_RETRIES)
@@ -11945,7 +13037,7 @@ async function advanceFixedStep(page, bridge, ticks, render = false) {
11945
13037
  await waitFrames(page, 1);
11946
13038
  }
11947
13039
  }
11948
- if (render && tick + 1 < ticks) await waitFrames(page, 1);
13040
+ if (render && tick < ticks) await waitFrames(page, 1);
11949
13041
  }
11950
13042
  }
11951
13043
  function playtestStepDrivesMovement(step, hasHeldInput) {
@@ -12015,6 +13107,23 @@ async function setPointerButtons(page, inputState, buttons) {
12015
13107
  }
12016
13108
  inputState.pointerButtons = buttons;
12017
13109
  }
13110
+ async function sampleFootSlip(page, bridge, ticks, label, entity, feet) {
13111
+ const samples = [];
13112
+ for (let tick = 0; tick < ticks; tick += 1) {
13113
+ await advanceFixedStep(page, bridge, 1);
13114
+ const snapshot = await bridge.sample({ entities: [entity], include: ["entities"], sceneNodes: feet.map((name) => ({ limit: 1, name })) });
13115
+ samples.push({
13116
+ body: entityPosition(snapshot, entity) ?? null,
13117
+ feet: feet.map((_name, index) => snapshot.sceneNodes?.[index]?.nodes[0]?.position ?? null)
13118
+ });
13119
+ }
13120
+ return { entity, feet, label, samples };
13121
+ }
13122
+ async function sampleSightLine(bridge, sightLine) {
13123
+ if (bridge === void 0 || sightLine === void 0) return;
13124
+ const snapshot = await bridge.sample({ sightLine: { entity: sightLine.entity } });
13125
+ if (snapshot.sightLine !== void 0) sightLine.samples.push(snapshot.sightLine);
13126
+ }
12018
13127
  async function samplePathPosition(bridge, entity, positions) {
12019
13128
  if (bridge === void 0 || entity === void 0) return;
12020
13129
  const snapshot = await bridge.sample({ entities: [entity] });
@@ -12026,18 +13135,49 @@ async function sampleAfterTransition(page, bridge, request) {
12026
13135
  await waitFrames(page, 1);
12027
13136
  return bridge.sample(request);
12028
13137
  }
12029
- async function waitFrames(page, frames) {
13138
+ async function waitFrames(page, frames, timeoutMs) {
12030
13139
  if (frames <= 0) return;
12031
- await page.evaluate((count) => new Promise((resolveFrame) => {
12032
- const schedule = globalThis.requestAnimationFrame;
12033
- let remaining = count;
12034
- const next = () => {
12035
- remaining -= 1;
12036
- if (remaining <= 0) resolveFrame();
12037
- else schedule(next);
12038
- };
12039
- schedule(next);
12040
- }), frames);
13140
+ let budgetMs;
13141
+ if (timeoutMs === void 0) {
13142
+ budgetMs = advanceTimeoutMs(frames);
13143
+ } else if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
13144
+ throw new PlaytestBridgeError(playtestDiagnostic(
13145
+ "TN_PLAYTEST_OPERATION_TIMEOUT",
13146
+ `waitFrames requested ${frames} frame(s) but the supplied remaining budget of ${String(timeoutMs)}ms is not a positive, finite value.`,
13147
+ "Check that the page is producing requestAnimationFrame callbacks; the wait cannot complete while rendering is stalled."
13148
+ ));
13149
+ } else {
13150
+ budgetMs = timeoutMs;
13151
+ }
13152
+ let timeout;
13153
+ try {
13154
+ await Promise.race([
13155
+ page.evaluate((count) => new Promise((resolveFrame) => {
13156
+ const schedule = globalThis.requestAnimationFrame;
13157
+ let remaining = count;
13158
+ const next = () => {
13159
+ remaining -= 1;
13160
+ if (remaining <= 0) resolveFrame();
13161
+ else schedule(next);
13162
+ };
13163
+ schedule(next);
13164
+ }), frames),
13165
+ new Promise((_resolve, reject) => {
13166
+ timeout = setTimeout(() => reject(new PlaytestBridgeError(playtestDiagnostic(
13167
+ "TN_PLAYTEST_OPERATION_TIMEOUT",
13168
+ `waitFrames requested ${frames} frame(s) exceeded ${budgetMs}ms.`,
13169
+ "Check that the page is producing requestAnimationFrame callbacks; the wait cannot complete while rendering is stalled."
13170
+ ))), budgetMs);
13171
+ })
13172
+ ]);
13173
+ } finally {
13174
+ if (timeout !== void 0) clearTimeout(timeout);
13175
+ }
13176
+ }
13177
+ var WARMUP_FIRST_FRAME_BUDGET_MS = 15e3;
13178
+ var WARMUP_FRAME_BUDGET_MS = 2e4;
13179
+ async function waitWarmupFrames(page, frames) {
13180
+ await waitFrames(page, frames, WARMUP_FIRST_FRAME_BUDGET_MS + frames * WARMUP_FRAME_BUDGET_MS);
12041
13181
  }
12042
13182
  function completionWindowLabel(scenario, target, live, raw = process.env.TN_PLAYTEST_COMPLETION_WINDOW_LABEL) {
12043
13183
  if (raw === void 0) return void 0;
@@ -12055,16 +13195,20 @@ async function measureCompletionWindow(label, mode, poll, release) {
12055
13195
  const fail2 = (reason) => {
12056
13196
  throw new Error(`TN_PLAYTEST_COMPLETION_WINDOW_FAILED: ${reason}`);
12057
13197
  };
12058
- const bounded = async (operation, timeoutMs = 5e3) => {
13198
+ const bounded = async (operation, timeoutMs2 = 5e3) => {
12059
13199
  let timer;
12060
13200
  try {
12061
13201
  return await Promise.race([operation(), new Promise((_resolve, reject) => {
12062
- timer = setTimeout(() => reject(new Error("TN_PLAYTEST_COMPLETION_WINDOW_FAILED: operation timeout")), timeoutMs);
13202
+ timer = setTimeout(() => reject(new Error("TN_PLAYTEST_COMPLETION_WINDOW_FAILED: operation timeout")), timeoutMs2);
12063
13203
  })]);
12064
13204
  } finally {
12065
13205
  clearTimeout(timer);
12066
13206
  }
12067
13207
  };
13208
+ const minimumFrames = Number(process.env.TN_PLAYTEST_COMPLETION_WINDOW_MIN_FRAMES ?? 101);
13209
+ const timeoutMs = Number(process.env.TN_PLAYTEST_COMPLETION_WINDOW_TIMEOUT_MS ?? 1e4);
13210
+ if (!Number.isSafeInteger(minimumFrames) || minimumFrames < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1)
13211
+ fail2("invalid completion frame count or timeout");
12068
13212
  const samples = [];
12069
13213
  let previous;
12070
13214
  let failure;
@@ -12080,7 +13224,7 @@ async function measureCompletionWindow(label, mode, poll, release) {
12080
13224
  const negotiated = await bounded(() => mode("wall-clock"));
12081
13225
  if (negotiated?.mode !== "wall-clock" || !Number.isSafeInteger(negotiated.tick) || !Number.isSafeInteger(negotiated.epoch) || negotiated.epoch < 0) fail2("clock negotiation unavailable");
12082
13226
  epoch = negotiated.epoch;
12083
- const deadline = Date.now() + 1e4;
13227
+ const deadline = Date.now() + timeoutMs;
12084
13228
  measurement: while (Date.now() <= deadline) {
12085
13229
  const value = await bounded(poll, Math.max(1, deadline - Date.now()));
12086
13230
  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"))
@@ -12109,6 +13253,7 @@ async function measureCompletionWindow(label, mode, poll, release) {
12109
13253
  samples.push({ sequence: sample.sequence, completedAtMs: sample.completedAtMs });
12110
13254
  if (sample.completedAtMs - samples[0].completedAtMs >= 5e3) {
12111
13255
  if (samples.length < 101) fail2("fewer than 100 complete intervals");
13256
+ if (samples.length < minimumFrames) continue;
12112
13257
  const intervals = samples.slice(1).map((entry, index) => entry.completedAtMs - samples[index].completedAtMs).sort((a, b) => a - b);
12113
13258
  result = {
12114
13259
  label,
@@ -12670,6 +13815,9 @@ var PlaytestCliUsageError = class extends Error {
12670
13815
  this.name = "PlaytestCliUsageError";
12671
13816
  }
12672
13817
  };
13818
+ function withScenarioClock(config, scenario) {
13819
+ return scenario.clock === "wall-clock" && config.liveClock !== true ? { ...config, liveClock: true } : config;
13820
+ }
12673
13821
  function formatUsage() {
12674
13822
  const flags = Object.entries(PLAYTEST_FLAGS).map(
12675
13823
  ([name, details]) => ` ${name.padEnd(20)} ${details.summary} (default: ${details.default})`
@@ -12905,7 +14053,7 @@ function parseStandalonePlaytestArgs(argv, cwd = process.cwd()) {
12905
14053
  ...flags.get("--xcrun")?.[0] === void 0 ? {} : { xcrunPath: flags.get("--xcrun")[0] }
12906
14054
  };
12907
14055
  }
12908
- var SCENARIO_GLOB = /[*?[]/u;
14056
+ var SCENARIO_GLOB = /[*?[{]/u;
12909
14057
  function expandScenarioPattern(projectPath, pattern) {
12910
14058
  if (!SCENARIO_GLOB.test(pattern)) return [pattern];
12911
14059
  const normalizedPattern = pattern.replaceAll("\\", "/");
@@ -12942,14 +14090,21 @@ function matchGlobParts(pattern, file) {
12942
14090
  return file.length > 0 && segmentMatches(head ?? "", file[0]) && matchGlobParts(tail, file.slice(1));
12943
14091
  }
12944
14092
  function segmentMatches(pattern, value) {
12945
- let expression = "^";
14093
+ return new RegExp(`^${segmentExpression(pattern)}$`, "u").test(value);
14094
+ }
14095
+ function segmentExpression(pattern) {
14096
+ let expression = "";
12946
14097
  for (let index = 0; index < pattern.length; index += 1) {
12947
14098
  const character = pattern[index];
12948
- if (character === "*") expression += "[^/]*";
14099
+ const close = character === "{" ? pattern.indexOf("}", index) : -1;
14100
+ if (close > index) {
14101
+ expression += `(?:${pattern.slice(index + 1, close).split(",").map(segmentExpression).join("|")})`;
14102
+ index = close;
14103
+ } else if (character === "*") expression += "[^/]*";
12949
14104
  else if (character === "?") expression += "[^/]";
12950
14105
  else expression += escapeRegExp(character);
12951
14106
  }
12952
- return new RegExp(`${expression}$`, "u").test(value);
14107
+ return expression;
12953
14108
  }
12954
14109
  function escapeRegExp(value) {
12955
14110
  return value.replace(/[|\\{}()[\]^$+?.]/gu, "\\$&");
@@ -13016,12 +14171,12 @@ function withPerformanceBudget(scenario, budget) {
13016
14171
  maxPassTriangles: { ...budget.maxPassTriangles, ...declared?.maxPassTriangles },
13017
14172
  maxPhaseMsP95: { ...budget.maxPhaseMsP95, ...declared?.maxPhaseMsP95 }
13018
14173
  };
13019
- const performance = {
14174
+ const performance2 = {
13020
14175
  ...budget,
13021
14176
  ...declared,
13022
14177
  ...Object.fromEntries(Object.entries(maps).filter(([, value]) => Object.keys(value).length > 0))
13023
14178
  };
13024
- return { ...scenario, assert: { ...scenario.assert, performance } };
14179
+ return { ...scenario, assert: { ...scenario.assert, performance: performance2 } };
13025
14180
  }
13026
14181
 
13027
14182
  // src/runner/camera.ts
@@ -13325,11 +14480,11 @@ function isJudgeMarkerRequestFailure(method, url, judgeMarkerUrl) {
13325
14480
  function addPreflightDiagnostic(report, diagnostic) {
13326
14481
  return diagnostic === void 0 ? report : { ...report, diagnostics: [diagnostic, ...report.diagnostics] };
13327
14482
  }
13328
- 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;
14483
+ 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;
13329
14484
  function isSoftwareDeviceLossEntry(entry) {
13330
14485
  return (entry.type === "error" || entry.type === "assert" || entry.type === "pageerror") && SOFTWARE_DEVICE_LOSS.test(entry.text);
13331
14486
  }
13332
- 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) {
14487
+ 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) {
13333
14488
  const movementSample = isAnonymousMovementScenario(scenario) ? observedMovementSample(movementSamples) : void 0;
13334
14489
  const entity = scenario.assert?.movement?.entity ?? scenario.subject ?? movementSample?.entity ?? "";
13335
14490
  const wholeRunObserved = isAnonymousMovementScenario(scenario) ? false : entityPosition(beforeSnapshot, entity) !== void 0 && entityPosition(afterSnapshot, entity) !== void 0;
@@ -13419,6 +14574,9 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
13419
14574
  // room does. Never merged with the first: a node that has since been removed is gone, and
13420
14575
  // reporting it from the earlier sample would assert against a scene that no longer exists.
13421
14576
  ...afterSnapshot?.sceneNodes === void 0 && beforeSnapshot?.sceneNodes === void 0 ? {} : { sceneNodes: afterSnapshot?.sceneNodes ?? beforeSnapshot?.sceneNodes },
14577
+ ...footSlip === void 0 ? {} : { footSlip },
14578
+ ...sightLine === void 0 ? {} : { sightLine },
14579
+ ...hudAudit === void 0 ? {} : { hudAudit },
13422
14580
  ...startup === void 0 ? {} : { startup },
13423
14581
  ...beforeSnapshot?.gameplay === void 0 && afterSnapshot?.gameplay === void 0 && labeledSamples.every(({ snapshot }) => snapshot.gameplay === void 0) ? {} : {
13424
14582
  runtimeObservations: {
@@ -13509,43 +14667,74 @@ function entityObservedWindow(samples, entity) {
13509
14667
  // src/runner/startupReady.ts
13510
14668
  async function waitForStartupReady(options) {
13511
14669
  const { bridge, pump } = options;
13512
- if (!bridge.description.capabilities.includes("runtime.startup")) return void 0;
14670
+ if (!bridge.description.capabilities.includes("runtime.startup")) {
14671
+ await options.warmup?.();
14672
+ return void 0;
14673
+ }
13513
14674
  const now = options.now ?? (() => Date.now());
13514
14675
  const timeoutMs = options.timeoutMs ?? PLAYTEST_STARTUP_READY_TIMEOUT_MS;
13515
14676
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
13516
14677
  throw new Error(`TN_PLAYTEST_STARTUP_TIMEOUT_INVALID: ${String(options.timeoutMs)}`);
14678
+ await options.warmup?.();
13517
14679
  const deadline = now() + timeoutMs;
13518
14680
  const aborted = options.aborted ?? (() => false);
13519
14681
  if (aborted()) throw abortedDuringStartup();
13520
14682
  const hostAlive = options.hostAlive ?? (async () => void 0);
13521
- let observed = await pollStartup(bridge);
13522
- while (observed === BUSY || observed.phase !== "ready") {
13523
- if (aborted()) throw abortedDuringStartup();
13524
- if (observed === BUSY && await hostAlive() === false) throw hostExitedDuringStartup();
13525
- if (now() >= deadline) {
13526
- throw new PlaytestBridgeError(playtestDiagnostic(
13527
- "TN_PLAYTEST_STARTUP_NOT_READY",
13528
- `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.`,
13529
- "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."
13530
- ));
13531
- }
13532
- try {
13533
- await pump();
13534
- } catch (error) {
13535
- if (error instanceof PlaytestBridgeError && error.diagnostic.code === "TN_PLAYTEST_OPERATION_TIMEOUT") {
13536
- observed = BUSY;
13537
- continue;
14683
+ let observed = BUSY;
14684
+ const timeoutError = () => new PlaytestBridgeError(playtestDiagnostic(
14685
+ "TN_PLAYTEST_STARTUP_NOT_READY",
14686
+ `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.`,
14687
+ "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."
14688
+ ));
14689
+ let settled = false;
14690
+ let timeout;
14691
+ const expired = new Promise((_resolve, reject) => {
14692
+ timeout = setTimeout(() => {
14693
+ settled = true;
14694
+ reject(timeoutError());
14695
+ }, timeoutMs);
14696
+ });
14697
+ try {
14698
+ return await Promise.race([expired, (async () => {
14699
+ if (settled) throw timeoutError();
14700
+ if (aborted()) throw abortedDuringStartup();
14701
+ if (settled || now() >= deadline) throw timeoutError();
14702
+ observed = await pollStartup(bridge);
14703
+ while (observed === BUSY || observed.phase !== "ready" || observed.revealed === false) {
14704
+ if (settled) throw timeoutError();
14705
+ if (aborted()) throw abortedDuringStartup();
14706
+ if (observed === BUSY) {
14707
+ const alive = await hostAlive();
14708
+ if (settled) throw timeoutError();
14709
+ if (alive === false) throw hostExitedDuringStartup();
14710
+ }
14711
+ if (settled || now() >= deadline) {
14712
+ throw timeoutError();
14713
+ }
14714
+ try {
14715
+ await pump(deadline - now());
14716
+ } catch (error) {
14717
+ if (error instanceof PlaytestBridgeError && error.diagnostic.code === "TN_PLAYTEST_OPERATION_TIMEOUT") {
14718
+ observed = BUSY;
14719
+ continue;
14720
+ }
14721
+ throw error;
14722
+ }
14723
+ if (settled || now() >= deadline) throw timeoutError();
14724
+ observed = await pollStartup(bridge);
13538
14725
  }
13539
- throw error;
13540
- }
13541
- observed = await pollStartup(bridge);
14726
+ if (settled || now() >= deadline) throw timeoutError();
14727
+ return {
14728
+ // A declared software lane reaches `ready` on the bounded window rather than on sustained
14729
+ // in-budget frames, so it is labelled for what it is: not a smoothness measurement.
14730
+ rule: options.declaredSoftware === true ? "compile-settled" : "sustained-frames",
14731
+ startup: observed
14732
+ };
14733
+ })()]);
14734
+ } finally {
14735
+ settled = true;
14736
+ if (timeout !== void 0) clearTimeout(timeout);
13542
14737
  }
13543
- return {
13544
- // A declared software lane reaches `ready` on the bounded window rather than on sustained
13545
- // in-budget frames, so it is labelled for what it is: not a smoothness measurement.
13546
- rule: options.declaredSoftware === true ? "compile-settled" : "sustained-frames",
13547
- startup: observed
13548
- };
13549
14738
  }
13550
14739
  function abortedDuringStartup() {
13551
14740
  return new PlaytestBridgeError(playtestDiagnostic(
@@ -13933,6 +15122,23 @@ function createOwnedRunResourceRelease(display, lease) {
13933
15122
  return releasePromise;
13934
15123
  };
13935
15124
  }
15125
+
15126
+ // src/runner/network.ts
15127
+ function networkBytesPerSecond(downloadKbps) {
15128
+ return downloadKbps * 1e3 / 8;
15129
+ }
15130
+ function networkEmulation(profile) {
15131
+ const bytesPerSecond = networkBytesPerSecond(profile.downloadKbps);
15132
+ return {
15133
+ connectionType: "cellular3g",
15134
+ downloadThroughput: bytesPerSecond,
15135
+ latency: profile.latencyMs,
15136
+ offline: false,
15137
+ uploadThroughput: bytesPerSecond
15138
+ };
15139
+ }
15140
+
15141
+ // src/runner/server.ts
13936
15142
  function startManagedServer(config, dynamicPort) {
13937
15143
  const port = dynamicPort ?? managedPort(config);
13938
15144
  return spawn(resolveManagedServerCommand(config, dynamicPort), {
@@ -14055,7 +15261,17 @@ function pageLifecycleDiagnostic(error, lifecycle, url) {
14055
15261
  "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."
14056
15262
  );
14057
15263
  }
15264
+ var throttledPages = /* @__PURE__ */ new WeakMap();
15265
+ async function applyNetworkProfile(page, scenario) {
15266
+ const profile = scenario.network;
15267
+ if (profile === void 0) return;
15268
+ const session = await page.context().newCDPSession(page);
15269
+ await session.send("Network.enable");
15270
+ await session.send("Network.emulateNetworkConditions", networkEmulation(profile));
15271
+ throttledPages.set(page, session);
15272
+ }
14058
15273
  async function openPageAndConnectBridge(page, config, scenario) {
15274
+ await applyNetworkProfile(page, scenario);
14059
15275
  const attempts = 3;
14060
15276
  let lastError;
14061
15277
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
@@ -14155,6 +15371,98 @@ async function retakeWhileBlank(retake, grace, boundMs, now = Date.now) {
14155
15371
  }
14156
15372
  }
14157
15373
  }
15374
+ var CHANNEL_TOLERANCE = 48;
15375
+ var DIFFERING_SHARE = 0.25;
15376
+ var UI_OVER_COVER_SHARE = 5e-3;
15377
+ var FIRST_PAINT_SLACK_MS = 8;
15378
+ var HANDOFF_FRAMES = 30;
15379
+ function meanColour(frame) {
15380
+ const sum = [0, 0, 0];
15381
+ const pixels = frame.width * frame.height;
15382
+ for (let i = 0; i < pixels; i += 1) {
15383
+ sum[0] += frame.data[i * 4] ?? 0;
15384
+ sum[1] += frame.data[i * 4 + 1] ?? 0;
15385
+ sum[2] += frame.data[i * 4 + 2] ?? 0;
15386
+ }
15387
+ return sum.map((value) => Math.round(value / Math.max(1, pixels)));
15388
+ }
15389
+ function differingShare(frame, reference) {
15390
+ if (frame.width !== reference.width || frame.height !== reference.height) return 1;
15391
+ const pixels = frame.width * frame.height;
15392
+ let moved = 0;
15393
+ for (let i = 0; i < pixels; i += 1) {
15394
+ for (let channel = 0; channel < 3; channel += 1) {
15395
+ if (Math.abs((frame.data[i * 4 + channel] ?? 0) - (reference.data[i * 4 + channel] ?? 0)) > CHANNEL_TOLERANCE) {
15396
+ moved += 1;
15397
+ break;
15398
+ }
15399
+ }
15400
+ }
15401
+ return moved / Math.max(1, pixels);
15402
+ }
15403
+ function uiShare(frame, cover, world) {
15404
+ if (frame.width !== cover.width || frame.width !== world.width || frame.height !== cover.height || frame.height !== world.height) return 0;
15405
+ const pixels = frame.width * frame.height;
15406
+ let ui = 0;
15407
+ for (let i = 0; i < pixels; i += 1) {
15408
+ let offCover = false;
15409
+ let onWorld = true;
15410
+ for (let channel = 0; channel < 3; channel += 1) {
15411
+ const value = frame.data[i * 4 + channel] ?? 0;
15412
+ if (Math.abs(value - (cover.data[i * 4 + channel] ?? 0)) > CHANNEL_TOLERANCE) offCover = true;
15413
+ if (Math.abs(value - (world.data[i * 4 + channel] ?? 0)) > CHANNEL_TOLERANCE) onWorld = false;
15414
+ }
15415
+ if (offCover && onWorld) ui += 1;
15416
+ }
15417
+ return ui / Math.max(1, pixels);
15418
+ }
15419
+ function compareStartupFrames(frames, readyMs = Number.POSITIVE_INFINITY, firstPaintMs = 0) {
15420
+ const startup = frames.filter((frame) => frame.ms >= firstPaintMs - FIRST_PAINT_SLACK_MS && frame.ms < readyMs);
15421
+ const handOff = frames.filter((frame) => frame.ms >= readyMs);
15422
+ const reference = startup.at(-1);
15423
+ if (reference === void 0) return { differing: [], frames: 0, reference: [0, 0, 0], uiOverCover: [] };
15424
+ const differing = [];
15425
+ for (const frame of startup) {
15426
+ const share = differingShare(frame, reference);
15427
+ if (share > DIFFERING_SHARE) differing.push({ mean: meanColour(frame), ms: Math.round(frame.ms), share: Number(share.toFixed(3)) });
15428
+ }
15429
+ const observation = { differing, frames: startup.length, reference: meanColour(reference), uiOverCover: [] };
15430
+ if (!Number.isFinite(readyMs)) return observation;
15431
+ const worldIndex = handOff.findIndex((frame) => differingShare(frame, reference) > DIFFERING_SHARE);
15432
+ const world = handOff[worldIndex];
15433
+ if (world === void 0) return observation;
15434
+ observation.worldMs = Math.round(world.ms);
15435
+ for (const frame of handOff.slice(0, worldIndex)) {
15436
+ const share = uiShare(frame, reference, world);
15437
+ if (share > UI_OVER_COVER_SHARE) observation.uiOverCover.push({ ms: Math.round(frame.ms), share: Number(share.toFixed(4)) });
15438
+ }
15439
+ return observation;
15440
+ }
15441
+ async function recordStartupCover(page) {
15442
+ const cdp = await page.context().newCDPSession(page);
15443
+ const frames = [];
15444
+ cdp.on("Page.screencastFrame", ({ data, metadata, sessionId }) => {
15445
+ frames.push({ epochMs: (metadata.timestamp ?? Date.now() / 1e3) * 1e3, png: Buffer.from(data, "base64") });
15446
+ void cdp.send("Page.screencastFrameAck", { sessionId }).catch(() => void 0);
15447
+ });
15448
+ await cdp.send("Page.startScreencast", { everyNthFrame: 1, format: "png", maxHeight: 72, maxWidth: 128 });
15449
+ return {
15450
+ async finish(readyMs) {
15451
+ await waitFrames(page, HANDOFF_FRAMES).catch(() => void 0);
15452
+ await cdp.send("Page.stopScreencast").catch(() => void 0);
15453
+ await cdp.detach().catch(() => void 0);
15454
+ const [origin, firstPaint] = await page.evaluate(() => [
15455
+ performance.timeOrigin,
15456
+ performance.getEntriesByName("first-paint")[0]?.startTime ?? 0
15457
+ ]);
15458
+ const startup = frames.filter(({ epochMs }) => epochMs >= origin).map(({ epochMs, png }) => {
15459
+ const image = PNG.sync.read(png);
15460
+ return { data: image.data, height: image.height, ms: epochMs - origin, width: image.width };
15461
+ });
15462
+ return compareStartupFrames(startup, readyMs, firstPaint);
15463
+ }
15464
+ };
15465
+ }
14158
15466
  var REMOTE_BROWSER_SESSIONS = /* @__PURE__ */ new WeakMap();
14159
15467
  function remoteBrowserFor(config) {
14160
15468
  return REMOTE_BROWSER_SESSIONS.get(config);
@@ -14312,6 +15620,14 @@ async function writeObservationArtifacts(artifactDirectory, requested, observati
14312
15620
  }
14313
15621
  return written;
14314
15622
  }
15623
+ var WorkerGameRelaunch = class extends Error {
15624
+ };
15625
+ async function runsGameInWorker(page) {
15626
+ for (const worker of page.workers()) {
15627
+ if (await worker.evaluate("typeof globalThis.__tnGamePlatform").catch(() => void 0) === "object") return true;
15628
+ }
15629
+ return false;
15630
+ }
14315
15631
  async function runStandalonePlaytest(config, options = {}) {
14316
15632
  return runStandalonePlaytestInternal(config, {
14317
15633
  ...options,
@@ -14319,12 +15635,25 @@ async function runStandalonePlaytest(config, options = {}) {
14319
15635
  });
14320
15636
  }
14321
15637
  async function runStandalonePlaytestInternal(config, options = {}) {
15638
+ try {
15639
+ return await runStandalonePlaytestOnce(config, options);
15640
+ } catch (error) {
15641
+ if (!(error instanceof WorkerGameRelaunch)) throw error;
15642
+ return runStandalonePlaytestOnce(config, { ...options, gameThread: "worker" });
15643
+ }
15644
+ }
15645
+ async function runStandalonePlaytestOnce(config, options) {
14322
15646
  const usesFreePort = config.server !== void 0 && config.port === 0;
14323
- const activeConfig = usesFreePort ? await resolveManagedServerConfig(config) : config;
15647
+ const resolvedConfig = usesFreePort ? await resolveManagedServerConfig(config) : config;
14324
15648
  const scenario = withPerformanceBudget(
14325
- await loadPlaytestScenario(activeConfig.projectPath, activeConfig.scenarioPath),
14326
- activeConfig.performanceBudget
15649
+ await loadPlaytestScenario(resolvedConfig.projectPath, resolvedConfig.scenarioPath),
15650
+ resolvedConfig.performanceBudget
14327
15651
  );
15652
+ let activeConfig = withScenarioClock(resolvedConfig, scenario);
15653
+ const performance2 = scenario.assert?.performance;
15654
+ if ((activeConfig.target ?? "browser") === "browser" && activeConfig.liveClock === void 0 && (performance2?.maxFrameMsP95 !== void 0 || performance2?.minFps !== void 0)) {
15655
+ activeConfig = { ...activeConfig, liveClock: true };
15656
+ }
14328
15657
  const cpuLabels = cpuWindowLabels(scenario, "browser", activeConfig.liveClock === true);
14329
15658
  if (cpuLabels.length > 0 && options.remoteBrowser !== void 0) {
14330
15659
  throw new Error("TN_PLAYTEST_CPU_WINDOW_FAILED: remote browser has no local owned process tree");
@@ -14334,11 +15663,12 @@ async function runStandalonePlaytestInternal(config, options = {}) {
14334
15663
  let completionWindow;
14335
15664
  const completionDisplay = completionLabel === void 0 ? void 0 : completionWindowEnvironment("browser", activeConfig.headless);
14336
15665
  if (completionLabel !== void 0 && options.remoteBrowser !== void 0) throw new Error("TN_PLAYTEST_COMPLETION_WINDOW_FAILED: requires a fresh local browser process");
14337
- const browserConfig = scenario.assert?.performance === void 0 && completionLabel === void 0 ? activeConfig : {
15666
+ const measurementArgs = measurementBrowserArgs(scenario.assert?.performance !== void 0, completionLabel !== void 0, frameDisplay(), options.gameThread);
15667
+ const browserConfig = measurementArgs.length === 0 ? activeConfig : {
14338
15668
  ...activeConfig,
14339
15669
  browserArgs: [
14340
15670
  ...activeConfig.browserArgs ?? [],
14341
- ...PERFORMANCE_BROWSER_ARGS.filter((argument) => !activeConfig.browserArgs?.includes(argument))
15671
+ ...measurementArgs.filter((argument) => !activeConfig.browserArgs?.includes(argument))
14342
15672
  ]
14343
15673
  };
14344
15674
  await mkdir(activeConfig.artifactDirectory, { recursive: true });
@@ -14488,6 +15818,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
14488
15818
  await page.addInitScript((liveClock) => {
14489
15819
  globalThis.__THREENATIVE_PLAYTEST_RUNNER_EXPECTED__ = true;
14490
15820
  if (liveClock) globalThis.__THREENATIVE_PLAYTEST_CLOCK__ = "wall-clock";
15821
+ globalThis.__THREENATIVE_ENGINE_COST__ = true;
14491
15822
  window.addEventListener("unhandledrejection", (event) => {
14492
15823
  const reason = event.reason instanceof Error ? event.reason.stack || event.reason.message : String(event.reason);
14493
15824
  console.error(`__THREENATIVE_PLAYTEST_UNHANDLED_REJECTION__:${reason}`);
@@ -14524,7 +15855,9 @@ async function runStandalonePlaytestInternal(config, options = {}) {
14524
15855
  pageLifecycle.closed = true;
14525
15856
  });
14526
15857
  const activePage = page;
15858
+ const coverRecorder = scenario.assert?.startup?.steadyCover === true ? await recordStartupCover(page) : void 0;
14527
15859
  const bridge = await openRunnerPage(page, browserConfig, scenario, options.remoteBrowser);
15860
+ if (options.gameThread === void 0 && measurementArgs.includes("--disable-frame-rate-limit") && await runsGameInWorker(page)) throw new WorkerGameRelaunch();
14528
15861
  pageLifecycle.settled = true;
14529
15862
  const setupApplication2 = bridge?.setupApplication;
14530
15863
  if (scenario.setup !== void 0) {
@@ -14536,13 +15869,16 @@ async function runStandalonePlaytestInternal(config, options = {}) {
14536
15869
  ));
14537
15870
  }
14538
15871
  }
14539
- await waitFrames(page, scenario.warmupFrames);
15872
+ if (bridge === void 0 || scenario.awaitStartup === false) await waitFrames(page, scenario.warmupFrames);
14540
15873
  const startupOutcome = bridge === void 0 || scenario.awaitStartup === false ? void 0 : await waitForStartupReady({
14541
15874
  aborted: () => tearingDown,
14542
15875
  bridge,
14543
15876
  declaredSoftware: activeConfig.allowSoftwareAdapter === true,
14544
- pump: () => waitFrames(activePage, 1)
15877
+ warmup: () => waitWarmupFrames(activePage, scenario.warmupFrames),
15878
+ pump: (remainingMs) => waitFrames(activePage, 1, remainingMs)
14545
15879
  });
15880
+ const readyMs = startupOutcome?.startup.timeline?.readyMs;
15881
+ const startupCover = coverRecorder === void 0 || readyMs === void 0 ? void 0 : await coverRecorder.finish(readyMs);
14546
15882
  await alignScenarioStartTick(bridge, scenario.startTick, activeConfig.liveClock === true);
14547
15883
  const runtimeReady = await page.evaluate(
14548
15884
  () => document.readyState !== "loading" && document.querySelector("canvas") !== null
@@ -14731,6 +16067,16 @@ async function runStandalonePlaytestInternal(config, options = {}) {
14731
16067
  if (activeConfig.cpuProfilePath !== void 0) {
14732
16068
  cpuProfile = await startBrowserCpuProfile(activePage, activeConfig.cpuProfilePath);
14733
16069
  }
16070
+ const footSlip = [];
16071
+ const footSlipAt = (label) => label === void 0 ? void 0 : scenario.assert?.footSlip?.find(({ atStep }) => atStep === label);
16072
+ const sightLineAssertion = scenario.assert?.sightLine;
16073
+ const sightLineEntity = sightLineAssertion?.entity ?? scenario.subject;
16074
+ const sightLine = sightLineAssertion === void 0 || sightLineEntity === void 0 ? void 0 : { entity: sightLineEntity, samples: [] };
16075
+ const drawnTicks = scenario.assert?.engineCost === void 0 || bridge === void 0 || activeConfig.liveClock === true || !bridge.description.capabilities.includes("runtime.fixedStep") ? void 0 : async (ticks) => {
16076
+ await advanceFixedStep(activePage, bridge, ticks, true);
16077
+ await samplePathPosition(bridge, pathEntity, pathPositions);
16078
+ await sampleSightLine(bridge, sightLine);
16079
+ };
14734
16080
  for (const [index, step] of scenario.steps.entries()) {
14735
16081
  const framebufferAssertion = scenario.assert?.framebufferCoverage;
14736
16082
  if (framebufferAssertion !== void 0 && step.label === framebufferAssertion.window.startStep) {
@@ -14783,7 +16129,17 @@ async function runStandalonePlaytestInternal(config, options = {}) {
14783
16129
  }
14784
16130
  );
14785
16131
  completionWindow.setupSnapshot = setupSnapshot;
14786
- } : void 0
16132
+ } : footSlipAt(step.label) === void 0 ? drawnTicks : async (ticks) => {
16133
+ const assertion = footSlipAt(step.label);
16134
+ const entity = assertion.entity ?? scenario.subject;
16135
+ if (bridge === void 0 || entity === void 0 || activeConfig.liveClock === true || !bridge.description.capabilities.includes("runtime.fixedStep")) {
16136
+ throw new Error("TN_PLAYTEST_FOOT_SLIP_UNOBSERVED: footSlip needs a fixed-step bridge and a subject entity");
16137
+ }
16138
+ footSlip.push(await sampleFootSlip(activePage, bridge, ticks, step.label, entity, assertion.feet));
16139
+ await samplePathPosition(bridge, pathEntity, pathPositions);
16140
+ await sampleSightLine(bridge, sightLine);
16141
+ },
16142
+ sightLine
14787
16143
  );
14788
16144
  if (movementBaselineSnapshot === void 0 && movementNeedsBaseline && movementEntity !== void 0) {
14789
16145
  const candidate = stepSamples.afterStep ?? stepSamples.afterInput;
@@ -14827,6 +16183,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
14827
16183
  if (position !== void 0) pathPositions.push(position);
14828
16184
  }
14829
16185
  const afterHud = await sampleHud(page, hudAssertions);
16186
+ const hudAudit = scenario.assert?.hudAudit === void 0 ? void 0 : await sampleHudAudit(page);
14830
16187
  const afterScreenshot = scenario.artifacts?.screenshots !== false && artifactFrames || wantsVisual || wantsFinalTone ? wantsVisual || wantsFinalTone ? await captureVisualPage(
14831
16188
  "after.png",
14832
16189
  scenario.artifacts?.screenshots === false ? void 0 : join(activeConfig.artifactDirectory, "after.png")
@@ -14861,9 +16218,16 @@ async function runStandalonePlaytestInternal(config, options = {}) {
14861
16218
  setupApplication2,
14862
16219
  deviceMetrics,
14863
16220
  movementBaselineSnapshot,
14864
- startupOutcome === void 0 ? void 0 : { ...startupOutcome.startup, rule: startupOutcome.rule },
16221
+ startupOutcome === void 0 ? void 0 : {
16222
+ ...startupOutcome.startup,
16223
+ rule: startupOutcome.rule,
16224
+ ...startupCover === void 0 ? {} : { cover: startupCover }
16225
+ },
14865
16226
  void 0,
14866
- tone
16227
+ tone,
16228
+ footSlip.length === 0 ? void 0 : footSlip,
16229
+ sightLine === void 0 || sightLine.samples.length === 0 ? void 0 : sightLine,
16230
+ hudAudit
14867
16231
  );
14868
16232
  if (cpuWindows.length !== cpuLabels.length) throw new Error("TN_PLAYTEST_CPU_WINDOW_FAILED: missing requested CPU window");
14869
16233
  if (completionWindow !== void 0) {
@@ -14874,6 +16238,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
14874
16238
  browserArgs: resolveBrowserArguments(browserConfig.browserArgs)
14875
16239
  };
14876
16240
  }
16241
+ if (options.gameThread !== void 0) report.gameThread = options.gameThread;
14877
16242
  report.acquisition = { requestUrls: [...requestUrls], ...cpuLabels.length === 0 ? {} : { cpuWindows }, ...completionWindow === void 0 ? {} : { completionWindow } };
14878
16243
  await writeObservationArtifacts(activeConfig.artifactDirectory, scenario.artifacts, {
14879
16244
  console: consoleEntries,
@@ -14886,6 +16251,7 @@ async function runStandalonePlaytestInternal(config, options = {}) {
14886
16251
  else await page.close();
14887
16252
  return addPreflightDiagnostic(report, preflight);
14888
16253
  } catch (error) {
16254
+ if (error instanceof WorkerGameRelaunch) throw error;
14889
16255
  try {
14890
16256
  if (!observationArtifactsWritten) await writeObservationArtifacts(activeConfig.artifactDirectory, scenario.artifacts, {
14891
16257
  console: consoleEntries,
@@ -15312,7 +16678,9 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
15312
16678
  // this the wait reads that as a slow loading gate and burns its whole deadline; with it
15313
16679
  // the report names the exit and carries the console tail that says why.
15314
16680
  hostAlive: () => target.driver.isAlive().catch(() => void 0),
15315
- pump: () => attached.advance(1)
16681
+ pump: async () => {
16682
+ await attached.advance(1);
16683
+ }
15316
16684
  });
15317
16685
  await throwIfAborted(target);
15318
16686
  for (let frame = 0; frame < scenario.warmupFrames; frame += 1) {
@@ -15348,7 +16716,7 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
15348
16716
  const before = await bridge.sample(sampleRequest);
15349
16717
  if (completionLabel !== void 0 && before.clock.mode !== "fixed-step") throw new Error("TN_PLAYTEST_COMPLETION_WINDOW_FAILED: prefix requires fixed-step clock");
15350
16718
  if (scenario.artifacts?.screenshots === "before-after" && config.captureArtifactScreenshots !== false) {
15351
- await captureDeviceScreenshot(target, join(config.artifactDirectory, "before.png"), tone, "before.png", void 0, renderOnly);
16719
+ await captureDeviceScreenshot(target, join(config.artifactDirectory, "before.png"), tone, "before.png", void 0, renderOnly, scenario.assert?.tone);
15352
16720
  }
15353
16721
  const pathEntity = scenario.assert?.movement?.pathLength === void 0 ? void 0 : scenario.assert.movement.entity ?? scenario.subject;
15354
16722
  const pathPositions = [];
@@ -15401,12 +16769,14 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
15401
16769
  throw new PlaytestBridgeError(playtestDiagnostic(
15402
16770
  "TN_PLAYTEST_OBSERVATION_UNAVAILABLE",
15403
16771
  `Resource wait for '${wait.id}.${wait.path}' has no timeout.`,
15404
- "Validate the scenario with timeoutMs as a positive integer no greater than 120000."
16772
+ "Validate the scenario with timeoutMs as a positive integer no greater than 300000."
15405
16773
  ));
15406
16774
  }
15407
16775
  const attachedBridge = bridge;
15408
16776
  afterInput = await waitForResource({
15409
- advance: () => attachedBridge.advance(1),
16777
+ advance: async () => {
16778
+ await attachedBridge.advance(1);
16779
+ },
15410
16780
  id: wait.id,
15411
16781
  path: wait.path,
15412
16782
  predicate: wait,
@@ -15507,7 +16877,9 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
15507
16877
  const pid = target.driver.processId;
15508
16878
  if (pid === void 0) throw new Error("TN_PLAYTEST_CPU_WINDOW_FAILED: native child PID unavailable");
15509
16879
  return { rootPid: pid, pid, tid: pid };
15510
- }, measuredBridge, () => measuredBridge.advance(1e3)));
16880
+ }, measuredBridge, async () => {
16881
+ await measuredBridge.advance(1e3);
16882
+ }));
15511
16883
  } finally {
15512
16884
  if (holdRender) await transport.call("_holdAutomaticRender", false);
15513
16885
  }
@@ -15534,7 +16906,7 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
15534
16906
  const wantsStepTone = step.label !== void 0 && scenario.assert?.tone?.some(({ atStep }) => atStep === step.label) === true;
15535
16907
  if (step.screenshot !== void 0 || wantsStepTone) {
15536
16908
  const label = step.screenshot === void 0 ? `tone-${index}.png` : `${safePart(step.screenshot)}.png`;
15537
- await captureDeviceScreenshot(target, join(config.artifactDirectory, label), tone, label, step.label, renderOnly);
16909
+ await captureDeviceScreenshot(target, join(config.artifactDirectory, label), tone, label, step.label, renderOnly, scenario.assert?.tone);
15538
16910
  }
15539
16911
  if (step.release && pressed !== void 0) {
15540
16912
  const released = typeof pressed === "string" ? [pressed] : [...pressed];
@@ -15583,7 +16955,7 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
15583
16955
  metrics?.stop();
15584
16956
  await metrics?.sampleNow("after").catch(() => void 0);
15585
16957
  if (scenario.artifacts?.screenshots !== false || scenario.assert?.tone?.some(({ atStep }) => atStep === void 0) === true) {
15586
- await captureDeviceScreenshot(target, join(config.artifactDirectory, "after.png"), tone, "after.png", void 0, renderOnly);
16958
+ await captureDeviceScreenshot(target, join(config.artifactDirectory, "after.png"), tone, "after.png", void 0, renderOnly, scenario.assert?.tone);
15587
16959
  }
15588
16960
  if (!await target.driver.isAlive()) {
15589
16961
  return failureReport(config, scenario, playtestDiagnostic(
@@ -15717,11 +17089,12 @@ async function runDevicePlaytestInternal(config, target, cleanupState) {
15717
17089
  if (cleanupErrors.length > 0) cleanupState.error = cleanupFailure(cleanupErrors);
15718
17090
  }
15719
17091
  }
15720
- async function captureDeviceScreenshot(target, path2, tone, label, atStep, renderOnly) {
17092
+ async function captureDeviceScreenshot(target, path2, tone, label, atStep, renderOnly, toneAssertions = []) {
15721
17093
  await target.driver.screenshot(path2, renderOnly);
15722
17094
  const png = await readFile(path2);
15723
17095
  const stats = target.name === "desktop" ? assertDesktopCaptureNotBlank(png, path2) : assertCaptureNotBlank(png, path2);
15724
17096
  if (stats.tone !== void 0) tone.push({ code: "TN_TONE", label, ...atStep === void 0 ? {} : { atStep }, ...stats.tone });
17097
+ tone.push(...collectRegionalTone(png, toneAssertions, label, atStep));
15725
17098
  }
15726
17099
  function deviceMetricsRecorder(target) {
15727
17100
  if (target.name !== "android") return void 0;
@@ -16149,21 +17522,15 @@ var LocalDeviceMailbox = class {
16149
17522
  }
16150
17523
  }
16151
17524
  async remove(path2) {
16152
- for (let retry = 0; ; retry += 1) {
16153
- try {
16154
- await rm(path2, { force: true });
16155
- return;
16156
- } catch (error) {
16157
- if (retry >= 10 || !isTransientMailboxLock(error)) throw error;
16158
- await delay3(20);
16159
- }
16160
- }
17525
+ await retryMailboxLock(() => rm(path2, { force: true }));
16161
17526
  }
16162
17527
  async write(path2, contents) {
16163
17528
  await mkdir(dirname(path2), { recursive: true });
16164
17529
  const temporary = `${path2}.tmp`;
16165
- await writeFile(temporary, contents, "utf8");
16166
- await rename(temporary, path2);
17530
+ await retryMailboxLock(async () => {
17531
+ await writeFile(temporary, contents, "utf8");
17532
+ await rename(temporary, path2);
17533
+ });
16167
17534
  }
16168
17535
  };
16169
17536
  var DesktopPlaytestDriver = class {
@@ -16208,6 +17575,10 @@ var DesktopPlaytestDriver = class {
16208
17575
  ...process.env,
16209
17576
  ...process.platform === "linux" && process.env.SDL_VIDEODRIVER === void 0 ? { SDL_VIDEODRIVER: "x11" } : {},
16210
17577
  MYSTRAL_HEADLESS: "1",
17578
+ // A debug launch, because the run's own warning evaluator reads `TN_SCENE_WARNING` and the
17579
+ // engine prints it only where a developer asked for the dev surfaces. The shell's value must
17580
+ // not decide it: an inherited `DEV_MODE=0` would leave the check blind rather than red.
17581
+ DEV_MODE: "1",
16211
17582
  ...this.options.env,
16212
17583
  TN_PLAYTEST_MAILBOX_ROOT: this.mailboxRoot,
16213
17584
  // The host reads the request before it evaluates the game entry, the way the browser runner
@@ -16405,6 +17776,17 @@ function isProcessExited(child) {
16405
17776
  function delay3(milliseconds) {
16406
17777
  return new Promise((resolve8) => setTimeout(resolve8, milliseconds));
16407
17778
  }
17779
+ async function retryMailboxLock(operation) {
17780
+ for (let retry = 0; ; retry += 1) {
17781
+ try {
17782
+ await operation();
17783
+ return;
17784
+ } catch (error) {
17785
+ if (retry >= 100 || !isTransientMailboxLock(error)) throw error;
17786
+ await delay3(20);
17787
+ }
17788
+ }
17789
+ }
16408
17790
  function isTransientMailboxLock(error) {
16409
17791
  const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
16410
17792
  return code === "EPERM" || code === "EBUSY";
@@ -16821,7 +18203,9 @@ var XcrunIosDriver = class {
16821
18203
  async prepareSimulator(endpoint, mailboxRoot) {
16822
18204
  const device = this.device();
16823
18205
  await this.run(["simctl", "bootstatus", device, "-b"]);
18206
+ const previous = await this.registeredBundlePath(device);
16824
18207
  await this.run(["simctl", "install", device, this.options.appPath]);
18208
+ await this.awaitInstalledBundle(device, previous);
16825
18209
  const container = (await this.run([
16826
18210
  "simctl",
16827
18211
  "get_app_container",
@@ -16874,6 +18258,28 @@ var XcrunIosDriver = class {
16874
18258
  ]);
16875
18259
  this.pid = parseLaunchedPid(output);
16876
18260
  }
18261
+ // `simctl install` returns while the simulator still lists the replaced bundle, which it has
18262
+ // moved to `containermanagerd/Dead/`. A launch in that window starts the previous build: a CI
18263
+ // physics scenario ran the input smoke game from a Dead container and failed every assertion.
18264
+ // Every reinstall gets a new bundle container, so launch only once the listed path is new.
18265
+ async awaitInstalledBundle(device, previous) {
18266
+ const deadline = Date.now() + kIosInstallRegistrationMs;
18267
+ for (; ; ) {
18268
+ const listed = await this.run(["simctl", "listapps", device]);
18269
+ const path2 = parseListedBundlePath(listed, this.options.bundleId);
18270
+ if (path2 !== void 0 && path2 !== previous && !path2.includes("/Dead/")) return;
18271
+ if (Date.now() >= deadline) {
18272
+ const at = listed.indexOf(`"${this.options.bundleId}"`);
18273
+ throw new Error(
18274
+ `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)
18275
+ );
18276
+ }
18277
+ await new Promise((resolve8) => setTimeout(resolve8, kIosInstallPollMs));
18278
+ }
18279
+ }
18280
+ async registeredBundlePath(device) {
18281
+ return parseListedBundlePath(await this.run(["simctl", "listapps", device]), this.options.bundleId);
18282
+ }
16877
18283
  device() {
16878
18284
  return this.options.device ?? "booted";
16879
18285
  }
@@ -16881,6 +18287,14 @@ var XcrunIosDriver = class {
16881
18287
  return this.mailboxRoot === void 0 ? path2 : join(this.mailboxRoot, basename(path2));
16882
18288
  }
16883
18289
  };
18290
+ var kIosInstallRegistrationMs = 6e4;
18291
+ var kIosInstallPollMs = 250;
18292
+ function parseListedBundlePath(output, bundleId) {
18293
+ const key = new RegExp(`"${bundleId.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}"\\s*=\\s*\\{`, "u").exec(output);
18294
+ if (key === null) return void 0;
18295
+ const path2 = /\n\s*Path = (?:"([^"]*)"|([^;\s]+));/u.exec(output.slice(key.index));
18296
+ return path2?.[1] ?? path2?.[2];
18297
+ }
16884
18298
  function parseLaunchedPid(output) {
16885
18299
  const pid = /(?:pid\s+|:\s*)(\d+)\b/iu.exec(output)?.[1];
16886
18300
  if (pid === void 0) throw new Error(`iOS launch did not report a process id: ${output.trim()}`);
@@ -17231,12 +18645,12 @@ async function withBrowserCapture(config, capture, signal) {
17231
18645
  networkEntries
17232
18646
  })}`);
17233
18647
  }
17234
- await stage("warmup", () => waitFrames(activePage, scenario.warmupFrames), startupBudget);
18648
+ await stage("warmup", () => waitFrames(activePage, scenario.warmupFrames, startupBudget), startupBudget);
17235
18649
  const startup = await stage("engine startup readiness", () => waitForStartupReady({
17236
18650
  aborted: () => controller.signal.aborted,
17237
18651
  bridge,
17238
18652
  declaredSoftware: active.allowSoftwareAdapter === true,
17239
- pump: () => waitFrames(activePage, 1)
18653
+ pump: (remainingMs) => waitFrames(activePage, 1, remainingMs)
17240
18654
  }), startupBudget);
17241
18655
  if (startup === void 0) throw new Error("TN_CAPTURE_SESSION_READINESS_REQUIRED: no startup observation was returned");
17242
18656
  const provenance = await stage("adapter provenance", () => readCaptureProvenance(activePage, active, scenario));
@@ -17301,4 +18715,4 @@ async function withBrowserCapture(config, capture, signal) {
17301
18715
  }
17302
18716
  }
17303
18717
 
17304
- export { ANDROID_TRANSPORT_CAPABILITIES, AdbAndroidDriver, DesktopPlaytestDriver, DeviceBridgeTransport, DeviceMailboxTransport, LocalDeviceMailbox, ManagedServerError, PERFORMANCE_BROWSER_ARGS, PIPELINE_CAPTURE_VERSION, PIPELINE_EVENT_MARKER, PLAYTEST_FLAGS, PlaytestBridgeError, PlaytestCliUsageError, PlaywrightTransport, STANDALONE_PLAYTEST_OBSERVATION_FIELDS, WEBGPU_BROWSER_ARGS, XcrunIosDriver, advanceFixedStep, advanceTimeoutMs, androidMailboxPaths, androidTouchBatches, batchArtifactDirectory, boundedTeardownStep, bridgeWaitTimeoutMs, buildReport, captureVisualSurface, connectPlaytestBridge, connectPlaytestBridgeTransport, decideDisplayStrategy, desktopConsoleType, deviceMailboxPaths, deviceTimeoutDiagnostic, discoverAdb, failedDiagnosticsAssertion, formatPipelineSummary, formatUsage, handlePlaytestSignal, initStandalonePlaytest, isRuntimeReadout, keyboardIsShown, openPageAndConnectBridge, pageLifecycleDiagnostic, parseAndroidConsole, parseAndroidTouchViewport, parseLaunchedPid, parsePipelineCapture, parsePipelineEventMarkers, parseStandalonePlaytestArgs, playtestStepDrivesMovement, preflightDisplay, reconcileBrowserPointers, recordToScenario, requireAssertions, resolveBrowserArguments, resolveManagedServerCommand, resolveManagedServerConfig, rotatedTouchPosition, runAndroidPlaytest, runDesktopPlaytest, runDevicePlaytest, runIosPlaytest, runStandalonePlaytest, runStandalonePlaytests, softwareAdapterName, substituteManagedPort, summarizePipelineCapture, tapCommand, touchPositionForViewport, touchRotationFromWindowDump, validateDeviceEndpoint, viewportPresentationCommands, viewportPresentationObserved, viewportRestoreCommands, withBrowserCapture, writeCaptureProvenance, writeObservationArtifacts };
18718
+ export { ANDROID_TRANSPORT_CAPABILITIES, AdbAndroidDriver, DesktopPlaytestDriver, DeviceBridgeTransport, DeviceMailboxTransport, LocalDeviceMailbox, ManagedServerError, PENDING_BRIDGE_OPERATIONS_GLOBAL, PERFORMANCE_BROWSER_ARGS, PIPELINE_CAPTURE_VERSION, PIPELINE_EVENT_MARKER, PLAYTEST_FLAGS, PlaytestBridgeError, PlaytestCliUsageError, PlaywrightTransport, STANDALONE_PLAYTEST_OBSERVATION_FIELDS, WEBGPU_BROWSER_ARGS, XcrunIosDriver, advanceFixedStep, advanceTimeoutMs, androidMailboxPaths, androidTouchBatches, batchArtifactDirectory, boundedTeardownStep, bridgeWaitTimeoutMs, buildReport, captureVisualSurface, connectPlaytestBridge, connectPlaytestBridgeTransport, decideDisplayStrategy, desktopConsoleType, deviceMailboxPaths, deviceTimeoutDiagnostic, discoverAdb, failedDiagnosticsAssertion, formatPipelineSummary, formatUsage, handlePlaytestSignal, initStandalonePlaytest, isRuntimeReadout, keyboardIsShown, openPageAndConnectBridge, pageLifecycleDiagnostic, parseAndroidConsole, parseAndroidTouchViewport, parseLaunchedPid, parsePipelineCapture, parsePipelineEventMarkers, parseStandalonePlaytestArgs, playtestStepDrivesMovement, preflightDisplay, reconcileBrowserPointers, recordToScenario, requireAssertions, resolveBrowserArguments, resolveManagedServerCommand, resolveManagedServerConfig, rotatedTouchPosition, runAndroidPlaytest, runDesktopPlaytest, runDevicePlaytest, runIosPlaytest, runStandalonePlaytest, runStandalonePlaytests, softwareAdapterName, substituteManagedPort, summarizePipelineCapture, tapCommand, touchPositionForViewport, touchRotationFromWindowDump, validateDeviceEndpoint, viewportPresentationCommands, viewportPresentationObserved, viewportRestoreCommands, withBrowserCapture, withScenarioClock, writeCaptureProvenance, writeObservationArtifacts };