@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.
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ import { readdirSync, readFileSync } from 'fs';
3
+ import { resolve, join } from 'path';
4
+ import 'child_process';
2
5
  import { readFile } from 'fs/promises';
3
- import { resolve } from 'path';
4
6
 
5
7
  // src/capabilities.ts
6
8
  var PLAYTEST_CAPABILITY_REGISTRY = [
@@ -371,7 +373,7 @@ var PLAYTEST_ASSERTION_REGISTRY = [
371
373
  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 } }] },
372
374
  fields: [
373
375
  { description: "Before/after or baseline-image changed-pixel ratio bounds.", name: "frameDiff", type: "{ baselineImage?: project-relative PNG, minChangedPixelRatio?: number, maxChangedPixelRatio?: number }" },
374
- { 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 }" },
376
+ { 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 }" },
375
377
  { description: "Entity projected-pixel floor, optionally across all captured samples.", name: "entityVisible", type: "{ entity: string, minProjectedPixels: number, throughoutFrames?: boolean }" }
376
378
  ],
377
379
  cardinality: "array",
@@ -465,7 +467,7 @@ var PLAYTEST_ASSERTION_REGISTRY = [
465
467
  { description: "Substring expected in the observed value.", name: "textIncludes", type: "string" },
466
468
  { description: "Require before and after values to differ or remain equal.", name: "changed", type: "boolean" },
467
469
  { description: "Require the value assertion after every labeled scenario step.", name: "throughoutSteps", type: "boolean" },
468
- { description: "Expected values at named scenario-step samples.", name: "atSteps", type: "Array<{ label: string, equals?: json, textIncludes?: string }>" },
470
+ { description: "Expected values at named scenario-step samples.", name: "atSteps", type: "Array<{ label: string, equals?: json, lte?: number, textIncludes?: string }>" },
469
471
  { description: "Written reason for a held invariant whose initial value intentionally satisfies the assertion.", name: "allowTrivial", type: "triviality reason" },
470
472
  { 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 }>" }
471
473
  ],
@@ -601,7 +603,8 @@ var PLAYTEST_ASSERTION_REGISTRY = [
601
603
  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.",
602
604
  example: { performance: { maxPassDrawCalls: { shadow: 400 }, maxPhaseMsP95: { render: 12 }, minFps: 30 } },
603
605
  fields: [
604
- { description: "Maximum nearest-rank 95th-percentile frame time in milliseconds.", name: "maxFrameMsP95", type: "number" },
606
+ { 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" },
607
+ { 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" },
605
608
  { description: "Minimum sustained frames per second, from the median sampled frame.", name: "minFps", type: "number" },
606
609
  { description: "Per-phase millisecond ceilings at nearest-rank p95. Phases: hostGap, update, render, overlay, residual.", name: "maxPhaseMsP95", type: "{ [phase]: number }" },
607
610
  { description: "Maximum observed renderer draw-call count across every pass combined.", name: "maxDrawCalls", type: "number" },
@@ -755,6 +758,7 @@ var PLAYTEST_ASSERTION_REGISTRY = [
755
758
  fields: [
756
759
  { description: "Entity id. Defaults to scenario subject.", name: "entity", type: "string" },
757
760
  { description: "Animation clip id or name.", name: "clip", type: "string" },
761
+ { description: "Labeled step whose animation report is judged; default is the last sample.", name: "atStep", type: "string" },
758
762
  { description: "Require entering the animation state.", name: "entered", type: "boolean" },
759
763
  { description: "Require animation advancement evidence.", name: "advancedFrames", type: "number" },
760
764
  { description: "Require the observed clip to report its completion state.", name: "finished", type: "boolean" },
@@ -812,6 +816,79 @@ var PLAYTEST_ASSERTION_REGISTRY = [
812
816
  triviality: "not-applicable",
813
817
  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."
814
818
  },
819
+ {
820
+ cardinality: "array",
821
+ 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.",
822
+ example: { footSlip: [{ atStep: "run", feet: ["footL", "footR"], maxSlip: 0.35 }] },
823
+ fields: [
824
+ { 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" },
825
+ { description: "Exact Object3D names of the nodes at the soles, one per foot.", name: "feet", type: "Array<string>" },
826
+ { 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" },
827
+ { 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" },
828
+ { 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" },
829
+ { description: "The moving entity; defaults to the scenario subject.", name: "entity", type: "string" }
830
+ ],
831
+ kind: "footSlip",
832
+ observationPath: "footSlip",
833
+ requiredCapabilities: ["entity.observe", "scene.nodes"],
834
+ resultIdPrefix: "footSlip",
835
+ supportedOn: ["web"],
836
+ triviality: "not-applicable",
837
+ trivialityRationale: "The measurement needs the subject to cover ground during the step, so a standing subject fails as unmeasured instead of passing."
838
+ },
839
+ {
840
+ cardinality: "object",
841
+ 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.",
842
+ example: { sightLine: { maxBlockedRatio: 0.02 } },
843
+ fields: [
844
+ { description: "The entity whose world bounds centre the camera should see; defaults to the scenario subject.", name: "entity", type: "string" },
845
+ { 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" }
846
+ ],
847
+ kind: "sightLine",
848
+ observationPath: "sightLine",
849
+ requiredCapabilities: ["camera.observe", "entity.observe"],
850
+ resultIdPrefix: "sightLine",
851
+ supportedOn: ["web"],
852
+ triviality: "not-applicable",
853
+ 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."
854
+ },
855
+ {
856
+ cardinality: "object",
857
+ 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.",
858
+ example: { engineCost: { maxPerFrame: { bridgeCrossings: 2e3, childrenReads: 60 }, skipWindows: 1, source: "shooter after-value 1,024 per frame on 2026-10-27, about 2x headroom" } },
859
+ fields: [
860
+ { description: "Counter name to its bound on a window's per-frame mean.", name: "maxPerFrame", type: "{ [counter: string]: number }" },
861
+ { description: "Counter name to its bound on any single frame of a window.", name: "maxInFrame", type: "{ [counter: string]: number }" },
862
+ { description: "Windows the run must report; default 1.", name: "minWindows", type: "positive integer" },
863
+ { description: "Windows left unbounded first, the boot (loading, first builds); still and moving count after them. Default 0.", name: "skipWindows", type: "non-negative integer" },
864
+ { 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 } }" },
865
+ { 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 } }" },
866
+ { description: "Where the bounds came from: the measured after-values and the headroom on them.", name: "source", required: true, type: "string" }
867
+ ],
868
+ kind: "engineCost",
869
+ observationPath: "console",
870
+ requiredCapabilities: ["browser.console"],
871
+ resultIdPrefix: "engineCost.",
872
+ supportedOn: ["web"],
873
+ triviality: "not-applicable",
874
+ trivialityRationale: "The counters are measured across the run's frames; an initial value has no frames to count."
875
+ },
876
+ {
877
+ cardinality: "object",
878
+ 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.",
879
+ example: { hudAudit: { minContrast: 3, noDebugText: true } },
880
+ fields: [
881
+ { 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" },
882
+ { description: "Require that no text reads like developer copy. Only true is accepted.", name: "noDebugText", type: "true" }
883
+ ],
884
+ kind: "hudAudit",
885
+ observationPath: "hudAudit",
886
+ requiredCapabilities: ["browser.dom"],
887
+ resultIdPrefix: "hudAudit.",
888
+ supportedOn: ["web"],
889
+ triviality: "not-applicable",
890
+ 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."
891
+ },
815
892
  {
816
893
  cardinality: "array",
817
894
  description: "Relates a tick-stamped effect to the tick-stamped cause that must precede it \u2014 the 'because' a terminal state needs.",
@@ -845,7 +922,9 @@ var PLAYTEST_ASSERTION_REGISTRY = [
845
922
  fields: [
846
923
  { description: "Ceiling on when the start scene's enter() returned, in ms since navigation.", name: "maxEnteredMs", type: "number" },
847
924
  { description: "Ceiling on when first-use compilation settled or its budget expired, in ms since navigation.", name: "maxCompileSettledMs", type: "number" },
848
- { description: "Ceiling on when startup readiness resolved, in ms since navigation.", name: "maxReadyMs", type: "number" }
925
+ { description: "Ceiling on when startup readiness resolved, in ms since navigation.", name: "maxReadyMs", type: "number" },
926
+ { 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" },
927
+ { 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" }
849
928
  ],
850
929
  cardinality: "object",
851
930
  kind: "startup",
@@ -1159,6 +1238,37 @@ function format(value) {
1159
1238
  return value === null ? "unknown" : String(value);
1160
1239
  }
1161
1240
 
1241
+ // src/evaluators/perf-warnings.ts
1242
+ var SCENE_WARNING = "TN_SCENE_WARNING";
1243
+ var BRIDGE_WARNING = "TN_BRIDGE_WARNING";
1244
+ var HOT_CALL = "TN_HOT_CALL";
1245
+ var PROJECTION = "TN_RENDER_PROJECTION:";
1246
+ function perfWarnings(consoleLines) {
1247
+ const found = [];
1248
+ for (const line of consoleLines) {
1249
+ if (typeof line !== "string") continue;
1250
+ for (const marker of [SCENE_WARNING, BRIDGE_WARNING, HOT_CALL]) {
1251
+ const warning = line.indexOf(marker);
1252
+ if (warning !== -1) found.push(line.slice(warning).trim());
1253
+ }
1254
+ const at = line.indexOf(PROJECTION);
1255
+ if (at === -1) continue;
1256
+ const text = line.slice(at).trim();
1257
+ let report;
1258
+ try {
1259
+ report = JSON.parse(line.slice(at + PROJECTION.length));
1260
+ } catch {
1261
+ found.push(`${text} (unreadable)`);
1262
+ continue;
1263
+ }
1264
+ if (report.projecting !== false || report.reasonCode === "disabled") continue;
1265
+ if (report.reasonCode === "belowMeshFloor") continue;
1266
+ const cause = report.cause === void 0 ? "" : ` [cause ${report.cause.code ?? "?"}: ${report.cause.hint ?? "no hint"}]`;
1267
+ found.push(`${text}${cause}`);
1268
+ }
1269
+ return found;
1270
+ }
1271
+
1162
1272
  // src/evaluators/measures.ts
1163
1273
  function horizontalRadius(transform, direction) {
1164
1274
  const halfExtents = transform?.halfExtents ?? (transform?.scale === void 0 ? void 0 : transform.scale.map((value) => Math.abs(value) * 0.5));
@@ -1444,6 +1554,15 @@ function evaluateDiagnosticsPolicy(report, policy) {
1444
1554
  suggestion: "Inspect console.json and fix the first TN_V8_FRAME_FAILED error."
1445
1555
  });
1446
1556
  }
1557
+ const warnings = perfWarnings((report.observations?.console ?? []).map(({ text }) => text));
1558
+ if (warnings.length > 0) {
1559
+ diagnostics.push({
1560
+ code: "TN_PLAYTEST_PERF_WARNING",
1561
+ message: `${warnings.length} engine performance warning(s): ${warnings.slice(0, 3).join(" | ")}`,
1562
+ severity: "error",
1563
+ 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."
1564
+ });
1565
+ }
1447
1566
  const capturedConsoleErrors = consoleErrors(report.observations?.console ?? []);
1448
1567
  if (policy.noConsoleErrors && capturedConsoleErrors.length > 0) {
1449
1568
  diagnostics.push({
@@ -1816,12 +1935,17 @@ function strideReading(observed) {
1816
1935
  return {
1817
1936
  clipGroundSpeed: stride.clipGroundSpeed,
1818
1937
  groundSpeed: stride.groundSpeed,
1938
+ inPlace: stride.inPlace === true,
1819
1939
  overridden: stride.overridden,
1820
1940
  rate: stride.rate,
1821
1941
  synced: stride.synced
1822
1942
  };
1823
1943
  }
1824
1944
  var STRIDE_GROUND_SPEED_FLOOR = 1e-3;
1945
+ function strideHasNoFootPlant(reading) {
1946
+ return reading.inPlace && Math.abs(reading.clipGroundSpeed) <= STRIDE_GROUND_SPEED_FLOOR && Math.abs(reading.groundSpeed) > STRIDE_GROUND_SPEED_FLOOR;
1947
+ }
1948
+ var NO_FOOT_PLANT_DETAIL = "no foot plant found: stride sync is off";
1825
1949
  function appliedStrideRate(reading) {
1826
1950
  return reading.synced ? reading.rate : 1;
1827
1951
  }
@@ -1840,6 +1964,8 @@ function strideFailure(assertion, observed) {
1840
1964
  code: "TN_PLAYTEST_STRIDE_UNOBSERVED",
1841
1965
  detail: "the runtime reported no stride for this clip, so neither the feet nor the ground were measured"
1842
1966
  };
1967
+ if (assertion.strideSynced !== false && strideHasNoFootPlant(reading))
1968
+ return { code: "TN_PLAYTEST_STRIDE_NO_FOOT_PLANT", detail: NO_FOOT_PLANT_DETAIL };
1843
1969
  if (assertion.strideSynced !== void 0 && reading.synced !== assertion.strideSynced)
1844
1970
  return {
1845
1971
  code: "TN_PLAYTEST_STRIDE_NOT_SYNCED",
@@ -1953,6 +2079,65 @@ function assertJsonSafe(value, path = "$") {
1953
2079
  }
1954
2080
  throw new TypeError(`${path} must be JSON-safe.`);
1955
2081
  }
2082
+ var HOST_DISPLAY_ENV = "TN_PLAYTEST_HOST_DISPLAY";
2083
+ function hostDisplayRequested(env) {
2084
+ const value = env[HOST_DISPLAY_ENV];
2085
+ return value === "1" || value?.toLowerCase() === "true";
2086
+ }
2087
+
2088
+ // src/evaluators/frame-cost.ts
2089
+ var FRAME_BUDGET = "TN_FRAME_BUDGET:";
2090
+ function frameDisplay(env = process.env, platform = process.platform) {
2091
+ return platform === "linux" && !hostDisplayRequested(env) ? "virtual" : "real";
2092
+ }
2093
+ function foreignGpuProcesses(ownPid = process.pid, procRoot = "/proc", platform = process.platform) {
2094
+ if (platform !== "linux") return [];
2095
+ const read = (pid, file) => {
2096
+ try {
2097
+ return readFileSync(join(procRoot, pid, file), "utf8");
2098
+ } catch {
2099
+ return void 0;
2100
+ }
2101
+ };
2102
+ const parentOf = (pid) => {
2103
+ const stat = read(String(pid), "stat");
2104
+ const ppid = stat === void 0 ? void 0 : Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
2105
+ return ppid === void 0 || !Number.isSafeInteger(ppid) ? void 0 : ppid;
2106
+ };
2107
+ const ours = (pid) => {
2108
+ for (let current = pid, hops = 0; current !== void 0 && current > 1 && hops < 64; hops++) {
2109
+ if (current === ownPid) return true;
2110
+ current = parentOf(current);
2111
+ }
2112
+ return false;
2113
+ };
2114
+ return readdirSync(procRoot).filter((entry) => {
2115
+ const argv = /^\d+$/u.test(entry) ? (read(entry, "cmdline") ?? "").split("\0") : [];
2116
+ return argv.includes("--type=gpu-process") && (argv[0] ?? "").includes("ms-playwright");
2117
+ }).map(Number).filter((pid) => !ours(pid)).sort((a, b) => a - b);
2118
+ }
2119
+ var MIN_GPU_SAMPLES = 3;
2120
+ function gpuWindows(consoleLines) {
2121
+ const windows = [];
2122
+ let samples;
2123
+ for (const line of consoleLines) {
2124
+ if (typeof line !== "string") continue;
2125
+ const at = line.indexOf(FRAME_BUDGET);
2126
+ if (at === -1) continue;
2127
+ let report;
2128
+ try {
2129
+ report = JSON.parse(line.slice(at + FRAME_BUDGET.length));
2130
+ } catch {
2131
+ continue;
2132
+ }
2133
+ const p95 = report.gpu?.p95;
2134
+ if (typeof p95 === "number" && Number.isFinite(p95) && (typeof report.gpu?.samples !== "number" || report.gpu.samples > 0)) {
2135
+ windows.push(p95);
2136
+ samples = typeof report.gpu?.samples === "number" ? report.gpu.samples : void 0;
2137
+ }
2138
+ }
2139
+ return windows.length === 0 ? { windows } : { p95: windows[windows.length - 1], ...samples === void 0 ? {} : { samples }, windows };
2140
+ }
1956
2141
 
1957
2142
  // src/evaluators/render-evidence.ts
1958
2143
  function projectedPixelsForEntity(snapshot, entity, viewport) {
@@ -1971,7 +2156,7 @@ function countMatchingEntries(effectLog, tokens) {
1971
2156
  return tokens.every((token) => text.includes(token));
1972
2157
  }).length;
1973
2158
  }
1974
- function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2159
+ function evaluatePerformanceAssertion(assertion, series, sourcePath, lane) {
1975
2160
  const samples = series ?? [];
1976
2161
  const validSamples = samples.length > 0 && samples.every(isRuntimeDiagnosticsSample);
1977
2162
  const observed = validSamples ? samples : [];
@@ -2012,13 +2197,17 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2012
2197
  });
2013
2198
  };
2014
2199
  if (assertion.maxFrameMsP95 !== void 0) {
2015
- addBound(
2016
- "performance.maxFrameMsP95",
2017
- assertion.maxFrameMsP95,
2018
- frameMsP95,
2019
- "ms",
2020
- samplesPass && frameMsP95 !== void 0 && frameMsP95 <= assertion.maxFrameMsP95
2021
- );
2200
+ if (lane === void 0) {
2201
+ addBound(
2202
+ "performance.maxFrameMsP95",
2203
+ assertion.maxFrameMsP95,
2204
+ frameMsP95,
2205
+ "ms",
2206
+ samplesPass && frameMsP95 !== void 0 && frameMsP95 <= assertion.maxFrameMsP95
2207
+ );
2208
+ } else {
2209
+ emitFrameBound(assertion.maxFrameMsP95, frameMsP95, observed, samples.length, samplesPass, lane, results, diagnostics, path, sourcePath);
2210
+ }
2022
2211
  }
2023
2212
  if (assertion.maxDrawCalls !== void 0) {
2024
2213
  addBound(
@@ -2030,17 +2219,26 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2030
2219
  );
2031
2220
  }
2032
2221
  if (assertion.minFps !== void 0) {
2033
- const exact = fpsFromFrameTimes(frameTimes);
2034
- const observed2 = exact === void 0 ? void 0 : Math.floor(exact * 100) / 100;
2222
+ const onXvfb = lane?.display === "virtual" && lane.target !== "android" && lane.target !== "ios";
2223
+ const costP95 = onXvfb ? frameCost(observed, samples.length, lane).costP95 : void 0;
2224
+ const virtual = costP95 !== void 0 && costP95 > 0;
2225
+ const exact = virtual ? 1e3 / costP95 : fpsFromFrameTimes(frameTimes);
2226
+ const observedFps = exact === void 0 ? void 0 : Math.floor(exact * 100) / 100;
2035
2227
  const pass = samplesPass && exact !== void 0 && exact >= assertion.minFps;
2036
2228
  results.push({
2037
- details: { actual: observed2 ?? null, expected: assertion.minFps, sampleCount: samples.length, unit: "fps" },
2229
+ details: {
2230
+ actual: observedFps ?? null,
2231
+ expected: assertion.minFps,
2232
+ sampleCount: samples.length,
2233
+ unit: "fps",
2234
+ ...virtual ? { basis: "frame-cost", interval: { gated: false, p95: frameMsP95 ?? null, reason: XVFB_CADENCE } } : {}
2235
+ },
2038
2236
  id: "performance.minFps",
2039
2237
  pass
2040
2238
  });
2041
2239
  if (!pass) diagnostics.push({
2042
2240
  code: "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
2043
- message: `performance.minFps expected at least ${assertion.minFps} fps, observed ${observed2 ?? "unavailable"}.`,
2241
+ message: `performance.minFps expected at least ${assertion.minFps} fps, observed ${observedFps ?? "unavailable"}${virtual ? " from frame cost on a virtual display" : ""}.`,
2044
2242
  observedRuntimePath: path,
2045
2243
  severity: "error",
2046
2244
  sourcePath,
@@ -2105,6 +2303,58 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
2105
2303
  addPassBound("triangles", kind, ceiling);
2106
2304
  return { assertions: results, diagnostics };
2107
2305
  }
2306
+ var HITCH_MS = 2e3;
2307
+ var XVFB_CADENCE = "display cadence, not gated: the runner's private Xvfb paces frames on its own timer, not the game's cost";
2308
+ function frameCost(observed, sampleCount, lane) {
2309
+ const cpu = observed.flatMap(({ phases }) => phases === void 0 || typeof phases.update !== "number" || typeof phases.render !== "number" ? [] : [phases.update + phases.render]);
2310
+ const hitches = observed.filter(({ frameMs, phases }) => phases === void 0 && frameMs >= HITCH_MS).length;
2311
+ const cpuP95 = cpu.length > 0 && cpu.length + hitches === sampleCount ? nearestRank(cpu, 0.95) : void 0;
2312
+ const costP95 = cpuP95 === void 0 || lane.gpuP95 === void 0 ? void 0 : Math.max(cpuP95, lane.gpuP95);
2313
+ return { costP95, cpuP95, hitches };
2314
+ }
2315
+ function emitFrameBound(ceiling, intervalP95, observed, sampleCount, samplesPass, lane, results, diagnostics, path, sourcePath) {
2316
+ const { costP95, cpuP95, hitches } = frameCost(observed, sampleCount, lane);
2317
+ const missing = [
2318
+ ...cpuP95 === void 0 ? ["the CPU frame split (phases.update and phases.render)"] : [],
2319
+ ...lane.gpuP95 === void 0 ? ["the GPU time (a TN_FRAME_BUDGET window with a gpu reading)"] : []
2320
+ ];
2321
+ const virtual = lane.display === "virtual";
2322
+ const costPass = costP95 !== void 0 && costP95 <= ceiling;
2323
+ const intervalPass = virtual || intervalP95 !== void 0 && intervalP95 <= ceiling;
2324
+ const thinGpu = lane.gpuP95 !== void 0 && !(lane.gpuSamples !== void 0 && lane.gpuSamples >= MIN_GPU_SAMPLES);
2325
+ const pass = samplesPass && costPass && intervalPass && !thinGpu;
2326
+ const round2 = (value) => value === void 0 ? null : Math.round(value * 100) / 100;
2327
+ results.push({
2328
+ details: {
2329
+ actual: round2(virtual || !costPass ? costP95 : intervalP95),
2330
+ cost: { cpuP95: round2(cpuP95), gpuP95: round2(lane.gpuP95), gpuSamples: lane.gpuSamples ?? null, hitchFrames: hitches, p95: round2(costP95) },
2331
+ display: lane.display,
2332
+ expected: ceiling,
2333
+ interval: virtual ? { gated: false, p95: round2(intervalP95), reason: XVFB_CADENCE } : { gated: true, p95: round2(intervalP95) },
2334
+ sampleCount,
2335
+ unit: "ms"
2336
+ },
2337
+ id: "performance.maxFrameMsP95",
2338
+ pass
2339
+ });
2340
+ if (pass) return;
2341
+ const foreign = lane.foreignGpu ?? [];
2342
+ const contended = missing.length === 0 && !costPass && foreign.length > 0;
2343
+ 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`;
2344
+ const fewSamples = missing.length === 0 && costPass && thinGpu;
2345
+ diagnostics.push({
2346
+ code: fewSamples ? "TN_PLAYTEST_PERF_FEW_GPU_SAMPLES" : "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
2347
+ message: `performance.maxFrameMsP95 ${fewSamples ? fewGpuSamples(lane.gpuSamples) : detail}.`,
2348
+ observedRuntimePath: path,
2349
+ severity: "error",
2350
+ sourcePath,
2351
+ 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."
2352
+ });
2353
+ }
2354
+ function fewGpuSamples(samples) {
2355
+ const held = samples === void 0 ? "reports no sample count" : `holds ${samples} GPU sample${samples === 1 ? "" : "s"}`;
2356
+ return `cannot be judged: the latest GPU window ${held}, under the minimum of ${MIN_GPU_SAMPLES}`;
2357
+ }
2108
2358
  function isRuntimeDiagnosticsSample(value) {
2109
2359
  if (!isRecord(value) || typeof value.frameMs !== "number" || !Number.isFinite(value.frameMs) || value.frameMs <= 0) {
2110
2360
  return false;
@@ -2423,6 +2673,17 @@ function emitEvidenceFamilies(ctx) {
2423
2673
  const pass = observed !== void 0 && observed.nonblankPixelRatio >= minimum;
2424
2674
  assertions.push({ id: `visual.${index}.region`, pass, details: { after: pass, expected: { equals: true }, minimum, observed: observed?.nonblankPixelRatio } });
2425
2675
  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." });
2676
+ if (staticRegion.minSharpness !== void 0) {
2677
+ const sharpness = observed?.sharpness;
2678
+ const sharpPass = sharpness !== void 0 && sharpness >= staticRegion.minSharpness;
2679
+ assertions.push({ id: `visual.${index}.region.sharpness`, pass: sharpPass, details: { minimum: staticRegion.minSharpness, observed: sharpness ?? null } });
2680
+ if (!sharpPass) diagnostics.push({
2681
+ code: "TN_PLAYTEST_REGION_BLURRED",
2682
+ 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).`,
2683
+ severity: "error",
2684
+ 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."
2685
+ });
2686
+ }
2426
2687
  if (staticRegion.minDarkPixelRatio !== void 0) {
2427
2688
  const darkPass = observed?.darkPixelRatio !== void 0 && observed.darkPixelRatio >= staticRegion.minDarkPixelRatio;
2428
2689
  assertions.push({
@@ -2485,12 +2746,14 @@ function emitMovementEvidence(ctx) {
2485
2746
  scenarioAssertions.diagnostics,
2486
2747
  input.report.target
2487
2748
  );
2749
+ const warningTexts = perfWarnings((input.report.observations?.console ?? []).map(({ text }) => text));
2488
2750
  const policyDiagnostics = evaluateDiagnosticsPolicy(input.report, diagnosticsPolicy);
2489
2751
  diagnostics.push(...policyDiagnostics);
2490
2752
  assertions.push({
2491
2753
  details: {
2492
2754
  consoleErrors: consoleErrors(input.report.observations?.console ?? []).length,
2493
2755
  networkErrors: input.report.observations?.network.length ?? 0,
2756
+ ...warningTexts.length === 0 ? {} : { perfWarnings: warningTexts },
2494
2757
  policy: diagnosticsPolicy,
2495
2758
  runtimeDiagnostics: runtimeDiagnostics(input.report.observations?.runtimeDiagnostics).length
2496
2759
  },
@@ -2901,7 +3164,8 @@ function emitMovementEvidence(ctx) {
2901
3164
  }
2902
3165
  for (const assertion of scenarioAssertions.animation ?? []) {
2903
3166
  const entity = assertion.entity ?? input.scenario.subject ?? input.report.entity;
2904
- const runtime = runtimeAnimationObservations(input.report.observations?.runtimeObservations);
3167
+ const stepAnimation = runtimeGameplayAtStep(input.report.observations?.runtimeObservations, assertion.atStep)?.animation;
3168
+ const runtime = assertion.atStep === void 0 ? runtimeAnimationObservations(input.report.observations?.runtimeObservations) : isRecord(stepAnimation) ? stepAnimation : void 0;
2905
3169
  if (runtime !== void 0) {
2906
3170
  const observed = isRecord(runtime[entity]) ? runtime[entity] : void 0;
2907
3171
  const clip = typeof observed?.clip === "string" ? observed.clip : void 0;
@@ -3264,19 +3528,119 @@ function emitParity(ctx) {
3264
3528
  }
3265
3529
  }
3266
3530
 
3531
+ // src/runner/browser.ts
3532
+ var SOFTWARE_ADAPTER = /swiftshader|llvmpipe|lavapipe|softwarerasterizer|software adapter|basic render/i;
3533
+ function softwareAdapterName(adapter) {
3534
+ if (adapter === void 0) return void 0;
3535
+ for (const value of Object.values(adapter)) {
3536
+ if (typeof value === "string" && SOFTWARE_ADAPTER.test(value)) return value;
3537
+ }
3538
+ return void 0;
3539
+ }
3540
+
3541
+ // src/evaluators/adapter-class.ts
3542
+ function classifyAdapter(report) {
3543
+ const capture = report.capture;
3544
+ if (capture === void 0 || capture.rendererKind !== "webgpu") return {};
3545
+ if (adapterIdentity(capture.adapter) === void 0) return {};
3546
+ const software = softwareAdapterName(capture.adapter);
3547
+ if (software !== void 0) return { adapterClass: "software", softwareAdapter: software };
3548
+ const gpuFamily = gpuFamilyOf(capture.adapter);
3549
+ return gpuFamily === void 0 ? { adapterClass: "hardware" } : { adapterClass: "hardware", gpuFamily };
3550
+ }
3551
+ var ADAPTER_IDENTITY_KEYS = ["architecture", "description", "device", "vendor"];
3552
+ function adapterIdentity(adapter) {
3553
+ if (adapter === void 0) return void 0;
3554
+ for (const key of ADAPTER_IDENTITY_KEYS) {
3555
+ const value = adapter[key];
3556
+ if (typeof value === "string" && value.trim() !== "") return value;
3557
+ }
3558
+ return void 0;
3559
+ }
3560
+ var MALI_MODEL = /\bmali[\s_-]*g?[\s-]*(\d{2,3})/i;
3561
+ var ADRENO_MODEL = /\badreno\W*(?:tm\W*)?(\d)(\d\d|xx)/i;
3562
+ var AMD_INTEGRATED = /radeon(?:\(tm\))?\s+(?:graphics|\d{3}m)\b/i;
3563
+ var INTEL_DISCRETE = /\barc\b|xe2?-hpg|battlemage|alchemist/i;
3564
+ var FAMILY_RULES = [
3565
+ ({ architecture, description, device }) => {
3566
+ const number = [description, device, architecture].map((value) => MALI_MODEL.exec(value)?.[1]).find((value) => value !== void 0);
3567
+ if (number === void 0) return void 0;
3568
+ const model = Number(number);
3569
+ if (model >= 710) return "mobile-high";
3570
+ return model < 57 || model === 71 || model === 72 ? "mobile-low" : "mobile-mid";
3571
+ },
3572
+ ({ architecture, vendor }) => {
3573
+ if (!/\barm\b/i.test(vendor)) return void 0;
3574
+ if (/midgard|bifrost/i.test(architecture)) return "mobile-low";
3575
+ if (/valhall/i.test(architecture)) return "mobile-mid";
3576
+ return /5th-?gen|immortalis/i.test(architecture) ? "mobile-high" : void 0;
3577
+ },
3578
+ ({ architecture, description, device }) => {
3579
+ const match = [description, device, architecture].map((value) => ADRENO_MODEL.exec(value)).find((value) => value !== null && value !== void 0);
3580
+ if (match === null || match === void 0) return void 0;
3581
+ const generation = Number(match[1]);
3582
+ if (generation <= 4) return "mobile-low";
3583
+ if (generation === 5) return "mobile-mid";
3584
+ if (generation === 6) return match[2] !== "xx" && Number(match[2]) >= 30 ? "mobile-high" : "mobile-mid";
3585
+ return "mobile-high";
3586
+ },
3587
+ ({ architecture, description, device, vendor }) => /nvidia/i.test(vendor) && ![architecture, description, device].some((value) => /tegra/i.test(value)) ? "discrete" : void 0,
3588
+ ({ architecture, description, device, vendor }) => {
3589
+ if (!/intel/i.test(vendor)) return void 0;
3590
+ return [architecture, description, device].some((value) => INTEL_DISCRETE.test(value)) ? "discrete" : "integrated";
3591
+ },
3592
+ // An APU and a card share an architecture name, so an AMD adapter that names no iGPU is `discrete`.
3593
+ ({ description, vendor }) => /\b(?:amd|ati)\b/i.test(vendor) ? AMD_INTEGRATED.test(description) ? "integrated" : "discrete" : void 0
3594
+ ];
3595
+ function gpuFamilyOf(adapter) {
3596
+ if (adapter === void 0) return void 0;
3597
+ const field = (key) => {
3598
+ const value = adapter[key];
3599
+ return typeof value === "string" ? value : "";
3600
+ };
3601
+ const fields = {
3602
+ architecture: field("architecture"),
3603
+ description: field("description"),
3604
+ device: field("device"),
3605
+ vendor: field("vendor")
3606
+ };
3607
+ for (const rule of FAMILY_RULES) {
3608
+ const family = rule(fields);
3609
+ if (family !== void 0) return family;
3610
+ }
3611
+ return void 0;
3612
+ }
3613
+
3267
3614
  // src/evaluators/perf-signals-world.ts
3615
+ function gpuLane(consoleTexts) {
3616
+ const { p95, samples } = gpuWindows(consoleTexts);
3617
+ return p95 === void 0 ? {} : { gpuP95: p95, ...samples === void 0 ? {} : { gpuSamples: samples } };
3618
+ }
3268
3619
  function emitPerfSignalsWorld(ctx) {
3269
3620
  const { assertions, diagnostics } = ctx;
3270
3621
  const { input, scenarioAssertions } = ctx;
3271
3622
  emitTerrainResidency(input.report.observations?.components?.terrain, assertions, diagnostics);
3272
3623
  if (scenarioAssertions.performance !== void 0) {
3624
+ const budget = frameBudget(scenarioAssertions.performance.maxFrameMsP95, classifyAdapter(input.report), scenarioAssertions.performance.maxFrameMsReason);
3273
3625
  const result = evaluatePerformanceAssertion(
3274
- scenarioAssertions.performance,
3626
+ budget.maxFrameMsP95 === void 0 ? scenarioAssertions.performance : { ...scenarioAssertions.performance, maxFrameMsP95: budget.maxFrameMsP95 },
3275
3627
  input.report.observations?.performanceSeries,
3276
- input.scenario.sourcePath
3628
+ input.scenario.sourcePath,
3629
+ { display: frameDisplay(), target: input.report.target, foreignGpu: foreignGpuProcesses(), ...gpuLane((input.report.observations?.console ?? []).map(({ text }) => text)) }
3277
3630
  );
3278
- assertions.push(...result.assertions);
3631
+ assertions.push(...result.assertions.map((row) => row.id === "performance.samples" || row.id === "performance.maxFrameMsP95" ? { ...row, details: { ...row.details, frameBudget: budget } } : row));
3279
3632
  diagnostics.push(...result.diagnostics);
3633
+ if (budget.unmeasurable === true) {
3634
+ assertions.push({ details: { frameBudget: budget }, id: "performance.maxFrameMsP95", pass: false });
3635
+ diagnostics.push({
3636
+ code: "TN_PLAYTEST_PERFORMANCE_UNMEASURABLE",
3637
+ message: `performance.maxFrameMsP95 cannot be judged: ${budget.reason}.`,
3638
+ observedRuntimePath: `${input.scenario.sourcePath ?? "playtest"}/observations.json/performanceSeries`,
3639
+ severity: "error",
3640
+ sourcePath: input.scenario.sourcePath,
3641
+ suggestion: "Run the scenario on a hardware GPU, or set maxFrameMsP95 with a maxFrameMsReason that names the adapter."
3642
+ });
3643
+ }
3280
3644
  }
3281
3645
  for (const assertion of scenarioAssertions.resources ?? []) {
3282
3646
  if (assertion.anyOf !== void 0) {
@@ -3320,7 +3684,7 @@ function emitPerfSignalsWorld(ctx) {
3320
3684
  const samples = assertion.atSteps.map((expected) => {
3321
3685
  const sample = (input.report.observations?.resourceSeries ?? []).find((candidate) => candidate.label === expected.label);
3322
3686
  const value = readPath(sample?.snapshots[assertion.id], assertion.path);
3323
- const pass2 = sample !== void 0 && (!Object.hasOwn(expected, "equals") || jsonEqual(value, expected.equals)) && (expected.textIncludes === void 0 || String(textValue(value)).includes(expected.textIncludes));
3687
+ 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));
3324
3688
  return { expected, pass: pass2, value };
3325
3689
  });
3326
3690
  const pass = samples.every((sample) => sample.pass);
@@ -3405,6 +3769,20 @@ function emitTerrainResidency(component, assertions, diagnostics) {
3405
3769
  suggestion: "Expose TerrainTiles.debug() through the terrain entity and inspect the residency counters."
3406
3770
  });
3407
3771
  }
3772
+ var FRAME_BUDGET_MS = 16.7;
3773
+ function frameBudget(explicit, adapter, reason) {
3774
+ const identity = {
3775
+ ...adapter.adapterClass === void 0 ? {} : { adapterClass: adapter.adapterClass },
3776
+ ...adapter.gpuFamily === void 0 ? {} : { gpuFamily: adapter.gpuFamily }
3777
+ };
3778
+ if (explicit !== void 0) {
3779
+ return { ...identity, maxFrameMsP95: explicit, reason: `maxFrameMsP95 set in the scenario overrides ${FRAME_BUDGET_MS} ms${reason === void 0 ? "" : `: ${reason}`}`, source: "scenario" };
3780
+ }
3781
+ if (adapter.adapterClass === "software") {
3782
+ return { ...identity, reason: `software adapter ${adapter.softwareAdapter ?? ""} is unmeasurable: it cannot carry a frame rate`.replace(" ", " "), source: "adapter", unmeasurable: true };
3783
+ }
3784
+ return { ...identity, maxFrameMsP95: FRAME_BUDGET_MS, reason: `one 60 Hz frame (${FRAME_BUDGET_MS} ms) on every tier`, source: "adapter" };
3785
+ }
3408
3786
 
3409
3787
  // src/evaluators/world-gameplay.ts
3410
3788
  function emitWorldGameplay(ctx) {
@@ -3930,100 +4308,6 @@ function emitWorldTopology(value, assertions, diagnostics) {
3930
4308
  }
3931
4309
  }
3932
4310
 
3933
- // src/runner/browser.ts
3934
- [
3935
- "--ozone-platform=x11",
3936
- "--enable-unsafe-webgpu",
3937
- "--disable-gpu-sandbox",
3938
- "--ignore-gpu-blocklist",
3939
- // Keep Vulkan available on both hardware and software adapters.
3940
- "--enable-features=Vulkan",
3941
- // Forced ANGLE/Vulkan selects NVIDIA locally but breaks hosted software adapters, especially headed.
3942
- // Apply that workaround only when the caller explicitly requests the host display.
3943
- ...typeof process !== "undefined" && process.env.TN_PLAYTEST_HOST_DISPLAY === "1" ? ["--use-angle=vulkan", "--use-vulkan", "--disable-vulkan-surface"] : []
3944
- ];
3945
- var SOFTWARE_ADAPTER = /swiftshader|llvmpipe|lavapipe|softwarerasterizer|software adapter|basic render/i;
3946
- function softwareAdapterName(adapter) {
3947
- if (adapter === void 0) return void 0;
3948
- for (const value of Object.values(adapter)) {
3949
- if (typeof value === "string" && SOFTWARE_ADAPTER.test(value)) return value;
3950
- }
3951
- return void 0;
3952
- }
3953
-
3954
- // src/evaluators/adapter-class.ts
3955
- function classifyAdapter(report) {
3956
- const capture = report.capture;
3957
- if (capture === void 0 || capture.rendererKind !== "webgpu") return {};
3958
- if (adapterIdentity(capture.adapter) === void 0) return {};
3959
- const software = softwareAdapterName(capture.adapter);
3960
- if (software !== void 0) return { adapterClass: "software", softwareAdapter: software };
3961
- const gpuFamily = gpuFamilyOf(capture.adapter);
3962
- return gpuFamily === void 0 ? { adapterClass: "hardware" } : { adapterClass: "hardware", gpuFamily };
3963
- }
3964
- var ADAPTER_IDENTITY_KEYS = ["architecture", "description", "device", "vendor"];
3965
- function adapterIdentity(adapter) {
3966
- if (adapter === void 0) return void 0;
3967
- for (const key of ADAPTER_IDENTITY_KEYS) {
3968
- const value = adapter[key];
3969
- if (typeof value === "string" && value.trim() !== "") return value;
3970
- }
3971
- return void 0;
3972
- }
3973
- var MALI_MODEL = /\bmali[\s_-]*g?[\s-]*(\d{2,3})/i;
3974
- var ADRENO_MODEL = /\badreno\W*(?:tm\W*)?(\d)(\d\d|xx)/i;
3975
- var AMD_INTEGRATED = /radeon(?:\(tm\))?\s+(?:graphics|\d{3}m)\b/i;
3976
- var INTEL_DISCRETE = /\barc\b|xe2?-hpg|battlemage|alchemist/i;
3977
- var FAMILY_RULES = [
3978
- ({ architecture, description, device }) => {
3979
- const number = [description, device, architecture].map((value) => MALI_MODEL.exec(value)?.[1]).find((value) => value !== void 0);
3980
- if (number === void 0) return void 0;
3981
- const model = Number(number);
3982
- if (model >= 710) return "mobile-high";
3983
- return model < 57 || model === 71 || model === 72 ? "mobile-low" : "mobile-mid";
3984
- },
3985
- ({ architecture, vendor }) => {
3986
- if (!/\barm\b/i.test(vendor)) return void 0;
3987
- if (/midgard|bifrost/i.test(architecture)) return "mobile-low";
3988
- if (/valhall/i.test(architecture)) return "mobile-mid";
3989
- return /5th-?gen|immortalis/i.test(architecture) ? "mobile-high" : void 0;
3990
- },
3991
- ({ architecture, description, device }) => {
3992
- const match = [description, device, architecture].map((value) => ADRENO_MODEL.exec(value)).find((value) => value !== null && value !== void 0);
3993
- if (match === null || match === void 0) return void 0;
3994
- const generation = Number(match[1]);
3995
- if (generation <= 4) return "mobile-low";
3996
- if (generation === 5) return "mobile-mid";
3997
- if (generation === 6) return match[2] !== "xx" && Number(match[2]) >= 30 ? "mobile-high" : "mobile-mid";
3998
- return "mobile-high";
3999
- },
4000
- ({ architecture, description, device, vendor }) => /nvidia/i.test(vendor) && ![architecture, description, device].some((value) => /tegra/i.test(value)) ? "discrete" : void 0,
4001
- ({ architecture, description, device, vendor }) => {
4002
- if (!/intel/i.test(vendor)) return void 0;
4003
- return [architecture, description, device].some((value) => INTEL_DISCRETE.test(value)) ? "discrete" : "integrated";
4004
- },
4005
- // An APU and a card share an architecture name, so an AMD adapter that names no iGPU is `discrete`.
4006
- ({ description, vendor }) => /\b(?:amd|ati)\b/i.test(vendor) ? AMD_INTEGRATED.test(description) ? "integrated" : "discrete" : void 0
4007
- ];
4008
- function gpuFamilyOf(adapter) {
4009
- if (adapter === void 0) return void 0;
4010
- const field = (key) => {
4011
- const value = adapter[key];
4012
- return typeof value === "string" ? value : "";
4013
- };
4014
- const fields = {
4015
- architecture: field("architecture"),
4016
- description: field("description"),
4017
- device: field("device"),
4018
- vendor: field("vendor")
4019
- };
4020
- for (const rule of FAMILY_RULES) {
4021
- const family = rule(fields);
4022
- if (family !== void 0) return family;
4023
- }
4024
- return void 0;
4025
- }
4026
-
4027
4311
  // src/evaluators/render-chain.ts
4028
4312
  function emitRenderChain(ctx) {
4029
4313
  const assertion = ctx.scenarioAssertions.renderChain;
@@ -4445,6 +4729,344 @@ function emitPerNode(ctx, id, index, bound, observation, sampled, expected, read
4445
4729
  });
4446
4730
  }
4447
4731
 
4732
+ // src/evaluators/foot-slip.ts
4733
+ var FOOT_SLIP_MIN_TRAVEL_M = 0.5;
4734
+ var FOOT_SLIP_CONTACT_BAND = 0.25;
4735
+ var MIN_CONTACT_PAIRS = 4;
4736
+ var DEFAULT_STEP_SECONDS = 1 / 60;
4737
+ function measureFootSlip(observation, stepSeconds = DEFAULT_STEP_SECONDS) {
4738
+ const { samples } = observation;
4739
+ let travel = 0;
4740
+ for (let index = 1; index < samples.length; index += 1) {
4741
+ const before = samples[index - 1].body;
4742
+ const after = samples[index].body;
4743
+ if (before !== null && after !== null) travel += Math.hypot(after[0] - before[0], after[2] - before[2]);
4744
+ }
4745
+ if (samples.length < 2 || samples.some(({ body }) => body === null))
4746
+ return { feet: [], travel, unobserved: `the subject '${observation.entity}' was not reported on every tick` };
4747
+ const missing = observation.feet.filter((_name, foot) => samples.some((sample) => sample.feet[foot] === null));
4748
+ if (missing.length > 0)
4749
+ 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` };
4750
+ if (travel < FOOT_SLIP_MIN_TRAVEL_M)
4751
+ 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` };
4752
+ const feet = observation.feet.map((name, foot) => {
4753
+ const heights = samples.map((sample) => sample.feet[foot][1] - sample.body[1]);
4754
+ const low = Math.min(...heights);
4755
+ const lift = Math.max(...heights) - low;
4756
+ const planted = heights.map((height) => height <= low + FOOT_SLIP_CONTACT_BAND * lift);
4757
+ let footTravel = 0;
4758
+ let bodyTravel = 0;
4759
+ let contactPairs = 0;
4760
+ for (let index = 1; index < samples.length; index += 1) {
4761
+ if (!planted[index - 1] || !planted[index]) continue;
4762
+ const [fx0, , fz0] = samples[index - 1].feet[foot];
4763
+ const [fx1, , fz1] = samples[index].feet[foot];
4764
+ const [bx0, , bz0] = samples[index - 1].body;
4765
+ const [bx1, , bz1] = samples[index].body;
4766
+ footTravel += Math.hypot(fx1 - fx0, fz1 - fz0);
4767
+ bodyTravel += Math.hypot(bx1 - bx0, bz1 - bz0);
4768
+ contactPairs += 1;
4769
+ }
4770
+ return {
4771
+ contactPairs,
4772
+ lift,
4773
+ name,
4774
+ ...contactPairs < MIN_CONTACT_PAIRS || bodyTravel <= 0 ? {} : { slip: footTravel / bodyTravel, speed: footTravel / (contactPairs * stepSeconds) }
4775
+ };
4776
+ });
4777
+ return { feet, travel };
4778
+ }
4779
+ function emitFootSlip(ctx) {
4780
+ const assertions = ctx.scenarioAssertions.footSlip;
4781
+ if (assertions === void 0 || assertions.length === 0) return;
4782
+ assertions.forEach((assertion, index) => {
4783
+ const id = `footSlip[${index}]`;
4784
+ const observation = ctx.input.report.observations?.footSlip?.find(({ label }) => label === assertion.atStep);
4785
+ const measure = observation === void 0 ? void 0 : measureFootSlip(observation, assertion.stepSeconds);
4786
+ const unmeasured = measure?.feet.find(({ slip }) => slip === void 0);
4787
+ 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`);
4788
+ if (reason !== void 0) {
4789
+ ctx.assertions.push({ details: { atStep: assertion.atStep, reason, ...measure === void 0 ? {} : { travel: measure.travel } }, id: `${id}.observed`, pass: false });
4790
+ ctx.diagnostics.push({
4791
+ code: "TN_PLAYTEST_FOOT_SLIP_UNOBSERVED",
4792
+ message: `footSlip at '${assertion.atStep}' was not measured: ${reason}.`,
4793
+ observedRuntimePath: "observations.json/footSlip",
4794
+ severity: "error",
4795
+ 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."
4796
+ });
4797
+ return;
4798
+ }
4799
+ const animation = runtimeGameplaySamples(ctx.input.report.observations?.runtimeObservations).find(({ label }) => label === assertion.atStep)?.gameplay.animation;
4800
+ const stride = isRecord(animation) ? strideReading(animation[observation.entity]) : void 0;
4801
+ if (stride !== void 0 && strideHasNoFootPlant(stride)) {
4802
+ ctx.assertions.push({ details: { atStep: assertion.atStep, reason: NO_FOOT_PLANT_DETAIL, stride, travel: measure.travel }, id: `${id}.observed`, pass: false });
4803
+ ctx.diagnostics.push({
4804
+ code: "TN_PLAYTEST_STRIDE_NO_FOOT_PLANT",
4805
+ message: `footSlip at '${assertion.atStep}' failed closed: ${NO_FOOT_PLANT_DETAIL}.`,
4806
+ observedRuntimePath: "observations.json/runtimeObservations",
4807
+ severity: "error",
4808
+ 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."
4809
+ });
4810
+ return;
4811
+ }
4812
+ const worst = Math.max(...measure.feet.map(({ slip }) => slip));
4813
+ const worstSpeed = Math.max(...measure.feet.map(({ speed }) => speed));
4814
+ const slipPass = assertion.maxSlip === void 0 || worst <= assertion.maxSlip;
4815
+ const speedPass = assertion.maxSlideSpeed === void 0 || worstSpeed <= assertion.maxSlideSpeed;
4816
+ ctx.assertions.push({
4817
+ details: {
4818
+ atStep: assertion.atStep,
4819
+ expected: { maxSlideSpeed: assertion.maxSlideSpeed, maxSlip: assertion.maxSlip },
4820
+ feet: measure.feet,
4821
+ travel: measure.travel,
4822
+ worst,
4823
+ worstSpeed
4824
+ },
4825
+ id: `${id}.slip`,
4826
+ pass: slipPass && speedPass
4827
+ });
4828
+ if (!slipPass)
4829
+ ctx.diagnostics.push({
4830
+ code: "TN_PLAYTEST_FOOT_SLIP",
4831
+ message: `A planted foot travelled ${worst.toFixed(2)} m per metre of body travel at '${assertion.atStep}', ceiling ${assertion.maxSlip}.`,
4832
+ observedRuntimePath: "observations.json/footSlip",
4833
+ severity: "error",
4834
+ 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."
4835
+ });
4836
+ if (!speedPass)
4837
+ ctx.diagnostics.push({
4838
+ code: "TN_PLAYTEST_FOOT_SLIP",
4839
+ message: `A planted foot slid at ${worstSpeed.toFixed(2)} m/s at '${assertion.atStep}', ceiling ${assertion.maxSlideSpeed} m/s.`,
4840
+ observedRuntimePath: "observations.json/footSlip",
4841
+ severity: "error",
4842
+ 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."
4843
+ });
4844
+ });
4845
+ }
4846
+
4847
+ // src/evaluators/sight-line.ts
4848
+ var MAX_BLOCKER_NAMES = 5;
4849
+ function topBlockers(blockers) {
4850
+ const counts = /* @__PURE__ */ new Map();
4851
+ for (const name of blockers) counts.set(name, (counts.get(name) ?? 0) + 1);
4852
+ return [...counts.entries()].sort(([leftName, leftCount], [rightName, rightCount]) => rightCount - leftCount || leftName.localeCompare(rightName)).slice(0, MAX_BLOCKER_NAMES).map(([name]) => name);
4853
+ }
4854
+ function emitSightLine(ctx) {
4855
+ const assertion = ctx.scenarioAssertions.sightLine;
4856
+ if (assertion === void 0) return;
4857
+ const observation = ctx.input.report.observations?.sightLine;
4858
+ const samples = observation?.samples ?? [];
4859
+ if (samples.length === 0) {
4860
+ ctx.assertions.push({ details: { samples: 0 }, id: "sightLine.observed", pass: false });
4861
+ ctx.diagnostics.push({
4862
+ code: "TN_PLAYTEST_SIGHT_LINE_UNOBSERVED",
4863
+ message: "A sightLine assertion was evaluated against a run that sampled no camera-to-subject sight line.",
4864
+ observedRuntimePath: "observations.json/sightLine",
4865
+ severity: "error",
4866
+ suggestion: "Run on the browser target and make sure the scenario advances at least one step whose subject is registered with the bridge."
4867
+ });
4868
+ return;
4869
+ }
4870
+ const blockedCount = samples.filter(({ blocked }) => blocked).length;
4871
+ const ratio = blockedCount / samples.length;
4872
+ const pass = ratio <= assertion.maxBlockedRatio;
4873
+ const blockers = topBlockers(samples.flatMap((sample) => sample.blockers));
4874
+ ctx.assertions.push({
4875
+ details: { blocked: blockedCount, blockers, ratio, samples: samples.length },
4876
+ id: "sightLine",
4877
+ pass
4878
+ });
4879
+ if (!pass) {
4880
+ ctx.diagnostics.push({
4881
+ code: "TN_PLAYTEST_SIGHT_LINE_BLOCKED",
4882
+ message: `Solid geometry blocked the camera's view of '${observation.entity}' on ${blockedCount} of ${samples.length} samples (${(ratio * 100).toFixed(1)}%), ceiling ${assertion.maxBlockedRatio}.`,
4883
+ observedRuntimePath: "observations.json/sightLine",
4884
+ severity: "error",
4885
+ 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."
4886
+ });
4887
+ }
4888
+ }
4889
+
4890
+ // src/evaluators/hud-audit.ts
4891
+ var MAX_OFFENDERS = 5;
4892
+ var JUDGED_BACKGROUND_ALPHA = 0.5;
4893
+ var DEVELOPER_TEXT = /\b(debug|todo|fixme|lorem ipsum|placeholder|probe|raycast|hitbox|wall ray)\b/iu;
4894
+ var UNRESOLVED_TEXT = /\b(undefined|null|NaN)\b/u;
4895
+ var COERCED_OBJECT = /\[object /u;
4896
+ function channelLuminance(channel) {
4897
+ const value = channel / 255;
4898
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
4899
+ }
4900
+ function relativeLuminance([red, green, blue]) {
4901
+ return 0.2126 * channelLuminance(red) + 0.7152 * channelLuminance(green) + 0.0722 * channelLuminance(blue);
4902
+ }
4903
+ function contrastRatio(foreground, background) {
4904
+ const alpha = Math.min(Math.max(foreground[3], 0), 1);
4905
+ const composited = [
4906
+ foreground[0] * alpha + background[0] * (1 - alpha),
4907
+ foreground[1] * alpha + background[1] * (1 - alpha),
4908
+ foreground[2] * alpha + background[2] * (1 - alpha),
4909
+ 1
4910
+ ];
4911
+ const first = relativeLuminance(composited);
4912
+ const second = relativeLuminance(background);
4913
+ return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
4914
+ }
4915
+ function readsAsDeveloperText(text) {
4916
+ return DEVELOPER_TEXT.test(text) || UNRESOLVED_TEXT.test(text) || COERCED_OBJECT.test(text);
4917
+ }
4918
+ function offenders(items) {
4919
+ return items.slice(0, MAX_OFFENDERS).map(({ selector, text }) => ({ selector, text }));
4920
+ }
4921
+ function emitHudAudit(ctx) {
4922
+ const assertion = ctx.scenarioAssertions.hudAudit;
4923
+ if (assertion === void 0) return;
4924
+ const items = ctx.input.report.observations?.hudAudit?.items ?? [];
4925
+ if (items.length === 0) {
4926
+ ctx.assertions.push({ details: { items: 0 }, id: "hudAudit.observed", pass: false });
4927
+ ctx.diagnostics.push({
4928
+ code: "TN_PLAYTEST_HUD_AUDIT_UNOBSERVED",
4929
+ message: "A hudAudit assertion was evaluated against a run that reported no visible page text.",
4930
+ observedRuntimePath: "observations.json/hudAudit",
4931
+ severity: "error",
4932
+ suggestion: "Run on the browser target and make sure the page draws player-facing text in the DOM, outside a canvas."
4933
+ });
4934
+ return;
4935
+ }
4936
+ if (assertion.noDebugText === true) {
4937
+ const found = items.filter(({ text }) => readsAsDeveloperText(text));
4938
+ const pass = found.length === 0;
4939
+ ctx.assertions.push({
4940
+ details: { checked: items.length, offenders: offenders(found) },
4941
+ id: "hudAudit.debugText",
4942
+ pass
4943
+ });
4944
+ if (!pass) {
4945
+ ctx.diagnostics.push({
4946
+ code: "TN_PLAYTEST_HUD_DEBUG_TEXT",
4947
+ 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(", ")}.`,
4948
+ observedRuntimePath: "observations.json/hudAudit/items",
4949
+ severity: "error",
4950
+ suggestion: "Replace debug, TODO, placeholder and unresolved values with the copy the player should read, then rerun the scenario."
4951
+ });
4952
+ }
4953
+ }
4954
+ if (assertion.minContrast !== void 0) {
4955
+ const judged = items.filter(({ background }) => background[3] >= JUDGED_BACKGROUND_ALPHA);
4956
+ const unjudged = items.length - judged.length;
4957
+ 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);
4958
+ const pass = worst.every(({ ratio }) => ratio >= assertion.minContrast);
4959
+ ctx.assertions.push({
4960
+ details: { judged: judged.length, minContrast: assertion.minContrast, unjudged, worst },
4961
+ id: "hudAudit.contrast",
4962
+ pass
4963
+ });
4964
+ if (!pass) {
4965
+ ctx.diagnostics.push({
4966
+ code: "TN_PLAYTEST_HUD_CONTRAST",
4967
+ 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(", ")}.`,
4968
+ observedRuntimePath: "observations.json/hudAudit/items",
4969
+ severity: "error",
4970
+ suggestion: "Raise the text colour's contrast against its backing plate, or darken the plate, until every judged item reaches the floor."
4971
+ });
4972
+ }
4973
+ }
4974
+ }
4975
+
4976
+ // src/evaluators/engine-cost.ts
4977
+ var FRAME_BUDGET_MARKER = "TN_FRAME_BUDGET:";
4978
+ var BRIDGE_CENSUS_MARKER = "TN_BRIDGE_CENSUS:";
4979
+ function engineCostWindows(lines) {
4980
+ const windows = [];
4981
+ let top;
4982
+ for (const line of lines) {
4983
+ if (typeof line !== "string") continue;
4984
+ const census = line.indexOf(BRIDGE_CENSUS_MARKER);
4985
+ if (census !== -1) {
4986
+ try {
4987
+ top = JSON.parse(line.slice(census + BRIDGE_CENSUS_MARKER.length)).top;
4988
+ } catch {
4989
+ top = void 0;
4990
+ }
4991
+ continue;
4992
+ }
4993
+ const at = line.indexOf(FRAME_BUDGET_MARKER);
4994
+ if (at === -1) continue;
4995
+ try {
4996
+ const report = JSON.parse(line.slice(at + FRAME_BUDGET_MARKER.length));
4997
+ const engine = report.counters?.engine;
4998
+ if (engine === void 0) continue;
4999
+ if (engine === null || typeof engine !== "object" || Array.isArray(engine)) throw new Error("invalid engine counters");
5000
+ const series = {
5001
+ ...engine,
5002
+ ...report.counters?.bridgeCrossings === void 0 ? {} : { bridgeCrossings: report.counters.bridgeCrossings }
5003
+ };
5004
+ for (const summary of Object.values(series)) {
5005
+ 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");
5006
+ }
5007
+ const pick = (field) => Object.fromEntries(Object.entries(series).map(([name, summary]) => [name, summary[field]]));
5008
+ windows.push({ maxFrame: pick("max"), perFrame: pick("mean"), top, ...report.window === void 0 ? {} : { window: report.window } });
5009
+ } catch {
5010
+ windows.push(void 0);
5011
+ }
5012
+ }
5013
+ return windows;
5014
+ }
5015
+ function topCaller(window) {
5016
+ const top = window.top?.[0];
5017
+ return top === void 0 ? "no census before this window" : `${top.name ?? "?"} ${top.perFrame ?? "?"}/frame from ${top.caller ?? "unknown"}`;
5018
+ }
5019
+ function emitEngineCost(ctx) {
5020
+ const assertion = ctx.scenarioAssertions.engineCost;
5021
+ if (assertion === void 0) return;
5022
+ const windows = engineCostWindows((ctx.input.report.observations?.console ?? []).map(({ text }) => text));
5023
+ const stillWindows = assertion.still?.windows ?? 0;
5024
+ const skipped = assertion.skipWindows ?? 0;
5025
+ const needed = Math.max(assertion.minWindows ?? 1, skipped + stillWindows + (assertion.moving === void 0 ? 0 : 1));
5026
+ const readable = windows.filter((window) => window !== void 0);
5027
+ const observed = readable.length >= needed && readable.length === windows.length;
5028
+ ctx.assertions.push({ details: { windows: windows.length, unreadable: windows.length - readable.length, needed }, id: "engineCost.observed", pass: observed });
5029
+ if (!observed) {
5030
+ ctx.diagnostics.push({
5031
+ code: "TN_PLAYTEST_ENGINE_COST_UNOBSERVED",
5032
+ message: `engineCost needs ${needed} readable TN_FRAME_BUDGET window(s) with counters.engine; the run printed ${windows.length}, ${windows.length - readable.length} unreadable.`,
5033
+ observedRuntimePath: "observations.json/console",
5034
+ severity: "error",
5035
+ 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."
5036
+ });
5037
+ return;
5038
+ }
5039
+ const bounded = readable.slice(skipped);
5040
+ for (const [kind, table, scope, windows2] of [
5041
+ ["perFrame", assertion.maxPerFrame, "maxPerFrame", bounded],
5042
+ ["maxFrame", assertion.maxInFrame, "maxInFrame", bounded],
5043
+ ["perFrame", assertion.still?.maxPerFrame, "still.maxPerFrame", bounded.slice(0, stillWindows)],
5044
+ ["perFrame", assertion.moving?.maxPerFrame, "moving.maxPerFrame", bounded.slice(stillWindows)],
5045
+ ["maxFrame", assertion.moving?.maxInFrame, "moving.maxInFrame", bounded.slice(stillWindows)]
5046
+ ]) {
5047
+ for (const [name, bound] of Object.entries(table ?? {})) {
5048
+ const values = windows2.map((window) => window[kind]?.[name]);
5049
+ const missing = values.findIndex((value2) => typeof value2 !== "number" || !Number.isFinite(value2));
5050
+ const worst = windows2.reduce(
5051
+ (top, window) => (window[kind]?.[name] ?? -1) > (top?.[kind]?.[name] ?? -1) ? window : top,
5052
+ void 0
5053
+ );
5054
+ const value = worst?.[kind]?.[name] ?? Number.NaN;
5055
+ const pass = missing === -1 && value <= bound;
5056
+ const id = `engineCost.${scope}.${name}`;
5057
+ ctx.assertions.push({ details: { bound, value, window: worst?.window, source: assertion.source }, id, pass });
5058
+ if (pass) continue;
5059
+ ctx.diagnostics.push({
5060
+ code: "TN_PLAYTEST_ENGINE_COST_OVER_BOUND",
5061
+ 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)}.`,
5062
+ observedRuntimePath: "observations.json/console",
5063
+ severity: "error",
5064
+ 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."
5065
+ });
5066
+ }
5067
+ }
5068
+ }
5069
+
4448
5070
  // src/runner/sceneRoom.ts
4449
5071
  var LIT_MATERIAL_PATTERN = /standard|physical|lambert|phong|toon/iu;
4450
5072
  function summariseRoom(scene) {
@@ -4566,12 +5188,47 @@ function emitScene(ctx) {
4566
5188
  }
4567
5189
 
4568
5190
  // src/evaluators/startup.ts
5191
+ var MB = 1e6;
5192
+ var mb = (bytes) => `${(bytes / MB).toFixed(1)} MB`;
5193
+ function emitOffscreenBytes(ctx) {
5194
+ const ceiling = ctx.scenarioAssertions.startup?.maxOffscreenBytes;
5195
+ const observed = ctx.input.report.observations?.startup?.offscreenBytes;
5196
+ const unsized = observed !== void 0 && observed.awaitedBytes === 0 && observed.unsizedFiles > 0;
5197
+ if (ceiling !== void 0) {
5198
+ const measured = observed !== void 0 && !unsized;
5199
+ const pass = measured && observed.offscreenBytes <= ceiling;
5200
+ ctx.assertions.push({
5201
+ details: { expected: ceiling, observed: measured ? observed.offscreenBytes : void 0 },
5202
+ id: "startup.offscreenBytes",
5203
+ pass
5204
+ });
5205
+ if (!pass) {
5206
+ ctx.diagnostics.push({
5207
+ code: measured ? "TN_PLAYTEST_STARTUP_OFFSCREEN_BYTES" : "TN_PLAYTEST_STARTUP_UNOBSERVABLE",
5208
+ 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.`,
5209
+ observedRuntimePath: "observations.json/startup/offscreenBytes",
5210
+ severity: "error",
5211
+ 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."
5212
+ });
5213
+ return;
5214
+ }
5215
+ }
5216
+ if (observed?.warn !== true) return;
5217
+ ctx.diagnostics.push({
5218
+ code: "TN_PLAYTEST_STARTUP_OFFSCREEN_BYTES",
5219
+ 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(", ")}).`,
5220
+ observedRuntimePath: "observations.json/startup/offscreenBytes",
5221
+ severity: "warning",
5222
+ suggestion: observed.fix
5223
+ });
5224
+ }
4569
5225
  var MILESTONES = {
4570
5226
  maxCompileSettledMs: "compileSettledMs",
4571
5227
  maxEnteredMs: "enteredMs",
4572
5228
  maxReadyMs: "readyMs"
4573
5229
  };
4574
5230
  function emitStartup(ctx) {
5231
+ emitOffscreenBytes(ctx);
4575
5232
  const assertion = ctx.scenarioAssertions.startup;
4576
5233
  if (assertion === void 0) return;
4577
5234
  const timeline = ctx.input.report.observations?.startup?.timeline;
@@ -4594,6 +5251,28 @@ function emitStartup(ctx) {
4594
5251
  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."
4595
5252
  });
4596
5253
  }
5254
+ if (assertion.steadyCover === true) emitSteadyCover(ctx);
5255
+ }
5256
+ function emitSteadyCover(ctx) {
5257
+ const cover = ctx.input.report.observations?.startup?.cover;
5258
+ const observed = cover !== void 0 && cover.frames > 0 && cover.worldMs !== void 0;
5259
+ const uiOverCover = cover?.uiOverCover ?? [];
5260
+ const pass = observed && cover.differing.length === 0 && uiOverCover.length === 0;
5261
+ ctx.assertions.push({
5262
+ 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 },
5263
+ id: "startup.steadyCover",
5264
+ pass
5265
+ });
5266
+ if (pass) return;
5267
+ const first = cover?.differing[0];
5268
+ const ui = uiOverCover[0];
5269
+ ctx.diagnostics.push({
5270
+ code: !observed ? "TN_PLAYTEST_STARTUP_COVER_UNOBSERVED" : first === void 0 && ui !== void 0 ? "TN_PLAYTEST_STARTUP_UI_OVER_COVER" : "TN_PLAYTEST_STARTUP_COVER_BROKEN",
5271
+ 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.",
5272
+ observedRuntimePath: "observations.json/startup/cover",
5273
+ severity: "error",
5274
+ 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."
5275
+ });
4597
5276
  }
4598
5277
 
4599
5278
  // src/runner/pipeline-summary.ts
@@ -5738,6 +6417,10 @@ function evaluateRichPlaytestAssertions(input) {
5738
6417
  emitPipelineCensus(ctx);
5739
6418
  emitScene(ctx);
5740
6419
  emitSceneNodes(ctx);
6420
+ emitFootSlip(ctx);
6421
+ emitSightLine(ctx);
6422
+ emitHudAudit(ctx);
6423
+ emitEngineCost(ctx);
5741
6424
  if (scenarioAssertions.geometry !== void 0) {
5742
6425
  const observed = input.report.observations?.geometry;
5743
6426
  const status = observed?.status;
@@ -6243,6 +6926,7 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
6243
6926
  }),
6244
6927
  "performance": Object.freeze({
6245
6928
  "maxFrameMsP95": (value) => typeof value === "number" && Number.isFinite(value),
6929
+ "maxFrameMsReason": (value) => typeof value === "string" && value.trim() !== "",
6246
6930
  "minFps": (value) => typeof value === "number" && Number.isFinite(value),
6247
6931
  "maxPhaseMsP95": (value) => isRecord2(value),
6248
6932
  "maxDrawCalls": (value) => typeof value === "number" && Number.isFinite(value),
@@ -6300,6 +6984,7 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
6300
6984
  "animation": Object.freeze({
6301
6985
  "entity": (value) => typeof value === "string" && value.trim() !== "",
6302
6986
  "clip": (value) => typeof value === "string" && value.trim() !== "",
6987
+ "atStep": (value) => typeof value === "string" && value.trim() !== "",
6303
6988
  "entered": (value) => typeof value === "boolean",
6304
6989
  "advancedFrames": (value) => typeof value === "number" && Number.isFinite(value),
6305
6990
  "finished": (value) => typeof value === "boolean",
@@ -6324,6 +7009,31 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
6324
7009
  "maxCount": (value) => typeof value === "number" && Number.isFinite(value),
6325
7010
  "minTriangles": (value) => typeof value === "number" && Number.isFinite(value)
6326
7011
  }),
7012
+ "footSlip": Object.freeze({
7013
+ "atStep": (value) => typeof value === "string" && value.trim() !== "",
7014
+ "feet": (value) => Array.isArray(value),
7015
+ "maxSlip": (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
7016
+ "maxSlideSpeed": (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
7017
+ "stepSeconds": (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
7018
+ "entity": (value) => typeof value === "string" && value.trim() !== ""
7019
+ }),
7020
+ "sightLine": Object.freeze({
7021
+ "entity": (value) => typeof value === "string" && value.trim() !== "",
7022
+ "maxBlockedRatio": (value) => typeof value === "number" && Number.isFinite(value)
7023
+ }),
7024
+ "engineCost": Object.freeze({
7025
+ "maxPerFrame": (value) => isRecord2(value),
7026
+ "maxInFrame": (value) => isRecord2(value),
7027
+ "minWindows": (value) => typeof value === "number" && Number.isInteger(value) && value > 0,
7028
+ "skipWindows": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
7029
+ "still": (value) => isRecord2(value),
7030
+ "moving": (value) => isRecord2(value),
7031
+ "source": (value) => typeof value === "string" && value.trim() !== ""
7032
+ }),
7033
+ "hudAudit": Object.freeze({
7034
+ "minContrast": (value) => typeof value === "number" && Number.isFinite(value),
7035
+ "noDebugText": (value) => value === true
7036
+ }),
6327
7037
  "causedBy": Object.freeze({
6328
7038
  "cause": (value) => isRecord2(value),
6329
7039
  "effect": (value) => isRecord2(value),
@@ -6333,7 +7043,9 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
6333
7043
  "startup": Object.freeze({
6334
7044
  "maxEnteredMs": (value) => typeof value === "number" && Number.isFinite(value),
6335
7045
  "maxCompileSettledMs": (value) => typeof value === "number" && Number.isFinite(value),
6336
- "maxReadyMs": (value) => typeof value === "number" && Number.isFinite(value)
7046
+ "maxReadyMs": (value) => typeof value === "number" && Number.isFinite(value),
7047
+ "maxOffscreenBytes": (value) => typeof value === "number" && Number.isFinite(value),
7048
+ "steadyCover": (value) => typeof value === "boolean"
6337
7049
  }),
6338
7050
  "pipelineCensus": Object.freeze({
6339
7051
  "maxNodeBuildsAfterWarmUpSettled": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
@@ -6365,6 +7077,9 @@ function validateVisualAssertion(value, scenarioPath, objectPath) {
6365
7077
  if (authoredEdge !== void 0) {
6366
7078
  throw invalidScenario(scenarioPath, `'${objectPath}.region.${authoredEdge}' cannot be combined with an element-bound region; the element supplies its bounds.`);
6367
7079
  }
7080
+ if (hasKey(regionRecord, "minSharpness")) {
7081
+ throw invalidScenario(scenarioPath, `'${objectPath}.region.minSharpness' measures the rendered frame; bound a static x/y/width/height region instead of an element.`);
7082
+ }
6368
7083
  region = {
6369
7084
  element,
6370
7085
  ...present("maxDarkPixelRatio", optionalRatio(regionRecord, "maxDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
@@ -6383,6 +7098,7 @@ function validateVisualAssertion(value, scenarioPath, objectPath) {
6383
7098
  }
6384
7099
  region = {
6385
7100
  ...edges,
7101
+ ...present("minSharpness", optionalPositiveNumber(regionRecord, "minSharpness", scenarioPath, `${objectPath}.region`)),
6386
7102
  ...present("maxDarkPixelRatio", optionalRatio(regionRecord, "maxDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
6387
7103
  ...present("maxLuminance", optionalRatio(regionRecord, "maxLuminance", scenarioPath, `${objectPath}.region`)),
6388
7104
  ...present("minDarkPixelRatio", optionalRatio(regionRecord, "minDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
@@ -6584,18 +7300,30 @@ function validateDeviceMetricsAssertion(value, scenarioPath, objectPath) {
6584
7300
  }
6585
7301
  return assertion;
6586
7302
  }
7303
+ var LEGACY_SCAFFOLD_FRAME_MS = 33;
7304
+ 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.";
6587
7305
  function validatePerformanceAssertion(value, scenarioPath, objectPath) {
6588
7306
  const record4 = requireRecord(value, scenarioPath, objectPath);
6589
- rejectUnknownKeys(record4, ["maxDrawCalls", "maxFrameMsP95", "maxPassDrawCalls", "maxPassTriangles", "maxPhaseMsP95", "maxTriangles", "minFps"], scenarioPath, objectPath);
7307
+ rejectUnknownKeys(record4, ["maxDrawCalls", "maxFrameMsP95", "maxFrameMsReason", "maxPassDrawCalls", "maxPassTriangles", "maxPhaseMsP95", "maxTriangles", "minFps"], scenarioPath, objectPath);
6590
7308
  const assertion = {
6591
7309
  ...present("maxDrawCalls", optionalNonNegativeNumber(record4, "maxDrawCalls", scenarioPath, objectPath)),
6592
7310
  ...present("maxFrameMsP95", optionalNonNegativeNumber(record4, "maxFrameMsP95", scenarioPath, objectPath)),
7311
+ ...present("maxFrameMsReason", optionalString(record4, "maxFrameMsReason", scenarioPath, objectPath)),
6593
7312
  ...present("maxPassDrawCalls", validatePassBudget(record4.maxPassDrawCalls, scenarioPath, `${objectPath}.maxPassDrawCalls`)),
6594
7313
  ...present("maxPassTriangles", validatePassBudget(record4.maxPassTriangles, scenarioPath, `${objectPath}.maxPassTriangles`)),
6595
7314
  ...present("maxPhaseMsP95", validatePhaseBudget(record4.maxPhaseMsP95, scenarioPath, `${objectPath}.maxPhaseMsP95`)),
6596
7315
  ...present("maxTriangles", optionalNonNegativeNumber(record4, "maxTriangles", scenarioPath, objectPath)),
6597
7316
  ...present("minFps", optionalNonNegativeNumber(record4, "minFps", scenarioPath, objectPath))
6598
7317
  };
7318
+ if (assertion.maxFrameMsP95 === LEGACY_SCAFFOLD_FRAME_MS && record4.maxFrameMsReason === void 0) {
7319
+ return { ...assertion, maxFrameMsReason: LEGACY_SCAFFOLD_FRAME_REASON };
7320
+ }
7321
+ if (assertion.maxFrameMsP95 !== void 0 && assertion.maxFrameMsP95 > 16.7 && (assertion.maxFrameMsReason ?? "").trim() === "") {
7322
+ throw invalidScenario(
7323
+ scenarioPath,
7324
+ `'${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.`
7325
+ );
7326
+ }
6599
7327
  if (Object.keys(assertion).length === 0) {
6600
7328
  throw invalidScenario(
6601
7329
  scenarioPath,
@@ -6757,8 +7485,21 @@ function validateStartupAssertion(value, scenarioPath, objectPath) {
6757
7485
  }
6758
7486
  result[key] = ceiling;
6759
7487
  }
7488
+ const bytes = record4.maxOffscreenBytes;
7489
+ if (bytes !== void 0) {
7490
+ if (typeof bytes !== "number" || !Number.isInteger(bytes) || bytes < 0) {
7491
+ throw invalidScenario(scenarioPath, `'${objectPath}.maxOffscreenBytes' must be a non-negative integer number of bytes, received ${describeValue(bytes)}.`);
7492
+ }
7493
+ result.maxOffscreenBytes = bytes;
7494
+ }
7495
+ if (record4.steadyCover !== void 0) {
7496
+ if (record4.steadyCover !== true) {
7497
+ throw invalidScenario(scenarioPath, `'${objectPath}.steadyCover' must be true, received ${describeValue(record4.steadyCover)}; leave it out to skip the check.`);
7498
+ }
7499
+ result.steadyCover = true;
7500
+ }
6760
7501
  if (Object.keys(result).length === 0) {
6761
- throw invalidScenario(scenarioPath, `'${objectPath}' must set at least one of ${STARTUP_CEILINGS.join(", ")}; an empty startup assertion observes nothing.`);
7502
+ throw invalidScenario(scenarioPath, `'${objectPath}' must set at least one of ${[...STARTUP_CEILINGS, "maxOffscreenBytes", "steadyCover"].join(", ")}; an empty startup assertion observes nothing.`);
6762
7503
  }
6763
7504
  return result;
6764
7505
  }
@@ -7067,12 +7808,116 @@ function validateSceneNodesAssertion(value, scenarioPath, objectPath) {
7067
7808
  );
7068
7809
  return result;
7069
7810
  }
7811
+ function validateFootSlipAssertion(value, scenarioPath, objectPath) {
7812
+ const record4 = requireRecord(value, scenarioPath, objectPath);
7813
+ rejectUnknownKeys(record4, ["atStep", "entity", "feet", "maxSlideSpeed", "maxSlip", "stepSeconds"], scenarioPath, objectPath);
7814
+ const feet = record4.feet;
7815
+ if (!Array.isArray(feet) || feet.length === 0 || feet.some((foot) => typeof foot !== "string" || foot.trim() === "") || new Set(feet).size !== feet.length)
7816
+ throw invalidScenario(scenarioPath, `${objectPath}.feet must be a non-empty array of unique node names; got ${describeValue(feet)}.`);
7817
+ const maxSlip = optionalPositiveNumber(record4, "maxSlip", scenarioPath, objectPath);
7818
+ const maxSlideSpeed = optionalPositiveNumber(record4, "maxSlideSpeed", scenarioPath, objectPath);
7819
+ if (maxSlip === void 0 && maxSlideSpeed === void 0)
7820
+ throw invalidScenario(scenarioPath, `${objectPath}.maxSlip or ${objectPath}.maxSlideSpeed is required; a slip measure with no ceiling bounds nothing.`);
7821
+ return {
7822
+ atStep: requireString(record4, "atStep", scenarioPath, objectPath),
7823
+ ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
7824
+ feet,
7825
+ ...present("maxSlideSpeed", maxSlideSpeed),
7826
+ ...present("maxSlip", maxSlip),
7827
+ ...present("stepSeconds", optionalPositiveNumber(record4, "stepSeconds", scenarioPath, objectPath))
7828
+ };
7829
+ }
7830
+ function validateSightLineAssertion(value, scenarioPath, objectPath) {
7831
+ const record4 = requireRecord(value, scenarioPath, objectPath);
7832
+ rejectUnknownKeys(record4, ["entity", "maxBlockedRatio"], scenarioPath, objectPath);
7833
+ const maxBlockedRatio = optionalRatio(record4, "maxBlockedRatio", scenarioPath, objectPath);
7834
+ if (maxBlockedRatio === void 0) throw invalidScenario(scenarioPath, `${objectPath}.maxBlockedRatio is required; a sight line with no allowed blocked share bounds nothing.`);
7835
+ return {
7836
+ ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
7837
+ maxBlockedRatio
7838
+ };
7839
+ }
7840
+ function validateEngineCostAssertion(value, scenarioPath, objectPath) {
7841
+ const record4 = requireRecord(value, scenarioPath, objectPath);
7842
+ rejectUnknownKeys(record4, ["maxInFrame", "maxPerFrame", "minWindows", "moving", "skipWindows", "source", "still"], scenarioPath, objectPath);
7843
+ const bounds = (key, owner = record4, at = objectPath) => {
7844
+ if (!hasKey(owner, key)) return void 0;
7845
+ const table = requireRecord(owner[key], scenarioPath, `${at}.${key}`);
7846
+ const names = Object.keys(table);
7847
+ if (names.length === 0) throw invalidScenario(scenarioPath, `'${at}.${key}' names no counter.`);
7848
+ for (const name of names) {
7849
+ const bound = table[name];
7850
+ if (typeof bound !== "number" || !Number.isFinite(bound) || bound < 0)
7851
+ throw invalidScenario(scenarioPath, `'${at}.${key}.${name}' must be a non-negative number, received ${describeValue(bound)}.`);
7852
+ }
7853
+ return table;
7854
+ };
7855
+ const maxPerFrame = bounds("maxPerFrame");
7856
+ const maxInFrame = bounds("maxInFrame");
7857
+ let still;
7858
+ if (hasKey(record4, "still")) {
7859
+ const at = `${objectPath}.still`;
7860
+ const stillRecord = requireRecord(record4.still, scenarioPath, at);
7861
+ rejectUnknownKeys(stillRecord, ["maxPerFrame", "windows"], scenarioPath, at);
7862
+ const windows = optionalPositiveInteger(stillRecord, "windows", scenarioPath, at);
7863
+ const stillBounds = bounds("maxPerFrame", stillRecord, at);
7864
+ if (windows === void 0 || stillBounds === void 0)
7865
+ throw invalidScenario(scenarioPath, `${at} needs 'windows' and 'maxPerFrame'.`);
7866
+ still = { maxPerFrame: stillBounds, windows };
7867
+ }
7868
+ let moving;
7869
+ if (hasKey(record4, "moving")) {
7870
+ const at = `${objectPath}.moving`;
7871
+ const movingRecord = requireRecord(record4.moving, scenarioPath, at);
7872
+ rejectUnknownKeys(movingRecord, ["maxInFrame", "maxPerFrame"], scenarioPath, at);
7873
+ if (still === void 0) throw invalidScenario(scenarioPath, `${at} needs 'still': the moving windows are the ones after it.`);
7874
+ const movingPerFrame = bounds("maxPerFrame", movingRecord, at);
7875
+ const movingInFrame = bounds("maxInFrame", movingRecord, at);
7876
+ if (movingPerFrame === void 0 && movingInFrame === void 0)
7877
+ throw invalidScenario(scenarioPath, `${at} must bound at least one counter.`);
7878
+ moving = { ...present("maxPerFrame", movingPerFrame), ...present("maxInFrame", movingInFrame) };
7879
+ }
7880
+ if (maxPerFrame === void 0 && maxInFrame === void 0 && still === void 0 && moving === void 0)
7881
+ throw invalidScenario(scenarioPath, `${objectPath} must bound at least one counter in 'maxPerFrame', 'maxInFrame', 'still' or 'moving'.`);
7882
+ const source = requireString(record4, "source", scenarioPath, objectPath);
7883
+ if (source.trim().length < 12)
7884
+ throw invalidScenario(scenarioPath, `'${objectPath}.source' must say where the bounds came from.`);
7885
+ return {
7886
+ ...present("maxPerFrame", maxPerFrame),
7887
+ ...present("maxInFrame", maxInFrame),
7888
+ ...present("minWindows", optionalPositiveInteger(record4, "minWindows", scenarioPath, objectPath)),
7889
+ ...present("skipWindows", optionalNonNegativeInteger(record4, "skipWindows", scenarioPath, objectPath)),
7890
+ source,
7891
+ ...present("still", still),
7892
+ ...present("moving", moving)
7893
+ };
7894
+ }
7895
+ function validateHudAuditAssertion(value, scenarioPath, objectPath) {
7896
+ const record4 = requireRecord(value, scenarioPath, objectPath);
7897
+ rejectUnknownKeys(record4, ["minContrast", "noDebugText"], scenarioPath, objectPath);
7898
+ const noDebugText = optionalBoolean(record4, "noDebugText", scenarioPath, objectPath);
7899
+ if (noDebugText === false) {
7900
+ throw invalidScenario(scenarioPath, `'${objectPath}.noDebugText' may only be true; remove the key to stop scanning for developer text.`);
7901
+ }
7902
+ const minContrast = optionalNumber2(record4, "minContrast", scenarioPath, objectPath);
7903
+ if (minContrast !== void 0 && (minContrast < 1 || minContrast > 21)) {
7904
+ throw invalidScenario(scenarioPath, `'${objectPath}.minContrast' must be between 1 and 21, received ${describeValue(minContrast)}.`);
7905
+ }
7906
+ if (noDebugText === void 0 && minContrast === void 0) {
7907
+ throw invalidScenario(scenarioPath, `${objectPath} must declare at least one of 'minContrast' or 'noDebugText'.`);
7908
+ }
7909
+ return {
7910
+ ...present("minContrast", minContrast),
7911
+ ...noDebugText === void 0 ? {} : { noDebugText: true }
7912
+ };
7913
+ }
7070
7914
  function validateAnimationAssertion(value, scenarioPath, objectPath) {
7071
7915
  const record4 = requireRecord(value, scenarioPath, objectPath);
7072
- rejectUnknownKeys(record4, ["advancedFrames", "allowTrivial", "clip", "entered", "entity", "finished", "maxFootSlide", "strideSynced"], scenarioPath, objectPath);
7916
+ rejectUnknownKeys(record4, ["advancedFrames", "allowTrivial", "atStep", "clip", "entered", "entity", "finished", "maxFootSlide", "strideSynced"], scenarioPath, objectPath);
7073
7917
  return {
7074
7918
  ...present("advancedFrames", optionalNumber2(record4, "advancedFrames", scenarioPath, objectPath)),
7075
7919
  ...present("allowTrivial", optionalTrivialityReason(record4, "allowTrivial", scenarioPath, objectPath)),
7920
+ ...present("atStep", optionalString(record4, "atStep", scenarioPath, objectPath)),
7076
7921
  ...present("clip", optionalString(record4, "clip", scenarioPath, objectPath)),
7077
7922
  ...present("entered", optionalBoolean(record4, "entered", scenarioPath, objectPath)),
7078
7923
  ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
@@ -7102,12 +7947,14 @@ function validatePathAssertion(value, scenarioPath, objectPath) {
7102
7947
  const atSteps = Array.isArray(record4.atSteps) ? record4.atSteps.map((step, index) => {
7103
7948
  const stepPath = `${objectPath}.atSteps[${index}]`;
7104
7949
  const entry = requireRecord(step, scenarioPath, stepPath);
7105
- if (!hasKey(entry, "equals") && entry.textIncludes === void 0) {
7106
- throw invalidScenario(scenarioPath, `'${stepPath}' must set equals or textIncludes; a labeled step with no expectation passes on any value.`);
7950
+ const stepLte = optionalNumber2(entry, "lte", scenarioPath, stepPath);
7951
+ if (!hasKey(entry, "equals") && entry.textIncludes === void 0 && stepLte === void 0) {
7952
+ throw invalidScenario(scenarioPath, `'${stepPath}' must set equals, lte or textIncludes; a labeled step with no expectation passes on any value.`);
7107
7953
  }
7108
7954
  return {
7109
7955
  ...hasKey(entry, "equals") ? { equals: entry.equals } : {},
7110
7956
  label: requireString(entry, "label", scenarioPath, stepPath),
7957
+ ...present("lte", stepLte),
7111
7958
  ...present("textIncludes", optionalString(entry, "textIncludes", scenarioPath, stepPath))
7112
7959
  };
7113
7960
  }) : void 0;
@@ -7264,7 +8111,7 @@ function validateNestedAssertionKeys(kind, value, scenarioPath, suffix) {
7264
8111
  if (Array.isArray(value.atSteps)) {
7265
8112
  value.atSteps.forEach((step, index) => {
7266
8113
  if (isRecord3(step)) {
7267
- rejectUnknownKeys(step, kind === "components" ? ["equals", "label"] : ["equals", "label", "textIncludes"], scenarioPath, `assert.${kind}${suffix}.atSteps[${index}]`);
8114
+ rejectUnknownKeys(step, kind === "components" ? ["equals", "label"] : ["equals", "label", "lte", "textIncludes"], scenarioPath, `assert.${kind}${suffix}.atSteps[${index}]`);
7268
8115
  }
7269
8116
  });
7270
8117
  }
@@ -7273,7 +8120,7 @@ function validateNestedAssertionKeys(kind, value, scenarioPath, suffix) {
7273
8120
  const fields = {
7274
8121
  entityVisible: ["entity", "minProjectedPixels", "throughoutFrames"],
7275
8122
  frameDiff: ["baselineImage", "maxChangedPixelRatio", "minChangedPixelRatio"],
7276
- region: ["element", "height", "maxDarkPixelRatio", "maxLuminance", "minDarkPixelRatio", "minNonblankPixelRatio", "width", "x", "y"]
8123
+ region: ["element", "height", "maxDarkPixelRatio", "maxLuminance", "minDarkPixelRatio", "minNonblankPixelRatio", "minSharpness", "width", "x", "y"]
7277
8124
  };
7278
8125
  for (const [field, keys] of Object.entries(fields)) {
7279
8126
  if (isRecord3(value[field])) {
@@ -7342,8 +8189,10 @@ var PLAYTEST_ROOT_KEYS = [
7342
8189
  "assert",
7343
8190
  "awaitStartup",
7344
8191
  "bootFailure",
8192
+ "clock",
7345
8193
  "inputDelivery",
7346
8194
  "name",
8195
+ "network",
7347
8196
  "parity",
7348
8197
  "reducedMotion",
7349
8198
  "schemaVersion",
@@ -7386,12 +8235,25 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7386
8235
  if (value.bootFailure !== void 0 && target !== "web") {
7387
8236
  throw invalidScenario(scenarioPath, "Scenario bootFailure is browser-only and requires target 'web'.");
7388
8237
  }
8238
+ if (value.clock !== void 0 && value.clock !== "wall-clock") {
8239
+ throw invalidScenario(scenarioPath, "Scenario clock must be 'wall-clock' when present.");
8240
+ }
8241
+ if (value.clock !== void 0 && target !== "web") {
8242
+ throw invalidScenario(scenarioPath, "Scenario clock is browser-only and requires target 'web'.");
8243
+ }
7389
8244
  if (value.reducedMotion !== void 0 && value.reducedMotion !== "reduce") {
7390
8245
  throw invalidScenario(scenarioPath, "Scenario reducedMotion must be 'reduce' when present.");
7391
8246
  }
7392
8247
  if (value.reducedMotion !== void 0 && target !== "web") {
7393
8248
  throw invalidScenario(scenarioPath, "Scenario reducedMotion is browser-only and requires target 'web'.");
7394
8249
  }
8250
+ if (value.network !== void 0 && !isRecord3(value.network)) {
8251
+ throw invalidScenario(scenarioPath, "Scenario network must be an object with downloadKbps and latencyMs.");
8252
+ }
8253
+ const network = value.network === void 0 ? void 0 : validateNetworkProfile(value.network, scenarioPath);
8254
+ if (network !== void 0 && target !== "web") {
8255
+ throw invalidScenario(scenarioPath, "Scenario network is browser-only and requires target 'web'.");
8256
+ }
7395
8257
  const inputDelivery = value.inputDelivery ?? "deterministic";
7396
8258
  if (inputDelivery !== "deterministic" && inputDelivery !== "focused-dom") {
7397
8259
  throw invalidScenario(scenarioPath, "Scenario inputDelivery must be deterministic or focused-dom.");
@@ -7406,7 +8268,7 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7406
8268
  throw invalidScenario(scenarioPath, "Scenario subject must be a non-empty entity id when present.");
7407
8269
  }
7408
8270
  const subject = typeof value.subject === "string" ? value.subject : void 0;
7409
- const steps = value.steps.map((step, index) => validateStep(step, scenarioPath, index));
8271
+ const steps = value.steps.flatMap((step, index) => isRecord3(step) && step.kind === "explore" ? expandExploreStep(step, scenarioPath, index) : [step]).map((step, index) => validateStep(step, scenarioPath, index));
7410
8272
  if (steps.some(({ kind }) => kind === "aimAt") && subject === void 0) {
7411
8273
  throw invalidScenario(scenarioPath, "A step with kind 'aimAt' aims the subject player start; declare scenario.subject or replace the step.");
7412
8274
  }
@@ -7418,8 +8280,10 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7418
8280
  ...assertions === void 0 ? {} : { assert: assertions },
7419
8281
  ...typeof value.awaitStartup === "boolean" ? { awaitStartup: value.awaitStartup } : {},
7420
8282
  ...value.bootFailure === "renderer-no-adapter" ? { bootFailure: value.bootFailure } : {},
8283
+ ...value.clock === "wall-clock" ? { clock: value.clock } : {},
7421
8284
  inputDelivery,
7422
8285
  name,
8286
+ ...network === void 0 ? {} : { network },
7423
8287
  ...value.parity === void 0 ? {} : { parity: validateParityConfig(requireRecord(value.parity, scenarioPath, "parity"), scenarioPath) },
7424
8288
  ...value.reducedMotion === "reduce" ? { reducedMotion: value.reducedMotion } : {},
7425
8289
  schemaVersion: 1,
@@ -7433,6 +8297,55 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
7433
8297
  warmupFrames: optionalNonNegativeInteger(value, "warmupFrames", scenarioPath, "scenario") ?? 0
7434
8298
  };
7435
8299
  }
8300
+ function expandExploreStep(value, scenarioPath, index) {
8301
+ rejectUnknownKeys(value, ["actions", "kind", "label", "move", "pointer", "seed", "ticks"], scenarioPath, `steps[${index}]`);
8302
+ const keys = (field) => {
8303
+ const list = value[field];
8304
+ if (list === void 0 && field === "actions") return [];
8305
+ if (!Array.isArray(list) || list.length === 0 || list.some((key) => typeof key !== "string" || key.trim() === "") || new Set(list).size !== list.length) {
8306
+ throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' must define ${field} as a non-empty array of unique key names.`);
8307
+ }
8308
+ return list;
8309
+ };
8310
+ if (!Number.isSafeInteger(value.seed)) throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' must define seed as an integer.`);
8311
+ const ticks = positiveInteger2(value.ticks);
8312
+ if (ticks === void 0) throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' must define ticks as a positive integer.`);
8313
+ if (value.pointer !== void 0 && typeof value.pointer !== "boolean") throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'explore' pointer must be a boolean.`);
8314
+ 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.`);
8315
+ const move = keys("move");
8316
+ const actions = keys("actions");
8317
+ let state = value.seed >>> 0;
8318
+ const random = () => {
8319
+ state = state + 1831565813 >>> 0;
8320
+ let t = state;
8321
+ t = Math.imul(t ^ t >>> 15, t | 1);
8322
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
8323
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
8324
+ };
8325
+ const pick = (list) => list[Math.floor(random() * list.length)];
8326
+ const steps = [];
8327
+ let heading = pick(move);
8328
+ for (let left = ticks; left > 0; ) {
8329
+ const holdTicks = Math.min(left, 10 + Math.floor(random() * 50));
8330
+ if (random() < 0.2) heading = pick(move);
8331
+ const press = /* @__PURE__ */ new Set([heading]);
8332
+ if (move.length > 1 && random() < 0.35) press.add(pick(move));
8333
+ if (actions.length > 0 && random() < 0.5) {
8334
+ press.add(pick(actions));
8335
+ if (random() < 0.25) press.add(pick(actions));
8336
+ }
8337
+ steps.push({
8338
+ holdTicks,
8339
+ kind: "input",
8340
+ press: [...press],
8341
+ ...value.pointer === true ? { pointerPosition: { x: random(), y: random() } } : {},
8342
+ release: true
8343
+ });
8344
+ left -= holdTicks;
8345
+ }
8346
+ if (typeof value.label === "string") steps[steps.length - 1].label = value.label;
8347
+ return steps;
8348
+ }
7436
8349
  function validateArtifacts(value, scenarioPath) {
7437
8350
  rejectUnknownKeys(value, ["console", "contactSheet", "effectLog", "network", "runtimeTrace", "screenshots"], scenarioPath, "artifacts");
7438
8351
  for (const key of ["console", "contactSheet", "network", "runtimeTrace"]) {
@@ -7515,12 +8428,27 @@ function validateParityTargets(value, scenarioPath, objectPath) {
7515
8428
  return target;
7516
8429
  });
7517
8430
  }
8431
+ function validateNetworkProfile(value, scenarioPath) {
8432
+ rejectUnknownKeys(value, ["downloadKbps", "latencyMs"], scenarioPath, "network");
8433
+ const downloadKbps = value.downloadKbps;
8434
+ if (typeof downloadKbps !== "number" || !Number.isFinite(downloadKbps) || downloadKbps <= 0) {
8435
+ throw invalidScenario(
8436
+ scenarioPath,
8437
+ "Scenario network.downloadKbps must be a positive number of kilobits per second."
8438
+ );
8439
+ }
8440
+ const latencyMs = value.latencyMs;
8441
+ if (typeof latencyMs !== "number" || !Number.isFinite(latencyMs) || latencyMs < 0) {
8442
+ throw invalidScenario(scenarioPath, "Scenario network.latencyMs must be a non-negative number.");
8443
+ }
8444
+ return { downloadKbps, latencyMs };
8445
+ }
7518
8446
  function validateSetup(value, scenarioPath, subject) {
7519
8447
  rejectUnknownKeys(value, ["aim", "entities", "place", "resources", "spawn"], scenarioPath, "setup");
7520
- const spawn = validateSpawnRequest(value.spawn, scenarioPath);
8448
+ const spawn2 = validateSpawnRequest(value.spawn, scenarioPath);
7521
8449
  const aim = validateAimRequest(value.aim, scenarioPath);
7522
8450
  const place = validatePlaceRequests(value.place, scenarioPath);
7523
- if (spawn !== void 0 && subject === void 0) {
8451
+ if (spawn2 !== void 0 && subject === void 0) {
7524
8452
  throw invalidScenario(scenarioPath, "Scenario setup.spawn overrides the subject player start, but the scenario declares no subject.");
7525
8453
  }
7526
8454
  if (aim !== void 0 && subject === void 0) {
@@ -7544,7 +8472,7 @@ function validateSetup(value, scenarioPath, subject) {
7544
8472
  ...Array.isArray(value.entities) ? { entities: value.entities.map((entity, index) => validateSetupEntity(entity, scenarioPath, index)) } : {},
7545
8473
  ...place === void 0 ? {} : { place },
7546
8474
  ...Array.isArray(value.resources) ? { resources: value.resources.map((resource, index) => validateSetupResource(resource, scenarioPath, index)) } : {},
7547
- ...spawn === void 0 ? {} : { spawn }
8475
+ ...spawn2 === void 0 ? {} : { spawn: spawn2 }
7548
8476
  };
7549
8477
  }
7550
8478
  function validateSpawnRequest(value, scenarioPath) {
@@ -7676,7 +8604,7 @@ var PLAYTEST_STEP_KEYS = [
7676
8604
  "wheel",
7677
8605
  "window"
7678
8606
  ];
7679
- var MAX_RESOURCE_WAIT_TIMEOUT_MS = 12e4;
8607
+ var MAX_RESOURCE_WAIT_TIMEOUT_MS = 3e5;
7680
8608
  function validateStep(value, scenarioPath, index) {
7681
8609
  if (!isRecord3(value)) {
7682
8610
  throw invalidStep(scenarioPath, `Scenario step ${index} must be a JSON object.`);
@@ -7753,7 +8681,7 @@ function validateStep(value, scenarioPath, index) {
7753
8681
  const waitTicks = positiveInteger2(value.waitTicks);
7754
8682
  const kind = value.kind === "aimAt" ? "aimAt" : value.kind === "click" ? "click" : value.kind === "lifecycle" ? "lifecycle" : value.kind === "wait" ? "wait" : value.kind === "input" ? "input" : void 0;
7755
8683
  if (value.kind !== void 0 && kind === void 0) {
7756
- throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'input', 'lifecycle', or 'wait'.`);
8684
+ throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'explore', 'input', 'lifecycle', or 'wait'.`);
7757
8685
  }
7758
8686
  const at = validateClickTarget(value.at, scenarioPath, index);
7759
8687
  const target = validateAimTarget(value.target, scenarioPath, index);
@@ -8081,6 +9009,14 @@ function validateStepLabels(steps, assertions, scenarioPath) {
8081
9009
  for (const [index, assertion] of (assertions.tone ?? []).entries()) {
8082
9010
  requireLabel(assertion.atStep, `assert.tone[${index}].atStep`);
8083
9011
  }
9012
+ for (const [index, assertion] of (assertions.animation ?? []).entries()) {
9013
+ requireLabel(assertion.atStep, `assert.animation[${index}].atStep`);
9014
+ }
9015
+ for (const [index, assertion] of (assertions.footSlip ?? []).entries()) {
9016
+ requireLabel(assertion.atStep, `assert.footSlip[${index}].atStep`);
9017
+ if (assertions.footSlip.findIndex(({ atStep }) => atStep === assertion.atStep) !== index)
9018
+ throw invalidScenario(scenarioPath, `Assertion 'assert.footSlip[${index}]' repeats atStep '${assertion.atStep}'; list every foot in one assertion.`);
9019
+ }
8084
9020
  for (const [index, assertion] of (assertions.signals ?? []).entries()) {
8085
9021
  requireLabel(assertion.atStep, `assert.signals[${index}].atStep`);
8086
9022
  }
@@ -8121,6 +9057,9 @@ function validateAssertions(value, scenarioPath) {
8121
9057
  if (Array.isArray(value.signals) && value.signals.length === 0) {
8122
9058
  throw invalidScenario(scenarioPath, "Assertion 'assert.signals' must contain at least one signal assertion.");
8123
9059
  }
9060
+ if (Array.isArray(value.footSlip) && value.footSlip.length === 0) {
9061
+ throw invalidScenario(scenarioPath, "Assertion 'assert.footSlip' must contain at least one foot-slip assertion.");
9062
+ }
8124
9063
  if (Array.isArray(value.tone) && value.tone.length === 0) {
8125
9064
  throw invalidScenario(scenarioPath, "Assertion 'assert.tone' must contain at least one tone assertion.");
8126
9065
  }
@@ -8204,6 +9143,12 @@ function validateAssertions(value, scenarioPath) {
8204
9143
  ...hasKey(value, "causedBy") ? {
8205
9144
  causedBy: requireArray(value, "causedBy", scenarioPath, "assert.causedBy").map((entry, index) => validateCausedByAssertion(entry, scenarioPath, `assert.causedBy[${index}]`))
8206
9145
  } : {},
9146
+ ...hasKey(value, "footSlip") ? {
9147
+ footSlip: requireArray(value, "footSlip", scenarioPath, "assert.footSlip").map((entry, index) => validateFootSlipAssertion(entry, scenarioPath, `assert.footSlip[${index}]`))
9148
+ } : {},
9149
+ ...hasKey(value, "sightLine") ? { sightLine: validateSightLineAssertion(value.sightLine, scenarioPath, "assert.sightLine") } : {},
9150
+ ...hasKey(value, "hudAudit") ? { hudAudit: validateHudAuditAssertion(value.hudAudit, scenarioPath, "assert.hudAudit") } : {},
9151
+ ...hasKey(value, "engineCost") ? { engineCost: validateEngineCostAssertion(value.engineCost, scenarioPath, "assert.engineCost") } : {},
8207
9152
  ...hasKey(value, "sceneNodes") ? {
8208
9153
  sceneNodes: requireArray(value, "sceneNodes", scenarioPath, "assert.sceneNodes").map((entry, index) => validateSceneNodesAssertion(entry, scenarioPath, `assert.sceneNodes[${index}]`))
8209
9154
  } : {},