@threenative/playtest 0.3.4 → 0.3.5

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
@@ -25,9 +25,11 @@ var PLAYTEST_CAPABILITY_REGISTRY = [
25
25
  capability("runtime.fixedStep", "Advances an application-owned deterministic tick."),
26
26
  capability("runtime.geometry", "Answers one armed per-object geometry capture for the frame it was requested on."),
27
27
  capability("runtime.physics", "Samples bounded application-owned physics observations."),
28
+ capability("runtime.network", "Captures native fetch requests and failures through the host mailbox."),
28
29
  capability("runtime.performance", "Samples bounded per-render frame cost and renderer counts."),
29
30
  capability("runtime.pipelineCensus", "Samples bounded shader and pipeline creation observations."),
30
31
  capability("runtime.renderChain", "Reports the render stages, quality tier, and velocity route actually applied."),
32
+ capability("runtime.renderOnly", "Draws the current world once without advancing the simulation, for a capture while the loop is driven."),
31
33
  capability("runtime.resources", "Reads and writes registered JSON-safe application state."),
32
34
  capability("runtime.startup", "Reports whether first-use startup work has finished and the world is safe to observe."),
33
35
  capability("runtime.state", "Samples application-owned state-machine state."),
@@ -50,8 +52,11 @@ function capability(name, description) {
50
52
  return { description, name, protocolVersion: 1 };
51
53
  }
52
54
 
55
+ // src/tone.ts
56
+ var TONE_METRICS = ["mean", "p1", "p50", "p99", "clipFraction", "blackFraction"];
57
+
53
58
  // src/assertion-report.ts
54
- var NETWORK_BLIND_TARGETS = /* @__PURE__ */ new Set(["android", "desktop", "ios"]);
59
+ var NETWORK_BLIND_TARGETS = /* @__PURE__ */ new Set(["android", "ios"]);
55
60
  var UNOBSERVABLE_NETWORK_REASON = "The run target has no network observer; its network observation is hardwired empty, so the default network policy is waived rather than evaluated against nothing.";
56
61
  function resolveDiagnosticsPolicy(policy, target) {
57
62
  const networkBlind = target !== void 0 && NETWORK_BLIND_TARGETS.has(target);
@@ -267,6 +272,24 @@ function isRecord(value) {
267
272
 
268
273
  // src/assertion-schema.ts
269
274
  var PLAYTEST_ASSERTION_REGISTRY = [
275
+ {
276
+ description: "Bounds display-referred luminance from a captured PNG frame, using a shared 256-bin histogram.",
277
+ example: { tone: [{ atStep: "landed", mean: { min: 60, max: 140 }, p99: { min: 150 } }] },
278
+ fields: [
279
+ { description: "Capture after this named step; omit for the final frame.", name: "atStep", type: "non-empty string" },
280
+ { description: "Exact decoded PNG physical-pixel rectangle; non-negative safe-integer x/y, positive safe-integer width/height. No clipping or scaling.", name: "region", type: "{ x: number, y: number, width: number, height: number }" },
281
+ { description: "Same-capture primary minus reference region metric must reach minDelta; requires primary region.", name: "compare", type: "{ region: object, metric: string, minDelta: number }" },
282
+ ...TONE_METRICS.map((name) => ({ description: "Inclusive finite bounds; luminance is 0..255 and fractions are 0..1. At least one bound is required.", name, type: "{ min?: number, max?: number }" }))
283
+ ],
284
+ cardinality: "array",
285
+ kind: "tone",
286
+ observationPath: "tone",
287
+ requiredCapabilities: ["browser.screenshot"],
288
+ resultIdPrefix: "tone.",
289
+ supportedOn: ["web", "desktop", "bevy"],
290
+ triviality: "not-applicable",
291
+ trivialityRationale: "The host decodes actual captured pixels; a missing capture fails closed."
292
+ },
270
293
  {
271
294
  description: "Reports the device's thermal, power and battery state around the run and judges whether the run is comparable with a cool one.",
272
295
  example: { deviceMetrics: { maxTemperatureRiseC: 5, notThermallyConfounded: true } },
@@ -570,7 +593,7 @@ var PLAYTEST_ASSERTION_REGISTRY = [
570
593
  observationPath: "runtimeDiagnostics",
571
594
  requiredCapabilities: ["browser.console", "browser.network", "runtime.diagnostics"],
572
595
  resultIdPrefix: "diagnostics",
573
- supportedOn: ["web"],
596
+ supportedOn: ["web", "desktop"],
574
597
  triviality: "not-applicable",
575
598
  trivialityRationale: "It evaluates captured error and readiness channels across the run; no initial scalar value can satisfy those diagnostics by itself."
576
599
  },
@@ -833,6 +856,25 @@ var PLAYTEST_ASSERTION_REGISTRY = [
833
856
  triviality: "not-applicable",
834
857
  trivialityRationale: "The timeline is stamped by the runtime as milestones happen; a missing milestone fails the ceiling rather than passing it."
835
858
  },
859
+ {
860
+ description: "Bounds node-builder state builds and render-pipeline creations after a complete runtime capture proves that explicit shader warm-up settled; a named streamed scope must also prove its target-bound first visible world frame, and missing, incomplete, or malformed census evidence fails closed.",
861
+ example: { pipelineCensus: { maxNodeBuildsAfterWarmUpSettled: 0, maxRenderPipelineCreationsAfterWarmUpSettled: 0 } },
862
+ fields: [
863
+ { description: "Ceiling on distinct node-builder states first observed after warm-up settled.", name: "maxNodeBuildsAfterWarmUpSettled", type: "non-negative integer" },
864
+ { description: "Ceiling on render-pipeline creations observed after warm-up settled.", name: "maxRenderPipelineCreationsAfterWarmUpSettled", type: "non-negative integer" },
865
+ { description: "Label of a repeatable streamed warm-up scope.", name: "warmUpScope", type: "string" },
866
+ { description: "Ceiling on node-builder state builds after the named warm-up scope.", name: "maxNodeBuildsAfterWarmUpScope", type: "non-negative integer" },
867
+ { description: "Ceiling on render-pipeline creations after the named warm-up scope.", name: "maxRenderPipelineCreationsAfterWarmUpScope", type: "non-negative integer" }
868
+ ],
869
+ cardinality: "object",
870
+ kind: "pipelineCensus",
871
+ observationPath: "pipelineCensus",
872
+ requiredCapabilities: ["runtime.pipelineCensus"],
873
+ resultIdPrefix: "pipelineCensus.",
874
+ supportedOn: ["web", "desktop", "bevy"],
875
+ triviality: "not-applicable",
876
+ trivialityRationale: "The runtime stamps a separate warm-up boundary and counts later observations; an initial scene value cannot satisfy a post-boundary ceiling."
877
+ },
836
878
  {
837
879
  description: "Proves the render chain reports its quality tier, authored stage ids/order, graph-output changes for named stages, and, when asserted, a bounded temporal-history rejection fraction.",
838
880
  example: { renderChain: { tier: "high", stages: { includes: ["outline", "kuwahara", "watercolor"], order: ["outline", "kuwahara", "watercolor"] }, contributions: { graphOutputChanged: ["outline", "kuwahara", "watercolor"] } } },
@@ -841,7 +883,7 @@ var PLAYTEST_ASSERTION_REGISTRY = [
841
883
  { description: "Stage ids to include, exclude, or find as an ordered subsequence in the applied chain.", name: "stages", type: "object" },
842
884
  { description: "Applied stage ids whose build returned a different graph node than its input; this is graph evidence, not pixel attribution.", name: "contributions", type: "object" },
843
885
  { description: "Temporal history rejection ceiling as a fraction from 0 to 1.", name: "velocity", type: "object" },
844
- { description: "What the chain must be on each adapter class the harness classified from its own adapter.info reading; an unclassifiable adapter fails rather than matching either branch.", name: "perAdapter", type: "object" }
886
+ { description: "What the chain must be on each adapter class (hardware, software) and each GPU family (discrete, integrated, mobile-high, mobile-mid, mobile-low) the harness classified from its own adapter.info reading; a family row overrides hardware only when the observed fields prove the family, and an unclassifiable adapter fails rather than matching any branch.", name: "perAdapter", type: "object" }
845
887
  ],
846
888
  cardinality: "object",
847
889
  kind: "renderChain",
@@ -882,6 +924,7 @@ var PLAYTEST_SETUP_REGISTRY = [
882
924
  ];
883
925
  function requiredPlaytestCapabilities(scenario, target) {
884
926
  const required = /* @__PURE__ */ new Set();
927
+ if (scenario.startTick !== void 0) required.add("runtime.fixedStep");
885
928
  if (scenario.steps.some((step) => step.waitForResource !== void 0)) {
886
929
  required.add("runtime.resources");
887
930
  }
@@ -902,13 +945,14 @@ function requiredPlaytestCapabilities(scenario, target) {
902
945
  if (entry.kind === "diagnostics") {
903
946
  const policy = resolveDiagnosticsPolicy(scenario.assert.diagnostics, target);
904
947
  if (policy.noConsoleErrors) required.add("browser.console");
905
- if (policy.noNetworkErrors) required.add("browser.network");
948
+ if (policy.noNetworkErrors) required.add(target === "desktop" ? "runtime.network" : "browser.network");
906
949
  if (policy.noRuntimeDiagnostics) required.add("runtime.diagnostics");
907
950
  } else {
908
951
  entry.requiredCapabilities.forEach((capability2) => required.add(capability2));
909
952
  }
910
953
  }
911
954
  }
955
+ if (target === "desktop" && resolveDiagnosticsPolicy(scenario.assert?.diagnostics, target).noNetworkErrors) required.add("runtime.network");
912
956
  for (const entry of PLAYTEST_SETUP_REGISTRY) {
913
957
  if (scenario.setup?.[entry.kind] !== void 0) {
914
958
  entry.requiredCapabilities.forEach((capability2) => required.add(capability2));
@@ -917,6 +961,87 @@ function requiredPlaytestCapabilities(scenario, target) {
917
961
  return [...required].sort();
918
962
  }
919
963
 
964
+ // src/evaluators/tone.ts
965
+ function emitTone({
966
+ assertions,
967
+ diagnostics,
968
+ input,
969
+ scenarioAssertions
970
+ }) {
971
+ for (const [index, expected] of (scenarioAssertions.tone ?? []).entries()) {
972
+ const label = expected.atStep ?? "after.png";
973
+ const frames = input.report.observations?.tone;
974
+ const frame = Array.isArray(frames) ? frames.slice().reverse().find((entry) => {
975
+ if (entry === null || typeof entry !== "object") return false;
976
+ const regional2 = entry;
977
+ const identity = expected.region === void 0 ? regional2.assertionIndex === void 0 && regional2.region === void 0 : regional2.assertionIndex === index && sameRegion(regional2.region, expected.region);
978
+ return identity && (expected.atStep === void 0 ? entry.atStep === void 0 && entry.label === "after.png" : entry.atStep === expected.atStep);
979
+ }) : void 0;
980
+ const regional = frame;
981
+ if (frame?.code !== "TN_TONE" || regional?.error !== void 0 || !validMetrics(frame) || expected.compare !== void 0 && (regional?.reference?.error !== void 0 || !sameRegion(regional?.reference?.region, expected.compare.region) || !validMetrics(regional?.reference?.metrics))) {
982
+ assertions.push({
983
+ id: `tone.${index}.observed`,
984
+ pass: false,
985
+ details: { expected, observed: frame }
986
+ });
987
+ diagnostics.push({
988
+ code: "TN_PLAYTEST_TONE_UNOBSERVED",
989
+ message: `Tone capture '${label}' is missing or has invalid luminance metrics.`,
990
+ severity: "error",
991
+ observedRuntimePath: "observations.json/tone"
992
+ });
993
+ continue;
994
+ }
995
+ if (expected.compare !== void 0) {
996
+ const { metric, minDelta } = expected.compare;
997
+ const observed = frame[metric] - regional.reference.metrics[metric];
998
+ const pass = observed >= minDelta;
999
+ assertions.push({
1000
+ id: `tone.${index}.compare`,
1001
+ pass,
1002
+ details: { observed, expected: expected.compare, frame }
1003
+ });
1004
+ if (!pass)
1005
+ diagnostics.push({
1006
+ code: "TN_PLAYTEST_TONE_ASSERTION_FAILED",
1007
+ message: `Tone '${label}' ${metric} primary minus reference measured ${observed}; required >= ${minDelta}.`,
1008
+ severity: "error",
1009
+ observedRuntimePath: "observations.json/tone"
1010
+ });
1011
+ }
1012
+ for (const key of TONE_METRICS) {
1013
+ const bound = expected[key];
1014
+ if (bound === void 0) continue;
1015
+ const observed = frame[key];
1016
+ const pass = (bound.min === void 0 || observed >= bound.min) && (bound.max === void 0 || observed <= bound.max);
1017
+ assertions.push({
1018
+ id: `tone.${index}.${key}`,
1019
+ pass,
1020
+ details: { observed, expected: bound, frame }
1021
+ });
1022
+ if (!pass)
1023
+ diagnostics.push({
1024
+ code: "TN_PLAYTEST_TONE_ASSERTION_FAILED",
1025
+ message: `Tone '${label}' ${key} measured ${observed}; required ${JSON.stringify(bound)}.`,
1026
+ severity: "error",
1027
+ observedRuntimePath: "observations.json/tone"
1028
+ });
1029
+ }
1030
+ }
1031
+ }
1032
+ function sameRegion(value, expected) {
1033
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1034
+ const observed = value;
1035
+ return observed.x === expected.x && observed.y === expected.y && observed.width === expected.width && observed.height === expected.height;
1036
+ }
1037
+ function validMetrics(value) {
1038
+ if (typeof value !== "object" || value === null) return false;
1039
+ const metrics = value;
1040
+ return TONE_METRICS.every(
1041
+ (key) => typeof metrics[key] === "number" && Number.isFinite(metrics[key]) && metrics[key] >= 0 && metrics[key] <= (key.endsWith("Fraction") ? 1 : 255)
1042
+ );
1043
+ }
1044
+
920
1045
  // src/evaluators/device-metrics.ts
921
1046
  function emitDeviceMetrics(ctx) {
922
1047
  const assertion = ctx.scenarioAssertions.deviceMetrics;
@@ -1311,6 +1436,14 @@ function evaluateDiagnosticsPolicy(report, policy) {
1311
1436
  suggestion: "Inspect runtime diagnostics and bundle validation output before replaying the scenario."
1312
1437
  });
1313
1438
  }
1439
+ if (report.observations?.console.some(({ text }) => /^\s*\[Playtest\] TN_V8_FRAME_FAILED:/u.test(text))) {
1440
+ diagnostics.push({
1441
+ code: "TN_PLAYTEST_NATIVE_FRAME_FAILED",
1442
+ message: "The native frame callback threw. A failed frame cannot pass a playtest.",
1443
+ severity: "error",
1444
+ suggestion: "Inspect console.json and fix the first TN_V8_FRAME_FAILED error."
1445
+ });
1446
+ }
1314
1447
  const capturedConsoleErrors = consoleErrors(report.observations?.console ?? []);
1315
1448
  if (policy.noConsoleErrors && capturedConsoleErrors.length > 0) {
1316
1449
  diagnostics.push({
@@ -1359,6 +1492,14 @@ function projectedOffscreenRatio(min, max) {
1359
1492
  const visibleHeight = Math.max(0, Math.min(max[1], 1) - Math.max(min[1], -1));
1360
1493
  return 1 - Math.max(0, visibleWidth * visibleHeight) / area;
1361
1494
  }
1495
+ function projectedPixelsFromNdcBounds(min, max, viewport) {
1496
+ const clamp = (value) => Math.min(1, Math.max(-1, value));
1497
+ const x0 = clamp(min[0]);
1498
+ const x1 = clamp(max[0]);
1499
+ const y0 = clamp(min[1]);
1500
+ const y1 = clamp(max[1]);
1501
+ return Math.max(0, (x1 - x0) / 2 * viewport.width) * Math.max(0, (y1 - y0) / 2 * viewport.height);
1502
+ }
1362
1503
  function hasNativeReadinessSamples(runtimeDiagnosticsValue) {
1363
1504
  return isRecord(runtimeDiagnosticsValue) && Array.isArray(runtimeDiagnosticsValue.readiness);
1364
1505
  }
@@ -1375,7 +1516,7 @@ function evaluateVisibilityAssertion(assertion, entity, viewport, runtimeDiagnos
1375
1516
  const initialBounds = isRecord(initialRendered?.projectedBounds) ? initialRendered.projectedBounds : void 0;
1376
1517
  const initialMin = Array.isArray(initialBounds?.min) ? initialBounds.min : void 0;
1377
1518
  const initialMax = Array.isArray(initialBounds?.max) ? initialBounds.max : void 0;
1378
- const initialProjectedPixels = initialMin === void 0 || initialMax === void 0 ? void 0 : Math.max(0, (Number(initialMax[0]) - Number(initialMin[0])) / 2 * viewport.width) * Math.max(0, (Number(initialMax[1]) - Number(initialMin[1])) / 2 * viewport.height);
1519
+ const initialProjectedPixels = initialMin === void 0 || initialMax === void 0 ? void 0 : projectedPixelsFromNdcBounds([Number(initialMin[0]), Number(initialMin[1])], [Number(initialMax[0]), Number(initialMax[1])], viewport);
1379
1520
  const initialOffscreenRatio = initialMin === void 0 || initialMax === void 0 ? void 0 : projectedOffscreenRatio([Number(initialMin[0]), Number(initialMin[1])], [Number(initialMax[0]), Number(initialMax[1])]);
1380
1521
  const initialPass = present2 !== void 0 && minProjectedPixels === void 0 && maxOffscreenRatio === void 0 ? initialObserved === present2 : initialRendered !== void 0 && (present2 === void 0 || present2) && (minProjectedPixels === void 0 || (initialProjectedPixels ?? 0) >= minProjectedPixels) && (maxOffscreenRatio === void 0 || (initialOffscreenRatio ?? 1) <= maxOffscreenRatio);
1381
1522
  const guarded = (comparisonPass, details, failure) => {
@@ -1423,7 +1564,7 @@ function evaluateVisibilityAssertion(assertion, entity, viewport, runtimeDiagnos
1423
1564
  const bounds = isRecord(rendered?.projectedBounds) ? rendered.projectedBounds : void 0;
1424
1565
  const min = Array.isArray(bounds?.min) ? bounds.min : void 0;
1425
1566
  const max = Array.isArray(bounds?.max) ? bounds.max : void 0;
1426
- const projectedPixels = min === void 0 || max === void 0 ? void 0 : Math.max(0, (Number(max[0]) - Number(min[0])) / 2 * viewport.width) * Math.max(0, (Number(max[1]) - Number(min[1])) / 2 * viewport.height);
1567
+ const projectedPixels = min === void 0 || max === void 0 ? void 0 : projectedPixelsFromNdcBounds([Number(min[0]), Number(min[1])], [Number(max[0]), Number(max[1])], viewport);
1427
1568
  const offscreenRatio = min === void 0 || max === void 0 ? void 0 : projectedOffscreenRatio([Number(min[0]), Number(min[1])], [Number(max[0]), Number(max[1])]);
1428
1569
  const pass = rendered !== void 0 && bounds !== void 0 && (present2 === void 0 || present2) && (minProjectedPixels === void 0 || (projectedPixels ?? 0) >= minProjectedPixels) && (maxOffscreenRatio === void 0 || (offscreenRatio ?? 1) <= maxOffscreenRatio);
1429
1570
  return guarded(pass, { entity, maxOffscreenRatio, minProjectedPixels, offscreenRatio, present: present2, projectedPixels }, {
@@ -1576,7 +1717,7 @@ function evaluateAudioAssertion(assertion, observations) {
1576
1717
  const minimum = assertion.minPlays ?? 1;
1577
1718
  const recent = Array.isArray(audio?.recentCues) ? audio.recentCues : [];
1578
1719
  const gap = smallestGapBefore(recent, assertion.cue);
1579
- const gapPass = assertion.minGapMs === void 0 || gap === void 0 || gap >= assertion.minGapMs;
1720
+ const gapPass = assertion.minGapMs === void 0 || Array.isArray(audio?.recentCues) && gap !== void 0 && gap >= assertion.minGapMs;
1580
1721
  const pass = cues !== void 0 && plays >= minimum && (assertion.maxPlays === void 0 || plays <= assertion.maxPlays) && gapPass;
1581
1722
  const result = {
1582
1723
  details: {
@@ -1594,7 +1735,7 @@ function evaluateAudioAssertion(assertion, observations) {
1594
1735
  assertion: result,
1595
1736
  diagnostic: {
1596
1737
  code: "TN_PLAYTEST_AUDIO_ASSERTION_FAILED",
1597
- message: cues === void 0 ? `No runtime audio ledger was published, so cue '${assertion.cue}' cannot be proved either way.` : gapPass ? `Cue '${assertion.cue}' played ${plays} time(s); expected at least ${minimum}${assertion.maxPlays === void 0 ? "" : ` and at most ${assertion.maxPlays}`}.` : `Cue '${assertion.cue}' started ${gap ?? 0} ms after the line before it, which is under the ${String(assertion.minGapMs)} ms it needs; one of them was cut off.`,
1738
+ message: cues === void 0 ? `No runtime audio ledger was published, so cue '${assertion.cue}' cannot be proved either way.` : gapPass ? `Cue '${assertion.cue}' played ${plays} time(s); expected at least ${minimum}${assertion.maxPlays === void 0 ? "" : ` and at most ${assertion.maxPlays}`}.` : assertion.minGapMs !== void 0 && !Array.isArray(audio?.recentCues) ? `Cue '${assertion.cue}' asserts a minimum gap, but no recentCues ledger was published, so the gap between plays was never measured.` : `Cue '${assertion.cue}' started ${gap ?? 0} ms after the line before it, which is under the ${String(assertion.minGapMs)} ms it needs; one of them was cut off.`,
1598
1739
  observedRuntimePath: "observations.json/runtimeObservations/gameplay/audio/cues",
1599
1740
  severity: "error",
1600
1741
  suggestion: cues === void 0 ? "Run on a target whose bridge advertises runtime.audio, and pass `cue` to AudioBus.play/playAt for the lines under test." : "Read observations.json/runtimeObservations/gameplay/audio/recentCues for when each play happened, and check the one-shot flag that gates the cue."
@@ -1819,7 +1960,7 @@ function projectedPixelsForEntity(snapshot, entity, viewport) {
1819
1960
  const bounds = isRecord(rendered?.projectedBounds) ? rendered.projectedBounds : void 0;
1820
1961
  const min = Array.isArray(bounds?.min) ? bounds.min : void 0;
1821
1962
  const max = Array.isArray(bounds?.max) ? bounds.max : void 0;
1822
- return min === void 0 || max === void 0 ? void 0 : Math.max(0, (Number(max[0]) - Number(min[0])) / 2 * viewport.width) * Math.max(0, (Number(max[1]) - Number(min[1])) / 2 * viewport.height);
1963
+ return min === void 0 || max === void 0 ? void 0 : projectedPixelsFromNdcBounds([Number(min[0]), Number(min[1])], [Number(max[0]), Number(max[1])], viewport);
1823
1964
  }
1824
1965
  function countMatchingEntries(effectLog, tokens) {
1825
1966
  if (tokens.length === 0 || !isRecord(effectLog) || !Array.isArray(effectLog.entries)) {
@@ -1838,7 +1979,6 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
1838
1979
  const drawCalls = observed.flatMap(({ drawCalls: value }) => value === void 0 ? [] : [value]);
1839
1980
  const triangles = observed.flatMap(({ triangles: value }) => value === void 0 ? [] : [value]);
1840
1981
  const frameMsP95 = nearestRank(frameTimes, 0.95);
1841
- const frameMsP50 = nearestRank(frameTimes, 0.5);
1842
1982
  const maxObservedDrawCalls = drawCalls.length === 0 ? void 0 : Math.max(...drawCalls);
1843
1983
  const maxObservedTriangles = triangles.length === 0 ? void 0 : Math.max(...triangles);
1844
1984
  const results = [];
@@ -1890,8 +2030,9 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
1890
2030
  );
1891
2031
  }
1892
2032
  if (assertion.minFps !== void 0) {
1893
- const observed2 = frameMsP50 === void 0 || frameMsP50 <= 0 ? void 0 : Math.round(1e3 / frameMsP50 * 100) / 100;
1894
- const pass = samplesPass && observed2 !== void 0 && observed2 >= assertion.minFps;
2033
+ const exact = fpsFromFrameTimes(frameTimes);
2034
+ const observed2 = exact === void 0 ? void 0 : Math.floor(exact * 100) / 100;
2035
+ const pass = samplesPass && exact !== void 0 && exact >= assertion.minFps;
1895
2036
  results.push({
1896
2037
  details: { actual: observed2 ?? null, expected: assertion.minFps, sampleCount: samples.length, unit: "fps" },
1897
2038
  id: "performance.minFps",
@@ -1987,6 +2128,10 @@ function nearestRank(values, percentile) {
1987
2128
  const sorted = [...values].sort((left, right) => left - right);
1988
2129
  return sorted[Math.max(0, Math.ceil(values.length * percentile) - 1)];
1989
2130
  }
2131
+ function fpsFromFrameTimes(frameTimes) {
2132
+ const frameMs = nearestRank(frameTimes, 0.5);
2133
+ return frameMs === void 0 || frameMs <= 0 ? void 0 : 1e3 / frameMs;
2134
+ }
1990
2135
  function mergeEffectLogs(effectLog, series) {
1991
2136
  return {
1992
2137
  entries: [effectLog, ...(series ?? []).map((sample) => sample.snapshot)].flatMap((log) => isRecord(log) && Array.isArray(log.entries) ? log.entries : [])
@@ -2355,14 +2500,15 @@ function emitMovementEvidence(ctx) {
2355
2500
  }
2356
2501
  if (scenarioAssertions.movement?.minVelocity !== void 0) {
2357
2502
  const velocity = input.report.frames <= 0 ? 0 : input.report.distance / input.report.frames;
2358
- const pass = velocity >= scenarioAssertions.movement.minVelocity;
2359
- assertions.push({ details: { minVelocity: scenarioAssertions.movement.minVelocity, velocity }, id: "movement.velocity", pass });
2503
+ const observed = input.report.before !== void 0 && input.report.after !== void 0;
2504
+ const pass = observed && velocity >= scenarioAssertions.movement.minVelocity;
2505
+ assertions.push({ details: { minVelocity: scenarioAssertions.movement.minVelocity, observed, velocity }, id: "movement.velocity", pass });
2360
2506
  if (!pass) {
2361
2507
  diagnostics.push({
2362
2508
  code: "TN_PLAYTEST_VELOCITY_ASSERTION_FAILED",
2363
- message: `Entity '${input.report.entity}' velocity ${velocity.toFixed(6)} was below required ${scenarioAssertions.movement.minVelocity}.`,
2509
+ message: observed ? `Entity '${input.report.entity}' velocity ${velocity.toFixed(6)} was below required ${scenarioAssertions.movement.minVelocity}.` : `Entity '${input.report.entity}' was not observed in both samples, so its velocity was never measured.`,
2364
2510
  severity: "error",
2365
- suggestion: "Check input force/speed tuning and whether the scenario holds input long enough."
2511
+ suggestion: observed ? "Check input force/speed tuning and whether the scenario holds input long enough." : "The entity is absent from the first or last sample; it cannot carry a velocity bound."
2366
2512
  });
2367
2513
  }
2368
2514
  }
@@ -2404,14 +2550,15 @@ function emitMovementEvidence(ctx) {
2404
2550
  }
2405
2551
  if (scenarioAssertions.movement?.pathLength !== void 0) {
2406
2552
  const pathLength = input.report.pathLength ?? input.report.distance;
2407
- const pass = pathLength >= scenarioAssertions.movement.pathLength;
2408
- assertions.push({ details: { minimum: scenarioAssertions.movement.pathLength, pathLength }, id: "movement.pathLength", pass });
2553
+ const observed = input.report.before !== void 0 && input.report.after !== void 0;
2554
+ const pass = observed && pathLength >= scenarioAssertions.movement.pathLength;
2555
+ assertions.push({ details: { minimum: scenarioAssertions.movement.pathLength, observed, pathLength }, id: "movement.pathLength", pass });
2409
2556
  if (!pass) {
2410
2557
  diagnostics.push({
2411
2558
  code: "TN_PLAYTEST_PATH_LENGTH_ASSERTION_FAILED",
2412
- message: `Entity '${input.report.entity}' accumulated path length ${pathLength.toFixed(6)}, below required ${scenarioAssertions.movement.pathLength}.`,
2559
+ message: observed ? `Entity '${input.report.entity}' accumulated path length ${pathLength.toFixed(6)}, below required ${scenarioAssertions.movement.pathLength}.` : `Entity '${input.report.entity}' was never observed, so its path length could not be bounded.`,
2413
2560
  severity: "error",
2414
- suggestion: "Use pathLength with minDistance to distinguish actual traversal from a route that returns to its starting point."
2561
+ suggestion: observed ? "Use pathLength with minDistance to distinguish actual traversal from a route that returns to its starting point." : "Register the entity with the playtest bridge under the id the assertion names."
2415
2562
  });
2416
2563
  }
2417
2564
  }
@@ -2991,8 +3138,7 @@ function emitParity(ctx) {
2991
3138
  });
2992
3139
  return;
2993
3140
  }
2994
- const median = (values) => [...values].sort((left, right) => left - right)[Math.floor(values.length / 2)];
2995
- const thisFps = 1e3 / median(frameTimes);
3141
+ const thisFps = fpsFromFrameTimes(frameTimes);
2996
3142
  const ratio = assertion.referenceSide === "native" ? reference.fps / thisFps : thisFps / reference.fps;
2997
3143
  assertions.push({
2998
3144
  details: { referenceFps: reference.fps, referenceSide: assertion.referenceSide, ratio, unit: "ratio" },
@@ -3282,11 +3428,10 @@ function emitWorldGameplay(ctx) {
3282
3428
  ];
3283
3429
  const checks = [
3284
3430
  ...valueChecks,
3285
- // Same absent-value trap as evaluatePathAssertion: a component that was
3286
- // never observed must not satisfy "this value did not change".
3287
- ...assertion.changed === void 0 ? [] : [(before !== void 0 || after !== void 0) && (assertion.changed ? !jsonEqual(before, after) : jsonEqual(before, after))]
3431
+ // A temporal comparison needs both observations; appearance or disappearance is not a measured change.
3432
+ ...assertion.changed === void 0 ? [] : [before !== void 0 && after !== void 0 && (assertion.changed ? !jsonEqual(before, after) : jsonEqual(before, after))]
3288
3433
  ];
3289
- const trivial = rejectsTrivialAssertion("components") && valueChecks.length > 0 && before !== void 0 && componentValueChecks(assertion, before).every(Boolean);
3434
+ const trivial = rejectsTrivialAssertion("components") && assertion.changed === void 0 && valueChecks.length > 0 && before !== void 0 && componentValueChecks(assertion, before).every(Boolean);
3290
3435
  const pass = checks.length > 0 && checks.every(Boolean) && (!trivial || typeof assertion.allowTrivial === "string");
3291
3436
  assertions.push({
3292
3437
  details: {
@@ -3786,6 +3931,17 @@ function emitWorldTopology(value, assertions, diagnostics) {
3786
3931
  }
3787
3932
 
3788
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
+ ];
3789
3945
  var SOFTWARE_ADAPTER = /swiftshader|llvmpipe|lavapipe|softwarerasterizer|software adapter|basic render/i;
3790
3946
  function softwareAdapterName(adapter) {
3791
3947
  if (adapter === void 0) return void 0;
@@ -3801,7 +3957,9 @@ function classifyAdapter(report) {
3801
3957
  if (capture === void 0 || capture.rendererKind !== "webgpu") return {};
3802
3958
  if (adapterIdentity(capture.adapter) === void 0) return {};
3803
3959
  const software = softwareAdapterName(capture.adapter);
3804
- return software === void 0 ? { adapterClass: "hardware" } : { adapterClass: "software", softwareAdapter: software };
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 };
3805
3963
  }
3806
3964
  var ADAPTER_IDENTITY_KEYS = ["architecture", "description", "device", "vendor"];
3807
3965
  function adapterIdentity(adapter) {
@@ -3812,6 +3970,59 @@ function adapterIdentity(adapter) {
3812
3970
  }
3813
3971
  return void 0;
3814
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
+ }
3815
4026
 
3816
4027
  // src/evaluators/render-chain.ts
3817
4028
  function emitRenderChain(ctx) {
@@ -3944,8 +4155,8 @@ function selectExpectation(ctx, assertion) {
3944
4155
  ...assertion.velocity === void 0 ? {} : { velocity: assertion.velocity }
3945
4156
  };
3946
4157
  const provenance = classifyAdapter(ctx.input.report);
3947
- const { adapterClass } = provenance;
3948
- const branch = adapterClass === void 0 ? void 0 : assertion.perAdapter?.[adapterClass];
4158
+ const { adapterClass, gpuFamily } = provenance;
4159
+ const branch = adapterClass === void 0 ? void 0 : (gpuFamily === void 0 ? void 0 : assertion.perAdapter?.[gpuFamily]) ?? assertion.perAdapter?.[adapterClass];
3949
4160
  return {
3950
4161
  classification: adapterClass,
3951
4162
  expectation: branch ?? flat,
@@ -4175,7 +4386,7 @@ function emitOne2(ctx, assertion, index, observation) {
4175
4386
  observation,
4176
4387
  sampled,
4177
4388
  true,
4178
- (node) => (node.materials ?? []).every((material) => material.mapsUnloaded.length === 0),
4389
+ (node) => (node.materials?.length ?? 0) > 0 && (node.materials ?? []).every((material) => material.mapsUnloaded.length === 0),
4179
4390
  {
4180
4391
  code: "TN_PLAYTEST_SCENE_NODE_TEXTURE_UNLOADED",
4181
4392
  failure: (names, nodes) => {
@@ -4385,12 +4596,1138 @@ function emitStartup(ctx) {
4385
4596
  }
4386
4597
  }
4387
4598
 
4599
+ // src/runner/pipeline-summary.ts
4600
+ var PIPELINE_CAPTURE_VERSION = 1;
4601
+ var PIPELINE_EVENT_MARKER = "TN_PIPELINE_EVENT:";
4602
+ var PIPELINE_CAPTURE_MARKER = "TN_PIPELINE_CAPTURE:";
4603
+ var PIPELINE_FIRST_PRESENT_MARKER = "TN_PIPELINE_FIRST_PRESENT:";
4604
+ var PIPELINE_COMPLETE_MARKER = "TN_PIPELINE_COMPLETE:";
4605
+ var PIPELINE_CHECKPOINT_MARKER = "TN_PIPELINE_CHECKPOINT:";
4606
+ function parsePipelineCapture(input) {
4607
+ if (typeof input === "string") return parseCaptureDocument(input);
4608
+ const root = asRecord(input);
4609
+ if (root === void 0) throw malformed("capture must be an object");
4610
+ if (root.nativeLog !== void 0) {
4611
+ if (root.version !== PIPELINE_CAPTURE_VERSION || typeof root.nativeLog !== "string")
4612
+ throw malformed("paired capture requires version 1 and a nativeLog string");
4613
+ const renderer = parsePipelineCapture(root.census);
4614
+ const native = nativeCapture(parseNativeMarkerCapture(root.nativeLog));
4615
+ return reconcilePipelineCaptures(renderer, native);
4616
+ }
4617
+ const observations = asRecord(root.observations);
4618
+ const nested = firstDefinedRecord(
4619
+ root.pipelineCensus,
4620
+ root.census,
4621
+ observations?.pipelineCensus,
4622
+ root.capture
4623
+ );
4624
+ const value = nested ?? root;
4625
+ if (value.version === void 0) throw malformed("capture is missing its version");
4626
+ if (typeof value.version !== "number" || !Number.isInteger(value.version)) {
4627
+ throw malformed("capture version must be an integer");
4628
+ }
4629
+ if (value.version !== PIPELINE_CAPTURE_VERSION) {
4630
+ return unsupportedCapture(value.version, value);
4631
+ }
4632
+ return parseBrowserCapture(value);
4633
+ }
4634
+ function parseCaptureDocument(text) {
4635
+ let document;
4636
+ try {
4637
+ document = JSON.parse(text);
4638
+ } catch (error) {
4639
+ const native = parseNativeMarkerCapture(text);
4640
+ if (native.events.length === 0)
4641
+ throw malformed(`input is neither JSON nor a native event log (${errorMessage(error)})`);
4642
+ return nativeCapture(native);
4643
+ }
4644
+ return parsePipelineCapture(document);
4645
+ }
4646
+ function reconcilePipelineCaptures(renderer, native) {
4647
+ const byHandle = /* @__PURE__ */ new Map();
4648
+ for (const event of renderer.events) {
4649
+ if (byHandle.has(event.pipelineIdentity)) throw malformed(`duplicate renderer pipeline ${event.pipelineIdentity}`);
4650
+ byHandle.set(event.pipelineIdentity, event);
4651
+ }
4652
+ const events = native.events.map((event) => {
4653
+ const observed = byHandle.get(event.pipelineIdentity);
4654
+ if (observed === void 0) return event;
4655
+ byHandle.delete(event.pipelineIdentity);
4656
+ if (observed.kind !== event.kind || observed.status !== event.status || observed.mode !== event.mode)
4657
+ throw malformed(`pipeline creation mismatch for ${event.pipelineIdentity}`);
4658
+ for (const stage of ["vertex", "fragment", "compute"]) {
4659
+ const expected = observed[stage];
4660
+ const actual = event[stage];
4661
+ if (expected?.hash !== actual?.hash || expected?.bytes !== actual?.bytes)
4662
+ throw malformed(`shader ${stage} mismatch for ${event.pipelineIdentity}`);
4663
+ }
4664
+ return { ...event, pass: observed.pass, provenance: observed.provenance, reasons: observed.reasons };
4665
+ });
4666
+ if (byHandle.size > 0) throw malformed(`unmatched renderer pipeline ${byHandle.keys().next().value}`);
4667
+ const incompleteReasons = [...native.incompleteReasons, ...renderer.incompleteReasons];
4668
+ return {
4669
+ ...native,
4670
+ events,
4671
+ complete: native.complete && renderer.complete,
4672
+ counts: { ...native.counts, lookups: renderer.counts.lookups },
4673
+ overflowed: native.overflowed || renderer.overflowed,
4674
+ incompleteReasons
4675
+ };
4676
+ }
4677
+ function parseNativeMarkerCapture(text) {
4678
+ const state = { events: [], eventsAfterCheckpoint: 0, seen: /* @__PURE__ */ new Map() };
4679
+ for (const line of text.split("\n")) {
4680
+ const marker = parseNativeMarkerLine(line);
4681
+ if (marker === void 0) continue;
4682
+ consumeNativeMarker(state, marker);
4683
+ }
4684
+ if (state.checkpoint !== void 0 && state.expectedEventCount !== void 0 && state.checkpoint.requested > state.expectedEventCount) {
4685
+ throw malformed(
4686
+ `a native pipeline checkpoint requested ${state.checkpoint.requested}, past the completion marker's ${state.expectedEventCount}`
4687
+ );
4688
+ }
4689
+ return {
4690
+ ...state.adapter === void 0 ? {} : { adapter: state.adapter },
4691
+ ...state.build === void 0 ? {} : { build: state.build },
4692
+ ...state.checkpoint === void 0 ? {} : { checkpoint: state.checkpoint },
4693
+ ...state.clock === void 0 ? {} : { clock: state.clock },
4694
+ events: state.events.sort((left, right) => left.sequence - right.sequence),
4695
+ eventsAfterCheckpoint: state.eventsAfterCheckpoint,
4696
+ ...state.expectedEventCount === void 0 ? {} : { expectedEventCount: state.expectedEventCount },
4697
+ ...state.firstPresentBoundaryMs === void 0 ? {} : { firstPresentBoundaryMs: state.firstPresentBoundaryMs }
4698
+ };
4699
+ }
4700
+ function consumeNativeMarker(state, marker) {
4701
+ if (marker.kind === "capture") {
4702
+ consumeNativeCaptureMetadata(state, marker.value);
4703
+ return;
4704
+ }
4705
+ if (marker.kind === "first-present") {
4706
+ consumeNativeFirstPresent(state, marker.value);
4707
+ return;
4708
+ }
4709
+ if (marker.kind === "complete") {
4710
+ consumeNativeCompletion(state, marker.value);
4711
+ return;
4712
+ }
4713
+ if (marker.kind === "checkpoint") {
4714
+ consumeNativeCheckpoint(state, marker.value);
4715
+ return;
4716
+ }
4717
+ consumeNativeEvent(state, marker.value);
4718
+ }
4719
+ function consumeNativeCaptureMetadata(state, value) {
4720
+ validateCaptureVersion(value, "native pipeline capture metadata");
4721
+ const metadata = nativeCaptureMetadata(value);
4722
+ if (state.build !== void 0 || state.adapter !== void 0 || state.clock !== void 0)
4723
+ throw malformed("native pipeline capture metadata appears more than once");
4724
+ state.build = metadata.build;
4725
+ state.adapter = metadata.adapter;
4726
+ state.clock = metadata.clock;
4727
+ }
4728
+ function consumeNativeFirstPresent(state, value) {
4729
+ validateCaptureVersion(value, "native first-present metadata");
4730
+ const metadata = asRecord(value);
4731
+ const boundaryMs = nonNegativeNumber(metadata?.boundaryMs, "native first-present boundaryMs");
4732
+ if (state.firstPresentBoundaryMs !== void 0 && state.firstPresentBoundaryMs !== boundaryMs)
4733
+ throw malformed("native first-present metadata appears with conflicting boundaries");
4734
+ state.firstPresentBoundaryMs = boundaryMs;
4735
+ }
4736
+ function consumeNativeCompletion(state, value) {
4737
+ validateCaptureVersion(value, "native completion metadata");
4738
+ const metadata = asRecord(value);
4739
+ const eventCount = nonNegativeInteger(metadata?.eventCount, "native completion eventCount");
4740
+ if (state.expectedEventCount !== void 0 && state.expectedEventCount !== eventCount)
4741
+ throw malformed("native completion metadata appears with conflicting event counts");
4742
+ state.expectedEventCount = eventCount;
4743
+ }
4744
+ function consumeNativeCheckpoint(state, value) {
4745
+ validateCaptureVersion(value, "native pipeline checkpoint");
4746
+ const metadata = asRecord(value);
4747
+ const checkpoint = {
4748
+ emitted: nonNegativeInteger(metadata?.emitted, "native checkpoint emitted"),
4749
+ outstanding: nonNegativeInteger(metadata?.outstanding, "native checkpoint outstanding"),
4750
+ present: nonNegativeInteger(metadata?.present, "native checkpoint present"),
4751
+ requested: nonNegativeInteger(metadata?.requested, "native checkpoint requested")
4752
+ };
4753
+ if (checkpoint.requested !== checkpoint.emitted + checkpoint.outstanding) {
4754
+ throw malformed(
4755
+ `native pipeline checkpoint counts do not reconcile: ${checkpoint.requested} requested against ${checkpoint.emitted} emitted and ${checkpoint.outstanding} outstanding`
4756
+ );
4757
+ }
4758
+ const previous = state.checkpoint;
4759
+ if (previous !== void 0 && (checkpoint.present < previous.present || checkpoint.requested < previous.requested || checkpoint.emitted < previous.emitted)) {
4760
+ throw malformed("a native pipeline checkpoint reports fewer than the one before it");
4761
+ }
4762
+ if (checkpoint.emitted < state.events.length) {
4763
+ throw malformed(
4764
+ `a native pipeline checkpoint counted ${checkpoint.emitted} event(s) after ${state.events.length} had already been written`
4765
+ );
4766
+ }
4767
+ state.checkpoint = checkpoint;
4768
+ state.eventsAfterCheckpoint = 0;
4769
+ }
4770
+ function consumeNativeEvent(state, value) {
4771
+ validateCaptureVersion(value, "native pipeline event");
4772
+ const event = normaliseNativeEvent(value);
4773
+ const existing = state.seen.get(event.sequence);
4774
+ const serialised = JSON.stringify(value);
4775
+ if (existing !== void 0) {
4776
+ if (existing !== serialised) throw malformed(`event ${event.sequence} appears with conflicting payloads`);
4777
+ return;
4778
+ }
4779
+ state.seen.set(event.sequence, serialised);
4780
+ state.events.push(event);
4781
+ if (state.checkpoint !== void 0) state.eventsAfterCheckpoint += 1;
4782
+ }
4783
+ function parseNativeMarkerLine(line) {
4784
+ const candidates = [
4785
+ { at: line.indexOf(PIPELINE_CAPTURE_MARKER), kind: "capture", marker: PIPELINE_CAPTURE_MARKER },
4786
+ { at: line.indexOf(PIPELINE_CHECKPOINT_MARKER), kind: "checkpoint", marker: PIPELINE_CHECKPOINT_MARKER },
4787
+ { at: line.indexOf(PIPELINE_COMPLETE_MARKER), kind: "complete", marker: PIPELINE_COMPLETE_MARKER },
4788
+ { at: line.indexOf(PIPELINE_FIRST_PRESENT_MARKER), kind: "first-present", marker: PIPELINE_FIRST_PRESENT_MARKER },
4789
+ { at: line.indexOf(PIPELINE_EVENT_MARKER), kind: "event", marker: PIPELINE_EVENT_MARKER }
4790
+ ];
4791
+ const candidate = candidates.filter(({ at }) => at !== -1).sort((left, right) => left.at - right.at)[0];
4792
+ if (candidate === void 0) return void 0;
4793
+ const payload = line.slice(candidate.at + candidate.marker.length).trim();
4794
+ try {
4795
+ return { kind: candidate.kind, value: JSON.parse(payload) };
4796
+ } catch (error) {
4797
+ throw malformed(`a ${candidate.marker.slice(0, -1)} line carries invalid JSON (${payload.slice(0, 100)}): ${errorMessage(error)}`);
4798
+ }
4799
+ }
4800
+ function summarizePipelineCapture(capture) {
4801
+ const passMap = /* @__PURE__ */ new Map();
4802
+ const contributorMap = /* @__PURE__ */ new Map();
4803
+ const programMap = /* @__PURE__ */ new Map();
4804
+ const sizeMap = /* @__PURE__ */ new Map();
4805
+ let beforeFirstPresent = 0;
4806
+ let afterFirstPresent = 0;
4807
+ let afterWarmUpSettled = 0;
4808
+ let renderPipelineCreationsAfterWarmUpSettled = 0;
4809
+ let warmedNodeBuildsAfterWarmUpSettled = 0;
4810
+ let warmedRenderPipelineCreationsAfterWarmUpSettled = 0;
4811
+ const scopeMap = /* @__PURE__ */ new Map();
4812
+ const measuredScopeLabels = /* @__PURE__ */ new Set();
4813
+ for (const scope of capture.warmUpScopes ?? []) {
4814
+ const previous = scopeMap.get(scope.label);
4815
+ if (scope.firstDraw !== void 0) measuredScopeLabels.add(scope.label);
4816
+ scopeMap.set(scope.label, {
4817
+ nodeBuilds: Math.max(previous?.nodeBuilds ?? 0, scope.firstDraw?.nodeBuilds ?? 0),
4818
+ renderPipelineCreations: Math.max(
4819
+ previous?.renderPipelineCreations ?? 0,
4820
+ scope.firstDraw?.renderPipelineCreations ?? 0
4821
+ ),
4822
+ ...scope.firstDraw !== void 0 && (previous === void 0 || previous.observed === true) ? { observed: true } : {}
4823
+ });
4824
+ }
4825
+ let unreported = 0;
4826
+ let sizeSamples = 0;
4827
+ const hasNodeBuildRecords = capture.nodeBuilds !== void 0;
4828
+ const warmedMaterialLabels = capture.warmUpSettled === void 0 ? void 0 : new Set([
4829
+ capture.events.filter(({ beforeWarmUpSettled, provenance }) => beforeWarmUpSettled === true && provenance.material !== void 0).map(contributorLabel),
4830
+ ...(capture.nodeBuilds ?? []).filter(({ beforeWarmUpSettled, provenance }) => beforeWarmUpSettled === true && provenance.material !== void 0).map(({ provenance }) => contributorLabelOfProvenance(provenance))
4831
+ ].flat());
4832
+ for (const event of capture.events) {
4833
+ const serviceMs = event.serviceMs;
4834
+ const previousPass = passMap.get(event.pass);
4835
+ passMap.set(event.pass, {
4836
+ creations: (previousPass?.creations ?? 0) + 1,
4837
+ failures: (previousPass?.failures ?? 0) + (event.status === "failed" ? 1 : 0),
4838
+ beforeFirstPresent: (previousPass?.beforeFirstPresent ?? 0) + (event.beforeFirstPresent === true ? 1 : 0),
4839
+ serviceMs: (previousPass?.serviceMs ?? 0) + (serviceMs ?? 0),
4840
+ serviceSamples: (previousPass?.serviceSamples ?? 0) + (serviceMs === void 0 ? 0 : 1)
4841
+ });
4842
+ const label = contributorLabel(event);
4843
+ const previousContributor = contributorMap.get(label);
4844
+ contributorMap.set(label, {
4845
+ afterWarmUpSettledCreations: (previousContributor?.afterWarmUpSettledCreations ?? 0) + (event.beforeWarmUpSettled === false && event.status === "created" ? 1 : 0),
4846
+ afterWarmUpSettledNodeBuilds: (previousContributor?.afterWarmUpSettledNodeBuilds ?? 0) + (hasNodeBuildRecords || event.beforeWarmUpSettled !== false ? 0 : event.nodeBuilds ?? 0),
4847
+ label,
4848
+ creations: (previousContributor?.creations ?? 0) + 1,
4849
+ failures: (previousContributor?.failures ?? 0) + (event.status === "failed" ? 1 : 0),
4850
+ nodeBuilds: (previousContributor?.nodeBuilds ?? 0) + (hasNodeBuildRecords ? 0 : event.nodeBuilds ?? 0),
4851
+ sampleCount: (previousContributor?.sampleCount ?? 0) + (event.serviceMs === void 0 ? 0 : 1),
4852
+ ...serviceMs === void 0 && previousContributor?.serviceMs === void 0 ? {} : { serviceMs: (previousContributor?.serviceMs ?? 0) + (serviceMs ?? 0) }
4853
+ });
4854
+ const previousProgram = programMap.get(event.programIdentity) ?? { creations: 0, reasons: /* @__PURE__ */ new Set() };
4855
+ previousProgram.creations += 1;
4856
+ for (const reason of event.reasons) previousProgram.reasons.add(reason);
4857
+ programMap.set(event.programIdentity, previousProgram);
4858
+ const bytes = event.kind === "render" ? event.vertex === void 0 || event.fragment === void 0 ? void 0 : event.vertex.bytes + event.fragment.bytes : event.compute?.bytes;
4859
+ if (bytes !== void 0 && event.serviceMs !== void 0) {
4860
+ sizeSamples += 1;
4861
+ const previousSize = sizeMap.get(event.pass) ?? { bytes: 0, serviceMs: 0, samples: 0 };
4862
+ previousSize.bytes += bytes;
4863
+ previousSize.serviceMs += event.serviceMs;
4864
+ previousSize.samples += 1;
4865
+ sizeMap.set(event.pass, previousSize);
4866
+ }
4867
+ if (event.beforeFirstPresent === true) beforeFirstPresent += 1;
4868
+ else if (event.beforeFirstPresent === false) afterFirstPresent += 1;
4869
+ else unreported += 1;
4870
+ if (event.beforeWarmUpSettled === false) {
4871
+ afterWarmUpSettled += 1;
4872
+ if (event.kind === "render" && event.status === "created")
4873
+ renderPipelineCreationsAfterWarmUpSettled += 1;
4874
+ if (warmedMaterialLabels?.has(label) === true) {
4875
+ if (!hasNodeBuildRecords) warmedNodeBuildsAfterWarmUpSettled += event.nodeBuilds ?? 0;
4876
+ if (event.kind === "render" && event.status === "created")
4877
+ warmedRenderPipelineCreationsAfterWarmUpSettled += 1;
4878
+ }
4879
+ }
4880
+ if (event.afterWarmUpScope !== void 0) {
4881
+ const scope = scopeMap.get(event.afterWarmUpScope) ?? {
4882
+ nodeBuilds: 0,
4883
+ renderPipelineCreations: 0
4884
+ };
4885
+ if (!measuredScopeLabels.has(event.afterWarmUpScope)) {
4886
+ if (!hasNodeBuildRecords) scope.nodeBuilds += event.nodeBuilds ?? 0;
4887
+ if (event.kind === "render" && event.status === "created")
4888
+ scope.renderPipelineCreations += 1;
4889
+ }
4890
+ scopeMap.set(event.afterWarmUpScope, scope);
4891
+ }
4892
+ }
4893
+ for (const nodeBuild of capture.nodeBuilds ?? []) {
4894
+ const label = contributorLabelOfProvenance(nodeBuild.provenance);
4895
+ const previousContributor = contributorMap.get(label);
4896
+ contributorMap.set(label, {
4897
+ afterWarmUpSettledCreations: previousContributor?.afterWarmUpSettledCreations ?? 0,
4898
+ afterWarmUpSettledNodeBuilds: (previousContributor?.afterWarmUpSettledNodeBuilds ?? 0) + (nodeBuild.beforeWarmUpSettled === false ? 1 : 0),
4899
+ label,
4900
+ creations: previousContributor?.creations ?? 0,
4901
+ failures: previousContributor?.failures ?? 0,
4902
+ nodeBuilds: (previousContributor?.nodeBuilds ?? 0) + 1,
4903
+ sampleCount: previousContributor?.sampleCount ?? 0,
4904
+ ...previousContributor?.serviceMs === void 0 ? {} : { serviceMs: previousContributor.serviceMs }
4905
+ });
4906
+ if (nodeBuild.beforeWarmUpSettled === false && warmedMaterialLabels?.has(label) === true)
4907
+ warmedNodeBuildsAfterWarmUpSettled += 1;
4908
+ if (nodeBuild.afterWarmUpScope !== void 0) {
4909
+ const scope = scopeMap.get(nodeBuild.afterWarmUpScope) ?? {
4910
+ nodeBuilds: 0,
4911
+ renderPipelineCreations: 0
4912
+ };
4913
+ if (!measuredScopeLabels.has(nodeBuild.afterWarmUpScope)) scope.nodeBuilds += 1;
4914
+ scopeMap.set(nodeBuild.afterWarmUpScope, scope);
4915
+ }
4916
+ }
4917
+ const source = capture.source;
4918
+ const nodeBuildsAfterWarmUpSettled = capture.warmUpSettled === void 0 || capture.counts.nodeBuilds === void 0 ? void 0 : capture.counts.nodeBuilds - capture.warmUpSettled.nodeBuilds;
4919
+ return {
4920
+ adapter: capture.adapter,
4921
+ ...capture.boundary === void 0 ? {} : { boundary: capture.boundary },
4922
+ build: capture.build,
4923
+ complete: capture.complete,
4924
+ counts: capture.counts,
4925
+ contributors: [...contributorMap.values()].sort(compareContributor),
4926
+ incompleteReasons: capture.incompleteReasons,
4927
+ passTotals: [...passMap.entries()].map(([pass, value]) => ({
4928
+ pass,
4929
+ creations: value.creations,
4930
+ failures: value.failures,
4931
+ beforeFirstPresent: value.beforeFirstPresent,
4932
+ serviceSamples: value.serviceSamples,
4933
+ ...value.serviceSamples === 0 ? {} : { serviceMs: value.serviceMs }
4934
+ })).sort((left, right) => (right.serviceMs ?? -1) - (left.serviceMs ?? -1) || left.pass.localeCompare(right.pass)),
4935
+ programReasons: [...programMap.entries()].map(([programIdentity, value]) => ({ programIdentity, creations: value.creations, reasons: [...value.reasons].sort() })).sort((left, right) => right.creations - left.creations || left.programIdentity.localeCompare(right.programIdentity)),
4936
+ sizeTime: {
4937
+ byPass: [...sizeMap.entries()].map(([pass, value]) => ({
4938
+ pass,
4939
+ samples: value.samples,
4940
+ meanBytes: value.bytes / value.samples,
4941
+ meanServiceMs: value.serviceMs / value.samples
4942
+ })).sort((left, right) => right.meanServiceMs - left.meanServiceMs || left.pass.localeCompare(right.pass)),
4943
+ samples: sizeSamples,
4944
+ statement: "Descriptive samples only; shader size and compile time are correlated here, not causal."
4945
+ },
4946
+ source,
4947
+ warmup: {
4948
+ total: capture.events.length,
4949
+ beforeFirstPresent,
4950
+ afterFirstPresent,
4951
+ afterWarmUpSettled,
4952
+ unreported,
4953
+ ...capture.firstPresent === void 0 ? {} : { eventsSettledAtFirstPresent: capture.firstPresent.eventsSettled },
4954
+ ...capture.warmUpSettled === void 0 ? {} : {
4955
+ eventsSettledAtWarmUpSettled: capture.warmUpSettled.eventsSettled,
4956
+ renderPipelineCreationsAfterWarmUpSettled
4957
+ },
4958
+ ...nodeBuildsAfterWarmUpSettled === void 0 ? {} : { nodeBuildsAfterWarmUpSettled },
4959
+ ...warmedMaterialLabels === void 0 || warmedMaterialLabels.size === 0 ? {} : {
4960
+ warmedNodeBuildsAfterWarmUpSettled,
4961
+ warmedRenderPipelineCreationsAfterWarmUpSettled
4962
+ },
4963
+ scopes: [...scopeMap.entries()].map(([label, value]) => ({ label, ...value })).sort((left, right) => left.label.localeCompare(right.label))
4964
+ }
4965
+ };
4966
+ }
4967
+ function parseBrowserCapture(value) {
4968
+ const eventsValue = value.events;
4969
+ if (!Array.isArray(eventsValue)) throw malformed("browser capture is missing an events array");
4970
+ const events = eventsValue.map((event, index) => normaliseBrowserEvent(event, index));
4971
+ const nodeBuilds = parseNodeBuilds(value.nodeBuilds);
4972
+ validateEventSequence(events, "browser capture", true);
4973
+ const declaredCounts = parseCounts(value.counts);
4974
+ const reasons = [];
4975
+ for (const event of events) {
4976
+ if (event.kind === "render" && event.vertex === void 0)
4977
+ reasons.push("a render pipeline is missing its vertex shader observation");
4978
+ if (event.kind === "compute" && event.compute === void 0)
4979
+ reasons.push("a compute pipeline is missing its shader observation");
4980
+ }
4981
+ if (typeof value.complete !== "boolean") throw malformed("browser capture complete must be boolean");
4982
+ if (value.complete !== true) reasons.push("capture declares itself incomplete");
4983
+ if (value.overflowed !== void 0 && typeof value.overflowed !== "boolean")
4984
+ throw malformed("browser capture overflowed must be boolean");
4985
+ if (value.overflowed === true) reasons.push("bounded event buffer overflowed");
4986
+ if (value.unsupported !== void 0 && typeof value.unsupported !== "boolean")
4987
+ throw malformed("browser capture unsupported must be boolean");
4988
+ if (value.unsupported === true) reasons.push("pipeline census is unsupported");
4989
+ const clock = parseClock(value.clock, reasons);
4990
+ const backend = parseBackend(value.backend, reasons);
4991
+ const build = parseBuild(value.build, reasons);
4992
+ const adapter = parseAdapter(value.adapter, reasons);
4993
+ const declaredReasons = stringArray(value.incompleteReasons);
4994
+ reasons.push(...declaredReasons.filter((reason) => !reasons.includes(reason)));
4995
+ const derivedFailures = events.filter(({ status }) => status === "failed").length;
4996
+ const derivedPending = events.filter(({ status }) => status === "pending").length;
4997
+ if (declaredCounts.pending !== derivedPending) reasons.push("pending count does not match event statuses");
4998
+ if (declaredCounts.failures !== derivedFailures) reasons.push("failure count does not match event statuses");
4999
+ if (declaredCounts.pending > 0) reasons.push(`${declaredCounts.pending} pipeline event(s) are pending`);
5000
+ if (declaredCounts.failures > 0) reasons.push(`${declaredCounts.failures} pipeline creation(s) failed`);
5001
+ if (declaredCounts.recordedEvents !== events.length) reasons.push("recorded event count does not match the events array");
5002
+ if (declaredCounts.uniquePrograms !== new Set(events.map(({ programIdentity }) => programIdentity)).size)
5003
+ reasons.push("unique program count does not match the events array");
5004
+ if (declaredCounts.uniquePipelines !== new Set(events.map(({ pipelineIdentity }) => pipelineIdentity)).size)
5005
+ reasons.push("unique pipeline count does not match the events array");
5006
+ if (declaredCounts.creations !== events.length + declaredCounts.droppedEvents)
5007
+ reasons.push("creation count does not reconcile with recorded and dropped events");
5008
+ if (declaredCounts.droppedEvents > 0)
5009
+ reasons.push(`${declaredCounts.droppedEvents} pipeline event(s) were dropped from the bounded capture`);
5010
+ const sequenceGaps = sequenceGapCount(events);
5011
+ if (sequenceGaps > declaredCounts.droppedEvents)
5012
+ reasons.push("event sequence gaps exceed the declared dropped event count");
5013
+ if (events[0]?.sequence !== void 0 && events[0].sequence !== 1)
5014
+ reasons.push(`browser event sequence starts at ${events[0].sequence}, expected 1`);
5015
+ if (declaredCounts.creations === 0) reasons.push("no pipeline creations observed");
5016
+ const firstPresent = parseFirstPresent(value.firstPresent);
5017
+ if (firstPresent === void 0) reasons.push("capture is missing its first-present boundary");
5018
+ if (firstPresent !== void 0) {
5019
+ const settledAtFirstPresent = events.filter(
5020
+ ({ settledMs }) => settledMs !== void 0 && settledMs <= firstPresent.boundaryMs
5021
+ ).length;
5022
+ if (firstPresent.eventsSettled !== settledAtFirstPresent)
5023
+ reasons.push("first-present settled count does not match event timings");
5024
+ for (const event of events) {
5025
+ if (event.beforeFirstPresent === true && event.settledMs !== void 0 && event.settledMs > firstPresent.boundaryMs)
5026
+ reasons.push("an event is marked before first present but settled after its boundary");
5027
+ if (event.beforeFirstPresent === false && event.settledMs !== void 0 && event.settledMs <= firstPresent.boundaryMs)
5028
+ reasons.push("an event is marked after first present but settled before its boundary");
5029
+ }
5030
+ }
5031
+ const warmUpSettled = parseWarmUpSettled(value.warmUpSettled);
5032
+ const warmUpScopes = parseWarmUpScopes(value.warmUpScopes);
5033
+ if (warmUpSettled !== void 0) {
5034
+ const settledAtWarmUp = events.filter(
5035
+ ({ settledMs }) => settledMs !== void 0 && settledMs <= warmUpSettled.boundaryMs
5036
+ ).length;
5037
+ if (warmUpSettled.eventsSettled !== settledAtWarmUp)
5038
+ reasons.push("warm-up settled event count does not match event timings");
5039
+ const renderCreationsAtWarmUp = events.filter(
5040
+ ({ kind, status, settledMs }) => kind === "render" && status === "created" && settledMs !== void 0 && settledMs <= warmUpSettled.boundaryMs
5041
+ ).length;
5042
+ if (warmUpSettled.renderPipelineCreations !== renderCreationsAtWarmUp)
5043
+ reasons.push("warm-up settled render creation count does not match event timings");
5044
+ for (const event of events) {
5045
+ if (event.beforeWarmUpSettled === true && event.settledMs !== void 0 && event.settledMs > warmUpSettled.boundaryMs)
5046
+ reasons.push("an event is marked before warm-up settled but settled after its boundary");
5047
+ if (event.beforeWarmUpSettled === false && event.settledMs !== void 0 && event.settledMs <= warmUpSettled.boundaryMs)
5048
+ reasons.push("an event is marked after warm-up settled but settled before its boundary");
5049
+ if (event.beforeWarmUpSettled === void 0)
5050
+ reasons.push("an event is missing its warm-up settled boundary tag");
5051
+ if (event.beforeWarmUpSettled === false && event.nodeBuilds === void 0)
5052
+ reasons.push("an event after warm-up settled is missing its node-build count");
5053
+ }
5054
+ if (declaredCounts.nodeBuilds !== void 0 && declaredCounts.nodeBuilds < warmUpSettled.nodeBuilds)
5055
+ reasons.push("warm-up settled node-build count exceeds the total node-build count");
5056
+ for (const [index, nodeBuild] of (nodeBuilds ?? []).entries()) {
5057
+ if (nodeBuild.beforeWarmUpSettled === void 0)
5058
+ reasons.push(`node build ${index + 1} is missing its warm-up settled boundary tag`);
5059
+ else if (nodeBuild.beforeWarmUpSettled && nodeBuild.startedMs > warmUpSettled.boundaryMs || !nodeBuild.beforeWarmUpSettled && nodeBuild.startedMs <= warmUpSettled.boundaryMs)
5060
+ reasons.push(`node build ${index + 1} has an invalid warm-up settled boundary tag`);
5061
+ }
5062
+ }
5063
+ if (warmUpScopes !== void 0) {
5064
+ const labels = new Set(warmUpScopes.map(({ label }) => label));
5065
+ for (const event of events) {
5066
+ if (event.afterWarmUpScope !== void 0 && !labels.has(event.afterWarmUpScope))
5067
+ reasons.push(`event ${event.sequence} names an unknown warm-up scope`);
5068
+ }
5069
+ for (const scope of warmUpScopes) {
5070
+ const settled = events.filter(
5071
+ ({ settledMs }) => settledMs !== void 0 && settledMs <= scope.boundaryMs
5072
+ ).length;
5073
+ if (settled !== scope.eventsSettled)
5074
+ reasons.push(`warm-up scope '${scope.label}' event count does not match event timings`);
5075
+ const creations = events.filter(
5076
+ ({ kind, status, settledMs }) => kind === "render" && status === "created" && settledMs !== void 0 && settledMs <= scope.boundaryMs
5077
+ ).length;
5078
+ if (creations !== scope.renderPipelineCreations)
5079
+ reasons.push(`warm-up scope '${scope.label}' render creation count does not match event timings`);
5080
+ }
5081
+ for (const [index, nodeBuild] of (nodeBuilds ?? []).entries()) {
5082
+ if (nodeBuild.afterWarmUpScope !== void 0 && !labels.has(nodeBuild.afterWarmUpScope))
5083
+ reasons.push(`node build ${index + 1} names an unknown warm-up scope`);
5084
+ }
5085
+ }
5086
+ if (nodeBuilds !== void 0 && declaredCounts.nodeBuilds !== void 0 && nodeBuilds.length !== declaredCounts.nodeBuilds)
5087
+ reasons.push("node-build count does not match the nodeBuilds array");
5088
+ return {
5089
+ version: PIPELINE_CAPTURE_VERSION,
5090
+ source: "browser",
5091
+ complete: reasons.length === 0,
5092
+ overflowed: value.overflowed === true,
5093
+ ...backend === void 0 ? {} : { backend },
5094
+ ...clock === void 0 ? {} : { clock },
5095
+ ...build === void 0 ? {} : { build },
5096
+ ...adapter === void 0 ? {} : { adapter },
5097
+ ...firstPresent === void 0 ? {} : { firstPresent },
5098
+ ...warmUpSettled === void 0 ? {} : { warmUpSettled },
5099
+ ...warmUpScopes === void 0 ? {} : { warmUpScopes },
5100
+ counts: declaredCounts,
5101
+ events,
5102
+ ...nodeBuilds === void 0 ? {} : { nodeBuilds },
5103
+ incompleteReasons: reasons
5104
+ };
5105
+ }
5106
+ function nativeCaptureMetadata(value) {
5107
+ const source = asRecord(value);
5108
+ if (source === void 0) throw malformed("native pipeline capture metadata is not an object");
5109
+ const reasons = [];
5110
+ const build = parseBuild(source.build, reasons);
5111
+ const adapter = parseAdapter(source.adapter, reasons);
5112
+ const clock = parseClock(source.clock, reasons);
5113
+ if (reasons.length > 0) throw malformed(`native pipeline capture metadata is incomplete: ${reasons.join("; ")}`);
5114
+ if (build === void 0 || adapter === void 0 || clock === void 0)
5115
+ throw malformed("native pipeline capture metadata is incomplete");
5116
+ return { adapter, build, clock };
5117
+ }
5118
+ function nativeCapture(metadata) {
5119
+ const firstPresent = nativeFirstPresent(metadata.events, metadata.firstPresentBoundaryMs);
5120
+ const events = nativeEventsWithBoundary(metadata.events, firstPresent);
5121
+ validateEventSequence(events, "native capture", true);
5122
+ const sequence = nativeSequenceSummary(events, declaredEventCount(metadata));
5123
+ const reasons = nativeCaptureReasons(
5124
+ metadata,
5125
+ events,
5126
+ firstPresent,
5127
+ sequence.droppedEvents
5128
+ );
5129
+ const failures = events.filter(({ status }) => status === "failed").length;
5130
+ const boundary = nativeBoundary(metadata);
5131
+ const pending = events.filter(({ status }) => status === "pending").length + (boundary?.kind === "checkpoint" ? boundary.outstanding ?? 0 : 0);
5132
+ const counts = {
5133
+ lookups: 0,
5134
+ creations: events.length + sequence.droppedEvents,
5135
+ failures,
5136
+ pending,
5137
+ uniquePrograms: new Set(events.map(({ programIdentity }) => programIdentity)).size,
5138
+ uniquePipelines: new Set(events.map(({ pipelineIdentity }) => pipelineIdentity)).size,
5139
+ recordedEvents: events.length,
5140
+ droppedEvents: sequence.droppedEvents
5141
+ };
5142
+ if (failures > 0) reasons.push(`${failures} pipeline creation(s) failed`);
5143
+ return {
5144
+ version: PIPELINE_CAPTURE_VERSION,
5145
+ source: "native",
5146
+ ...boundary === void 0 ? {} : { boundary },
5147
+ complete: reasons.length === 0,
5148
+ overflowed: false,
5149
+ ...metadata.clock === void 0 ? {} : { clock: metadata.clock },
5150
+ ...metadata.build === void 0 ? {} : { build: metadata.build },
5151
+ ...metadata.adapter === void 0 ? {} : { adapter: metadata.adapter },
5152
+ ...firstPresent === void 0 ? {} : { firstPresent },
5153
+ counts,
5154
+ events,
5155
+ incompleteReasons: reasons
5156
+ };
5157
+ }
5158
+ function nativeFirstPresent(events, boundaryMs) {
5159
+ if (boundaryMs === void 0) return void 0;
5160
+ return {
5161
+ boundaryMs,
5162
+ eventsSettled: events.filter(
5163
+ ({ settledMs }) => settledMs !== void 0 && settledMs <= boundaryMs
5164
+ ).length
5165
+ };
5166
+ }
5167
+ function nativeEventsWithBoundary(events, firstPresent) {
5168
+ if (firstPresent === void 0) return events;
5169
+ return events.map(
5170
+ (event) => event.settledMs === void 0 ? event : { ...event, beforeFirstPresent: event.settledMs <= firstPresent.boundaryMs }
5171
+ );
5172
+ }
5173
+ function nativeSequenceSummary(events, expectedEventCount) {
5174
+ const firstId = events[0]?.sequence;
5175
+ const lastId = events.at(-1)?.sequence;
5176
+ const declaredCount = expectedEventCount ?? lastId;
5177
+ return {
5178
+ firstId,
5179
+ droppedEvents: declaredCount === void 0 ? 0 : Math.max(0, declaredCount - events.length)
5180
+ };
5181
+ }
5182
+ function nativeCaptureReasons(metadata, events, firstPresent, droppedEvents) {
5183
+ const reasons = nativeEventReasons(events);
5184
+ const firstId = events[0]?.sequence;
5185
+ if (firstId !== 1) reasons.push(`native event sequence starts at ${firstId ?? "missing"}, expected 1`);
5186
+ if (droppedEvents > 0) reasons.push(`${droppedEvents} native pipeline event(s) are missing from the sequence`);
5187
+ reasons.push(...nativeBoundaryReasons(metadata, events));
5188
+ if (events.length === 0) reasons.push("no native pipeline events observed");
5189
+ reasons.push(...nativeMetadataReasons(metadata, firstPresent));
5190
+ return reasons;
5191
+ }
5192
+ function declaredEventCount(metadata) {
5193
+ return metadata.expectedEventCount ?? metadata.checkpoint?.emitted;
5194
+ }
5195
+ function nativeBoundary(metadata) {
5196
+ if (metadata.expectedEventCount !== void 0)
5197
+ return { kind: "finalized", events: metadata.expectedEventCount };
5198
+ const checkpoint = metadata.checkpoint;
5199
+ if (checkpoint === void 0) return void 0;
5200
+ return {
5201
+ kind: "checkpoint",
5202
+ events: checkpoint.emitted,
5203
+ outstanding: checkpoint.outstanding,
5204
+ present: checkpoint.present
5205
+ };
5206
+ }
5207
+ function nativeBoundaryReasons(metadata, events) {
5208
+ const lastSequence = events.at(-1)?.sequence ?? 0;
5209
+ if (metadata.expectedEventCount !== void 0) {
5210
+ return metadata.expectedEventCount !== events.length || metadata.expectedEventCount !== lastSequence ? ["native pipeline event count does not match the completion marker"] : [];
5211
+ }
5212
+ const checkpoint = metadata.checkpoint;
5213
+ if (checkpoint === void 0) return ["native marker capture is missing its completion marker"];
5214
+ const reasons = [];
5215
+ if (checkpoint.outstanding > 0)
5216
+ reasons.push(`native pipeline checkpoint reports ${checkpoint.outstanding} compile(s) still outstanding`);
5217
+ if (checkpoint.emitted !== events.length || checkpoint.emitted !== lastSequence)
5218
+ reasons.push("native pipeline event count does not match the checkpoint");
5219
+ if (metadata.eventsAfterCheckpoint > 0)
5220
+ reasons.push(
5221
+ `${metadata.eventsAfterCheckpoint} native pipeline event(s) were written after the checkpoint that bounds the capture`
5222
+ );
5223
+ return reasons;
5224
+ }
5225
+ function nativeEventReasons(events) {
5226
+ const reasons = [];
5227
+ for (const event of events) {
5228
+ if (event.kind === "render" && event.vertex === void 0)
5229
+ reasons.push("a render pipeline is missing its vertex shader observation");
5230
+ if (event.kind === "compute" && event.compute === void 0)
5231
+ reasons.push("a compute pipeline is missing its shader observation");
5232
+ }
5233
+ return reasons;
5234
+ }
5235
+ function nativeMetadataReasons(metadata, firstPresent) {
5236
+ const reasons = [];
5237
+ if (metadata.build === void 0) reasons.push("native marker capture is missing its build identity");
5238
+ if (metadata.adapter === void 0) reasons.push("native marker capture is missing its adapter identity");
5239
+ else if (metadata.adapter.thermal === void 0) reasons.push("native marker capture is missing its thermal identity");
5240
+ if (metadata.clock === void 0) reasons.push("native marker capture is missing its clock origin");
5241
+ if (firstPresent === void 0) reasons.push("native marker capture is missing its first-present boundary");
5242
+ return reasons;
5243
+ }
5244
+ function unsupportedCapture(version, value) {
5245
+ return {
5246
+ version,
5247
+ source: "browser",
5248
+ complete: false,
5249
+ overflowed: value.overflowed === true,
5250
+ counts: emptyCounts(),
5251
+ events: [],
5252
+ incompleteReasons: [`unsupported pipeline capture version ${version}`]
5253
+ };
5254
+ }
5255
+ function normaliseBrowserEvent(value, index) {
5256
+ const event = asRecord(value);
5257
+ if (event === void 0) throw malformed(`browser event ${index + 1} is not an object`);
5258
+ const kind = enumValue(event.kind, ["compute", "render"], `event ${index + 1} kind`);
5259
+ const mode = enumValue(event.mode, ["sync", "async"], `event ${index + 1} mode`);
5260
+ const status = enumValue(event.status, ["created", "failed", "pending"], `event ${index + 1} status`);
5261
+ const sequence = positiveInteger(event.sequence, `event ${index + 1} sequence`);
5262
+ const programIdentity = stringValue(event.programIdentity, `event ${index + 1} programIdentity`);
5263
+ const pipelineIdentity = stringValue(event.pipelineIdentity, `event ${index + 1} pipelineIdentity`);
5264
+ const provenance = normaliseProvenance(event.provenance, `event ${index + 1}`);
5265
+ const reasons = stringArray(event.reasons);
5266
+ if (reasons.length === 0) throw malformed(`event ${index + 1} has no structural reasons`);
5267
+ const result = {
5268
+ sequence,
5269
+ programIdentity,
5270
+ pipelineIdentity,
5271
+ kind,
5272
+ pass: stringValue(event.pass, `event ${index + 1} pass`),
5273
+ mode,
5274
+ status,
5275
+ provenance,
5276
+ reasons,
5277
+ startedMs: nonNegativeNumber(event.startedMs, `event ${index + 1} startedMs`),
5278
+ ...optionalShader(event.vertex, `event ${index + 1} vertex`),
5279
+ ...optionalShader(event.fragment, `event ${index + 1} fragment`),
5280
+ ...optionalShader(event.compute, `event ${index + 1} compute`),
5281
+ ...optionalNumber(event.settledMs, "settledMs", index),
5282
+ ...optionalNumber(event.serviceMs, "serviceMs", index),
5283
+ ...optionalNumber(event.promiseMs, "promiseMs", index),
5284
+ ...optionalNumber(event.queueMs, "queueMs", index),
5285
+ ...optionalNumber(event.wallMs, "wallMs", index),
5286
+ ...event.error === void 0 ? {} : { error: stringValue(event.error, `event ${index + 1} error`) },
5287
+ ...event.nodeBuilds === void 0 ? {} : { nodeBuilds: nonNegativeInteger(event.nodeBuilds, `event ${index + 1} nodeBuilds`) },
5288
+ ...event.beforeFirstPresent === void 0 ? {} : { beforeFirstPresent: booleanValue(event.beforeFirstPresent, `event ${index + 1} beforeFirstPresent`) },
5289
+ ...event.beforeWarmUpSettled === void 0 ? {} : { beforeWarmUpSettled: booleanValue(event.beforeWarmUpSettled, `event ${index + 1} beforeWarmUpSettled`) },
5290
+ ...event.afterWarmUpScope === void 0 ? {} : { afterWarmUpScope: stringValue(event.afterWarmUpScope, `event ${index + 1} afterWarmUpScope`) }
5291
+ };
5292
+ validateEventTiming(result, `event ${index + 1}`);
5293
+ if (status === "failed" && result.error === void 0)
5294
+ throw malformed(`event ${index + 1} failed without an error`);
5295
+ if (status === "created" && result.error !== void 0)
5296
+ throw malformed(`event ${index + 1} is created but carries an error`);
5297
+ return result;
5298
+ }
5299
+ function normaliseNativeEvent(value) {
5300
+ const event = asRecord(value);
5301
+ if (event === void 0) throw malformed("native pipeline event is not an object");
5302
+ const kind = enumValue(event.kind, ["compute", "render"], "native event kind");
5303
+ const status = enumValue(event.status, ["created", "failed", "pending"], "native event status");
5304
+ const mode = enumValue(event.mode, ["sync", "async"], "native event mode");
5305
+ const sequence = positiveInteger(event.eventId, "native event eventId");
5306
+ const queueMs = nonNegativeNumber(event.queueMs, "native event queueMs");
5307
+ const serviceMs = nonNegativeNumber(event.serviceMs, "native event serviceMs");
5308
+ const wallMs = nonNegativeNumber(event.wallMs, "native event wallMs");
5309
+ const provenance = normaliseProvenance(event.provenance, "native event");
5310
+ const reasons = stringArray(event.reasons);
5311
+ const shaderField = kind === "compute" ? "compute" : "vertex";
5312
+ const shader = optionalShader(event[shaderField], `native event ${shaderField}`)[shaderField];
5313
+ const startedMs = event.startedMs === void 0 ? 0 : nonNegativeNumber(event.startedMs, "native event startedMs");
5314
+ const settledMs = event.settledMs === void 0 ? startedMs + wallMs : nonNegativeNumber(event.settledMs, "native event settledMs");
5315
+ const result = {
5316
+ sequence,
5317
+ programIdentity: stringValue(event.programIdentity, "native event programIdentity"),
5318
+ pipelineIdentity: stringValue(event.pipelineIdentity, "native event pipelineIdentity"),
5319
+ kind,
5320
+ pass: nativePass(stringValue(event.pass, "native event pass"), event.label),
5321
+ mode,
5322
+ status,
5323
+ ...kind === "compute" ? { compute: shader } : { vertex: shader },
5324
+ ...optionalShader(event.fragment, "native event fragment"),
5325
+ provenance,
5326
+ reasons: reasons.length === 0 ? ["unknown-structural-difference"] : reasons,
5327
+ startedMs,
5328
+ settledMs,
5329
+ queueMs,
5330
+ serviceMs,
5331
+ wallMs,
5332
+ ...event.label === void 0 ? {} : { label: stringValue(event.label, "native event label") },
5333
+ ...event.error === void 0 ? {} : { error: stringValue(event.error, "native event error") }
5334
+ };
5335
+ validateEventTiming(result, "native event");
5336
+ if (wallMs + 1e-6 < queueMs + serviceMs)
5337
+ throw malformed("native event wallMs is shorter than queueMs plus serviceMs");
5338
+ if (status === "failed" && result.error === void 0)
5339
+ throw malformed("native event failed without an error");
5340
+ if (status === "created" && result.error !== void 0)
5341
+ throw malformed("native event is created but carries an error");
5342
+ return result;
5343
+ }
5344
+ function parseCounts(value) {
5345
+ const source = asRecord(value);
5346
+ if (source === void 0) throw malformed("browser capture is missing counts");
5347
+ const fields = [
5348
+ "lookups",
5349
+ "creations",
5350
+ "failures",
5351
+ "pending",
5352
+ "uniquePrograms",
5353
+ "uniquePipelines",
5354
+ "recordedEvents",
5355
+ "droppedEvents"
5356
+ ];
5357
+ for (const field of fields) {
5358
+ if (!Object.hasOwn(source, field)) throw malformed(`counts is missing ${field}`);
5359
+ }
5360
+ return {
5361
+ lookups: nonNegativeInteger(source.lookups, "counts lookups"),
5362
+ creations: nonNegativeInteger(source.creations, "counts creations"),
5363
+ failures: nonNegativeInteger(source.failures, "counts failures"),
5364
+ pending: nonNegativeInteger(source.pending, "counts pending"),
5365
+ uniquePrograms: nonNegativeInteger(source.uniquePrograms, "counts uniquePrograms"),
5366
+ uniquePipelines: nonNegativeInteger(source.uniquePipelines, "counts uniquePipelines"),
5367
+ recordedEvents: nonNegativeInteger(source.recordedEvents, "counts recordedEvents"),
5368
+ droppedEvents: nonNegativeInteger(source.droppedEvents, "counts droppedEvents"),
5369
+ ...source.nodeBuilds === void 0 ? {} : { nodeBuilds: nonNegativeInteger(source.nodeBuilds, "counts nodeBuilds") }
5370
+ };
5371
+ }
5372
+ function optionalShader(value, label) {
5373
+ if (value === void 0) return {};
5374
+ const shader = asRecord(value);
5375
+ if (shader === void 0) throw malformed(`${label} is not an object`);
5376
+ return { [label.split(" ").at(-1)]: {
5377
+ hash: stringValue(shader.hash, `${label} hash`),
5378
+ bytes: nonNegativeInteger(shader.bytes, `${label} bytes`)
5379
+ } };
5380
+ }
5381
+ function normaliseProvenance(value, label) {
5382
+ const source = asRecord(value);
5383
+ if (source === void 0) throw malformed(`${label} provenance is missing`);
5384
+ const material = optionalLabel(source.material, `${label} material`);
5385
+ const object = optionalLabel(source.object, `${label} object`);
5386
+ if (typeof source.unknown !== "boolean") throw malformed(`${label} provenance unknown must be boolean`);
5387
+ if (source.unknown === true && (material !== void 0 || object !== void 0))
5388
+ throw malformed(`${label} unknown provenance cannot include material or object`);
5389
+ if (source.unknown === false && material === void 0 && object === void 0)
5390
+ throw malformed(`${label} provenance is not unknown but has no material or object`);
5391
+ return { ...material === void 0 ? {} : { material }, ...object === void 0 ? {} : { object }, unknown: source.unknown };
5392
+ }
5393
+ function optionalLabel(value, label) {
5394
+ if (value === void 0) return void 0;
5395
+ const source = asRecord(value);
5396
+ if (source === void 0) throw malformed(`${label} is not an object`);
5397
+ const result = {
5398
+ ...source.id === void 0 ? {} : { id: finiteNumber(source.id, `${label} id`) },
5399
+ ...source.name === void 0 ? {} : { name: stringValue(source.name, `${label} name`) },
5400
+ ...source.type === void 0 ? {} : { type: stringValue(source.type, `${label} type`) },
5401
+ ...source.uuid === void 0 ? {} : { uuid: stringValue(source.uuid, `${label} uuid`) }
5402
+ };
5403
+ return Object.keys(result).length === 0 ? void 0 : result;
5404
+ }
5405
+ function parseFirstPresent(value) {
5406
+ if (value === void 0) return void 0;
5407
+ const source = asRecord(value);
5408
+ if (source === void 0) throw malformed("firstPresent is not an object");
5409
+ return {
5410
+ boundaryMs: nonNegativeNumber(source.boundaryMs, "firstPresent boundaryMs"),
5411
+ eventsSettled: nonNegativeInteger(source.eventsSettled, "firstPresent eventsSettled")
5412
+ };
5413
+ }
5414
+ function parseWarmUpSettled(value) {
5415
+ if (value === void 0) return void 0;
5416
+ const source = asRecord(value);
5417
+ if (source === void 0) throw malformed("warmUpSettled is not an object");
5418
+ return {
5419
+ boundaryMs: nonNegativeNumber(source.boundaryMs, "warmUpSettled boundaryMs"),
5420
+ eventsSettled: nonNegativeInteger(source.eventsSettled, "warmUpSettled eventsSettled"),
5421
+ nodeBuilds: nonNegativeInteger(source.nodeBuilds, "warmUpSettled nodeBuilds"),
5422
+ renderPipelineCreations: nonNegativeInteger(
5423
+ source.renderPipelineCreations,
5424
+ "warmUpSettled renderPipelineCreations"
5425
+ )
5426
+ };
5427
+ }
5428
+ function parseWarmUpScopes(value) {
5429
+ if (value === void 0) return void 0;
5430
+ if (!Array.isArray(value)) throw malformed("warmUpScopes is not an array");
5431
+ return value.map((entry, index) => {
5432
+ const source = asRecord(entry);
5433
+ if (source === void 0) throw malformed(`warmUpScopes[${index}] is not an object`);
5434
+ const label = stringValue(source.label, `warmUpScopes[${index}] label`);
5435
+ if (label.trim() === "") throw malformed(`warmUpScopes[${index}] label is empty`);
5436
+ const firstDraw = source.firstDraw === void 0 ? void 0 : (() => {
5437
+ const draw = asRecord(source.firstDraw);
5438
+ if (draw === void 0) throw malformed(`warmUpScopes[${index}] firstDraw is not an object`);
5439
+ return {
5440
+ nodeBuilds: nonNegativeInteger(draw.nodeBuilds, `warmUpScopes[${index}] firstDraw nodeBuilds`),
5441
+ renderPipelineCreations: nonNegativeInteger(
5442
+ draw.renderPipelineCreations,
5443
+ `warmUpScopes[${index}] firstDraw renderPipelineCreations`
5444
+ )
5445
+ };
5446
+ })();
5447
+ return {
5448
+ label,
5449
+ boundaryMs: nonNegativeNumber(source.boundaryMs, `warmUpScopes[${index}] boundaryMs`),
5450
+ eventsSettled: nonNegativeInteger(source.eventsSettled, `warmUpScopes[${index}] eventsSettled`),
5451
+ nodeBuilds: nonNegativeInteger(source.nodeBuilds, `warmUpScopes[${index}] nodeBuilds`),
5452
+ renderPipelineCreations: nonNegativeInteger(
5453
+ source.renderPipelineCreations,
5454
+ `warmUpScopes[${index}] renderPipelineCreations`
5455
+ ),
5456
+ ...firstDraw === void 0 ? {} : { firstDraw }
5457
+ };
5458
+ });
5459
+ }
5460
+ function parseNodeBuilds(value) {
5461
+ if (value === void 0) return void 0;
5462
+ if (!Array.isArray(value)) throw malformed("nodeBuilds is not an array");
5463
+ return value.map((entry, index) => {
5464
+ const source = asRecord(entry);
5465
+ if (source === void 0) throw malformed(`nodeBuilds[${index}] is not an object`);
5466
+ return {
5467
+ provenance: normaliseProvenance(source.provenance, `nodeBuilds[${index}]`),
5468
+ startedMs: nonNegativeNumber(source.startedMs, `nodeBuilds[${index}] startedMs`),
5469
+ ...source.beforeFirstPresent === void 0 ? {} : { beforeFirstPresent: booleanValue(source.beforeFirstPresent, `nodeBuilds[${index}] beforeFirstPresent`) },
5470
+ ...source.beforeWarmUpSettled === void 0 ? {} : { beforeWarmUpSettled: booleanValue(source.beforeWarmUpSettled, `nodeBuilds[${index}] beforeWarmUpSettled`) },
5471
+ ...source.afterWarmUpScope === void 0 ? {} : { afterWarmUpScope: stringValue(source.afterWarmUpScope, `nodeBuilds[${index}] afterWarmUpScope`) }
5472
+ };
5473
+ });
5474
+ }
5475
+ function validateCaptureVersion(value, label) {
5476
+ const event = asRecord(value);
5477
+ if (event === void 0) throw malformed(`${label} is not an object`);
5478
+ if (event.version === void 0) throw malformed(`${label} is missing its version`);
5479
+ if (typeof event.version !== "number" || !Number.isInteger(event.version))
5480
+ throw malformed(`${label} version must be an integer`);
5481
+ if (event.version !== PIPELINE_CAPTURE_VERSION)
5482
+ throw malformed(`${label} has unsupported version ${event.version}`);
5483
+ }
5484
+ function validateEventSequence(events, label, allowMissing = false) {
5485
+ let previous = 0;
5486
+ for (const event of events) {
5487
+ if (event.sequence <= previous)
5488
+ throw malformed(`${label} event sequence is not strictly increasing`);
5489
+ if (!allowMissing && event.sequence !== previous + 1 && previous !== 0)
5490
+ throw malformed(`${label} event sequence has a gap before ${event.sequence}`);
5491
+ previous = event.sequence;
5492
+ }
5493
+ }
5494
+ function sequenceGapCount(events) {
5495
+ if (events.length === 0) return 0;
5496
+ const first = events[0];
5497
+ const last = events.at(-1);
5498
+ if (first === void 0 || last === void 0) return 0;
5499
+ return last.sequence - first.sequence + 1 - events.length;
5500
+ }
5501
+ function validateEventTiming(event, label) {
5502
+ if (event.settledMs !== void 0 && event.settledMs < event.startedMs)
5503
+ throw malformed(`${label} settledMs precedes startedMs`);
5504
+ if (event.serviceMs !== void 0 && event.serviceMs < 0)
5505
+ throw malformed(`${label} serviceMs must be non-negative`);
5506
+ if (event.promiseMs !== void 0 && event.promiseMs < 0)
5507
+ throw malformed(`${label} promiseMs must be non-negative`);
5508
+ if (event.queueMs !== void 0 && event.serviceMs !== void 0 && event.wallMs !== void 0 && event.wallMs + 1e-6 < event.queueMs + event.serviceMs)
5509
+ throw malformed(`${label} wallMs is shorter than queueMs plus serviceMs`);
5510
+ }
5511
+ function nativePass(pass, labelValue) {
5512
+ if (pass !== "unknown" || typeof labelValue !== "string") return pass;
5513
+ const materialMatch = /^renderPipeline_(.+)_\d+$/iu.exec(labelValue);
5514
+ const materialLabel = materialMatch?.[1] ?? labelValue;
5515
+ const label = materialLabel.toLowerCase();
5516
+ if (label.includes("shadow")) return "shadow";
5517
+ if (label.includes("pmrem")) return "pmrem";
5518
+ if (label === "outputcolortransform" || label === "renderpipeline") return "output";
5519
+ if (materialMatch !== null) return "main";
5520
+ return pass;
5521
+ }
5522
+ function contributorLabel(event) {
5523
+ return contributorLabelOfProvenance(event.provenance);
5524
+ }
5525
+ function contributorLabelOfProvenance(provenance) {
5526
+ const material = provenance.material;
5527
+ if (material?.name !== void 0) return `material:${material.name}`;
5528
+ if (material?.id !== void 0) return `material#${material.id}`;
5529
+ if (material?.type !== void 0) return `material:${material.type}`;
5530
+ const object = provenance.object;
5531
+ if (object?.name !== void 0) return `object:${object.name}`;
5532
+ if (object?.id !== void 0) return `object#${object.id}`;
5533
+ return "unknown provenance";
5534
+ }
5535
+ function compareContributor(left, right) {
5536
+ return (right.serviceMs ?? -1) - (left.serviceMs ?? -1) || right.creations - left.creations || left.label.localeCompare(right.label);
5537
+ }
5538
+ function firstDefinedRecord(...values) {
5539
+ for (const value of values) {
5540
+ if (value === void 0) continue;
5541
+ const record4 = asRecord(value);
5542
+ if (record4 === void 0) throw malformed("pipeline capture wrapper must be an object");
5543
+ return record4;
5544
+ }
5545
+ return void 0;
5546
+ }
5547
+ function asRecord(value) {
5548
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
5549
+ }
5550
+ function recordOrUndefined(value) {
5551
+ return asRecord(value);
5552
+ }
5553
+ function stringArray(value) {
5554
+ if (value === void 0) return [];
5555
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) throw malformed("expected an array of strings");
5556
+ return [...value];
5557
+ }
5558
+ function enumValue(value, values, label) {
5559
+ if (typeof value !== "string" || !values.includes(value)) throw malformed(`${label} is invalid`);
5560
+ return value;
5561
+ }
5562
+ function stringValue(value, label) {
5563
+ if (typeof value !== "string" || value.length === 0) throw malformed(`${label} must be a non-empty string`);
5564
+ return value;
5565
+ }
5566
+ function finiteNumber(value, label) {
5567
+ if (typeof value !== "number" || !Number.isFinite(value)) throw malformed(`${label} must be finite`);
5568
+ return value;
5569
+ }
5570
+ function nonNegativeNumber(value, label) {
5571
+ const result = finiteNumber(value, label);
5572
+ if (result < 0) throw malformed(`${label} must be non-negative`);
5573
+ return result;
5574
+ }
5575
+ function positiveInteger(value, label) {
5576
+ const result = nonNegativeInteger(value, label);
5577
+ if (result === 0) throw malformed(`${label} must be positive`);
5578
+ return result;
5579
+ }
5580
+ function nonNegativeInteger(value, label) {
5581
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw malformed(`${label} must be a non-negative integer`);
5582
+ return value;
5583
+ }
5584
+ function booleanValue(value, label) {
5585
+ if (typeof value !== "boolean") throw malformed(`${label} must be boolean`);
5586
+ return value;
5587
+ }
5588
+ function optionalNumber(value, field, index) {
5589
+ if (value === void 0) return {};
5590
+ return { [field]: nonNegativeNumber(value, `event ${index + 1} ${field}`) };
5591
+ }
5592
+ function emptyCounts() {
5593
+ return { lookups: 0, creations: 0, failures: 0, pending: 0, uniquePrograms: 0, uniquePipelines: 0, recordedEvents: 0, droppedEvents: 0 };
5594
+ }
5595
+ function parseClock(value, reasons) {
5596
+ const source = recordOrUndefined(value);
5597
+ if (source === void 0) {
5598
+ reasons.push("capture is missing its clock origin");
5599
+ return void 0;
5600
+ }
5601
+ if (source.source !== "performance" && source.source !== "date" && source.source !== "steady")
5602
+ reasons.push("capture clock source is invalid");
5603
+ if (typeof source.originMs !== "number" || !Number.isFinite(source.originMs) || source.originMs < 0)
5604
+ reasons.push("capture clock origin is invalid");
5605
+ return source;
5606
+ }
5607
+ function parseBackend(value, reasons) {
5608
+ const source = recordOrUndefined(value);
5609
+ if (source === void 0) {
5610
+ reasons.push("capture is missing its backend identity");
5611
+ return void 0;
5612
+ }
5613
+ if (source.kind !== "webgpu" && source.kind !== "webgl2")
5614
+ reasons.push("capture backend kind is invalid");
5615
+ if (typeof source.identity !== "string" || source.identity.length === 0)
5616
+ reasons.push("capture backend identity is invalid");
5617
+ return source;
5618
+ }
5619
+ function parseBuild(value, reasons) {
5620
+ const source = recordOrUndefined(value);
5621
+ if (source === void 0) {
5622
+ reasons.push("capture is missing its build identity");
5623
+ return void 0;
5624
+ }
5625
+ if (typeof source.identity !== "string" || source.identity.length === 0)
5626
+ reasons.push("capture build identity is invalid");
5627
+ return source;
5628
+ }
5629
+ function parseAdapter(value, reasons) {
5630
+ const source = recordOrUndefined(value);
5631
+ if (source === void 0) {
5632
+ reasons.push("capture is missing its adapter identity", "capture is missing its thermal identity");
5633
+ return void 0;
5634
+ }
5635
+ if (typeof source.identity !== "string" || source.identity.length === 0)
5636
+ reasons.push("capture adapter identity is invalid");
5637
+ if (typeof source.thermal !== "string" || source.thermal.length === 0)
5638
+ reasons.push("capture thermal identity is invalid");
5639
+ return source;
5640
+ }
5641
+ function malformed(detail) {
5642
+ return new Error(`TN_PIPELINE_CAPTURE_MALFORMED: ${detail}`);
5643
+ }
5644
+ function errorMessage(error) {
5645
+ return error instanceof Error ? error.message : String(error);
5646
+ }
5647
+
5648
+ // src/evaluators/pipeline-census.ts
5649
+ function emitPipelineCensus(ctx) {
5650
+ const assertion = ctx.scenarioAssertions.pipelineCensus;
5651
+ if (assertion === void 0) return;
5652
+ let capture;
5653
+ let summary;
5654
+ let parseError;
5655
+ try {
5656
+ capture = parsePipelineCapture({
5657
+ observations: { pipelineCensus: ctx.input.report.observations?.pipelineCensus }
5658
+ });
5659
+ summary = summarizePipelineCapture(capture);
5660
+ } catch (error) {
5661
+ parseError = error instanceof Error ? error.message : String(error);
5662
+ }
5663
+ const boundary = capture?.warmUpSettled;
5664
+ const nodeBuilds = summary?.warmup.warmedNodeBuildsAfterWarmUpSettled;
5665
+ const renderPipelineCreations = summary?.warmup.warmedRenderPipelineCreationsAfterWarmUpSettled;
5666
+ const scopeLabel = assertion.warmUpScope;
5667
+ const scope = scopeLabel === void 0 ? void 0 : summary?.warmup.scopes.find(({ label }) => label === scopeLabel);
5668
+ const boundaryUsable = capture?.complete === true && boundary !== void 0;
5669
+ const usable = boundaryUsable && nodeBuilds !== void 0 && renderPipelineCreations !== void 0;
5670
+ const unobservable = parseError ?? (boundary === void 0 ? "the capture has no warm-up-settled boundary" : capture?.complete !== true ? `the capture is incomplete: ${capture?.incompleteReasons.join("; ") ?? "unknown reason"}` : nodeBuilds === void 0 ? "the capture has no per-material warm-up node-build count" : "the capture has no per-material post-warm-up render-pipeline count");
5671
+ const checks = [
5672
+ ["maxNodeBuildsAfterWarmUpSettled", nodeBuilds, "node builds"],
5673
+ ["maxRenderPipelineCreationsAfterWarmUpSettled", renderPipelineCreations, "render-pipeline creations"]
5674
+ ];
5675
+ if (assertion.maxNodeBuildsAfterWarmUpScope !== void 0 || assertion.maxRenderPipelineCreationsAfterWarmUpScope !== void 0) {
5676
+ const scopedUsable = capture?.complete === true && scope?.observed === true;
5677
+ const scopedChecks = [
5678
+ ["maxNodeBuildsAfterWarmUpScope", scope?.nodeBuilds, "node builds"],
5679
+ ["maxRenderPipelineCreationsAfterWarmUpScope", scope?.renderPipelineCreations, "render-pipeline creations"]
5680
+ ];
5681
+ for (const [key, observed, label] of scopedChecks) {
5682
+ const expected = assertion[key];
5683
+ if (expected === void 0) continue;
5684
+ const pass = scopedUsable && observed !== void 0 && observed <= expected;
5685
+ const id = `pipelineCensus.${key}`;
5686
+ ctx.assertions.push({ details: { boundary, complete: capture?.complete, expected, incompleteReasons: capture?.incompleteReasons, observed, scope: scopeLabel }, id, pass });
5687
+ if (!pass)
5688
+ ctx.diagnostics.push({
5689
+ code: scopedUsable ? "TN_PLAYTEST_PIPELINE_CENSUS_CEILING_EXCEEDED" : "TN_PLAYTEST_PIPELINE_CENSUS_UNOBSERVABLE",
5690
+ message: scopedUsable ? `The pipeline census observed ${observed} ${label} after warm-up scope '${scopeLabel}', above the asserted ceiling of ${expected}.` : `The pipeline census cannot evaluate '${id}': ${scopeLabel === void 0 ? "the assertion has no warm-up scope label" : `scope '${scopeLabel}' is absent or incomplete`}.`,
5691
+ observedRuntimePath: "observations.json/pipelineCensus",
5692
+ severity: "error",
5693
+ suggestion: scopedUsable ? "Move the affected first-use pipeline work into the streamed warm-up and verify the scoped census again." : "Run with runtime.pipelineCensus enabled and keep the named warm-up scope in the report."
5694
+ });
5695
+ }
5696
+ }
5697
+ for (const [key, observed, label] of checks) {
5698
+ const expected = assertion[key];
5699
+ if (expected === void 0) continue;
5700
+ const pass = usable && observed !== void 0 && observed <= expected;
5701
+ const id = `pipelineCensus.${key}`;
5702
+ ctx.assertions.push({
5703
+ details: {
5704
+ boundary,
5705
+ complete: capture?.complete,
5706
+ expected,
5707
+ incompleteReasons: capture?.incompleteReasons,
5708
+ observed
5709
+ },
5710
+ id,
5711
+ pass
5712
+ });
5713
+ if (pass) continue;
5714
+ ctx.diagnostics.push({
5715
+ code: usable ? "TN_PLAYTEST_PIPELINE_CENSUS_CEILING_EXCEEDED" : "TN_PLAYTEST_PIPELINE_CENSUS_UNOBSERVABLE",
5716
+ message: usable ? `The pipeline census observed ${observed} ${label} after warm-up settled, above the asserted ceiling of ${expected}.` : `The pipeline census cannot evaluate '${id}': ${unobservable}.`,
5717
+ observedRuntimePath: "observations.json/pipelineCensus",
5718
+ severity: "error",
5719
+ suggestion: usable ? "Move the affected first-use pipeline work into the explicit warm-up and verify the post-warm-up census again." : "Run with runtime.pipelineCensus enabled and keep the warm-up-settled boundary and complete capture in the report."
5720
+ });
5721
+ }
5722
+ }
5723
+
4388
5724
  // src/assertion-evaluators.ts
4389
5725
  function evaluateRichPlaytestAssertions(input) {
4390
5726
  const assertions = [];
4391
5727
  const diagnostics = [];
4392
5728
  const scenarioAssertions = input.scenario.assert ?? {};
4393
5729
  const ctx = { assertions, diagnostics, input, scenarioAssertions };
5730
+ emitTone(ctx);
4394
5731
  emitDeviceMetrics(ctx);
4395
5732
  emitDisplayFamilies(ctx);
4396
5733
  emitEvidenceFamilies(ctx);
@@ -4398,6 +5735,7 @@ function evaluateRichPlaytestAssertions(input) {
4398
5735
  emitPerfSignalsWorld(ctx);
4399
5736
  emitWorldGameplay(ctx);
4400
5737
  emitRenderChain(ctx);
5738
+ emitPipelineCensus(ctx);
4401
5739
  emitScene(ctx);
4402
5740
  emitSceneNodes(ctx);
4403
5741
  if (scenarioAssertions.geometry !== void 0) {
@@ -4764,12 +6102,25 @@ function rejectUnknownKeys(value, allowedKeys, scenarioPath, objectPath) {
4764
6102
  }
4765
6103
  var NUMERIC_COMPARISON_KEYS = ["gte", "lte"];
4766
6104
  var MIN_TRIVIALITY_REASON_LENGTH = 20;
6105
+ var PLAYTEST_GPU_FAMILIES = ["discrete", "integrated", "mobile-high", "mobile-low", "mobile-mid"];
6106
+ var PLAYTEST_PER_ADAPTER_KEYS = ["hardware", "software", ...PLAYTEST_GPU_FAMILIES];
4767
6107
 
4768
6108
  // src/scenario/generated-assertion-validators.ts
4769
6109
  function isRecord2(value) {
4770
6110
  return typeof value === "object" && value !== null && !Array.isArray(value);
4771
6111
  }
4772
6112
  var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
6113
+ "tone": Object.freeze({
6114
+ "atStep": (value) => typeof value === "string" && value.trim() !== "",
6115
+ "region": (value) => isRecord2(value),
6116
+ "compare": (value) => isRecord2(value),
6117
+ "mean": (value) => isRecord2(value),
6118
+ "p1": (value) => isRecord2(value),
6119
+ "p50": (value) => isRecord2(value),
6120
+ "p99": (value) => isRecord2(value),
6121
+ "clipFraction": (value) => isRecord2(value),
6122
+ "blackFraction": (value) => isRecord2(value)
6123
+ }),
4773
6124
  "deviceMetrics": Object.freeze({
4774
6125
  "maxTemperatureRiseC": (value) => typeof value === "number" && Number.isFinite(value) && value >= 0,
4775
6126
  "maxThermalStatus": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 6,
@@ -4984,6 +6335,13 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
4984
6335
  "maxCompileSettledMs": (value) => typeof value === "number" && Number.isFinite(value),
4985
6336
  "maxReadyMs": (value) => typeof value === "number" && Number.isFinite(value)
4986
6337
  }),
6338
+ "pipelineCensus": Object.freeze({
6339
+ "maxNodeBuildsAfterWarmUpSettled": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
6340
+ "maxRenderPipelineCreationsAfterWarmUpSettled": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
6341
+ "warmUpScope": (value) => typeof value === "string" && value.trim() !== "",
6342
+ "maxNodeBuildsAfterWarmUpScope": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
6343
+ "maxRenderPipelineCreationsAfterWarmUpScope": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0
6344
+ }),
4987
6345
  "renderChain": Object.freeze({
4988
6346
  "tier": (value) => typeof value === "string" && value.trim() !== "",
4989
6347
  "stages": (value) => isRecord2(value),
@@ -4996,7 +6354,7 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
4996
6354
  // src/scenario/schema-accessors.ts
4997
6355
  function validateVisualAssertion(value, scenarioPath, objectPath) {
4998
6356
  const record4 = requireRecord(value, scenarioPath, objectPath);
4999
- const frameDiff = record4.frameDiff === void 0 ? void 0 : validateVisualFrameDiff(requireRecord(record4.frameDiff, scenarioPath, `${objectPath}.frameDiff`), scenarioPath, `${objectPath}.frameDiff`);
6357
+ const frameDiff = record4.frameDiff === void 0 ? void 0 : validateVisualFrameDiff(record4.frameDiff, scenarioPath, `${objectPath}.frameDiff`);
5000
6358
  const regionRecord = record4.region === void 0 ? void 0 : requireRecord(record4.region, scenarioPath, `${objectPath}.region`);
5001
6359
  let region;
5002
6360
  if (regionRecord !== void 0) {
@@ -5010,9 +6368,9 @@ function validateVisualAssertion(value, scenarioPath, objectPath) {
5010
6368
  region = {
5011
6369
  element,
5012
6370
  ...present("maxDarkPixelRatio", optionalRatio(regionRecord, "maxDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
5013
- ...present("maxLuminance", optionalNumber(regionRecord, "maxLuminance", scenarioPath, `${objectPath}.region`)),
5014
- ...present("minDarkPixelRatio", optionalNumber(regionRecord, "minDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
5015
- ...present("minNonblankPixelRatio", optionalNumber(regionRecord, "minNonblankPixelRatio", scenarioPath, `${objectPath}.region`))
6371
+ ...present("maxLuminance", optionalRatio(regionRecord, "maxLuminance", scenarioPath, `${objectPath}.region`)),
6372
+ ...present("minDarkPixelRatio", optionalRatio(regionRecord, "minDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
6373
+ ...present("minNonblankPixelRatio", optionalRatio(regionRecord, "minNonblankPixelRatio", scenarioPath, `${objectPath}.region`))
5016
6374
  };
5017
6375
  } else {
5018
6376
  const edges = { height: 0, width: 0, x: 0, y: 0 };
@@ -5026,17 +6384,17 @@ function validateVisualAssertion(value, scenarioPath, objectPath) {
5026
6384
  region = {
5027
6385
  ...edges,
5028
6386
  ...present("maxDarkPixelRatio", optionalRatio(regionRecord, "maxDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
5029
- ...present("maxLuminance", optionalNumber(regionRecord, "maxLuminance", scenarioPath, `${objectPath}.region`)),
5030
- ...present("minDarkPixelRatio", optionalNumber(regionRecord, "minDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
5031
- ...present("minNonblankPixelRatio", optionalNumber(regionRecord, "minNonblankPixelRatio", scenarioPath, `${objectPath}.region`))
6387
+ ...present("maxLuminance", optionalRatio(regionRecord, "maxLuminance", scenarioPath, `${objectPath}.region`)),
6388
+ ...present("minDarkPixelRatio", optionalRatio(regionRecord, "minDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
6389
+ ...present("minNonblankPixelRatio", optionalRatio(regionRecord, "minNonblankPixelRatio", scenarioPath, `${objectPath}.region`))
5032
6390
  };
5033
6391
  }
5034
6392
  }
5035
6393
  const entityVisibleRecord = record4.entityVisible === void 0 ? void 0 : requireRecord(record4.entityVisible, scenarioPath, `${objectPath}.entityVisible`);
5036
6394
  let entityVisible;
5037
6395
  if (entityVisibleRecord !== void 0) {
5038
- if (typeof entityVisibleRecord.minProjectedPixels !== "number") {
5039
- throw invalidScenario(scenarioPath, `'${objectPath}.entityVisible.minProjectedPixels' must be a number, received ${describeValue(entityVisibleRecord.minProjectedPixels)}.`);
6396
+ if (typeof entityVisibleRecord.minProjectedPixels !== "number" || !Number.isFinite(entityVisibleRecord.minProjectedPixels) || entityVisibleRecord.minProjectedPixels < 0) {
6397
+ throw invalidScenario(scenarioPath, `'${objectPath}.entityVisible.minProjectedPixels' must be a non-negative number of pixels, received ${describeValue(entityVisibleRecord.minProjectedPixels)}.`);
5040
6398
  }
5041
6399
  entityVisible = {
5042
6400
  entity: requireString(entityVisibleRecord, "entity", scenarioPath, `${objectPath}.entityVisible`),
@@ -5069,15 +6427,20 @@ function validateVisualRegionTarget(value, scenarioPath, objectPath) {
5069
6427
  ...selector === void 0 ? {} : { selector }
5070
6428
  };
5071
6429
  }
5072
- function validateVisualFrameDiff(record4, scenarioPath, objectPath) {
6430
+ function validateVisualFrameDiff(value, scenarioPath, objectPath) {
6431
+ const record4 = requireRecord(value, scenarioPath, objectPath);
5073
6432
  if (record4.baselineImage !== void 0 && !isSafeProjectRelativePng(record4.baselineImage)) {
5074
6433
  throw invalidScenario(scenarioPath, `'${objectPath}.baselineImage' must be a project-relative .png path without '..' or absolute segments, received ${describeValue(record4.baselineImage)}.`);
5075
6434
  }
5076
- return {
6435
+ const frameDiff = {
5077
6436
  ...present("baselineImage", optionalString(record4, "baselineImage", scenarioPath, objectPath)),
5078
- ...present("maxChangedPixelRatio", optionalNumber(record4, "maxChangedPixelRatio", scenarioPath, objectPath)),
5079
- ...present("minChangedPixelRatio", optionalNumber(record4, "minChangedPixelRatio", scenarioPath, objectPath))
6437
+ ...present("maxChangedPixelRatio", optionalRatio(record4, "maxChangedPixelRatio", scenarioPath, objectPath)),
6438
+ ...present("minChangedPixelRatio", optionalRatio(record4, "minChangedPixelRatio", scenarioPath, objectPath))
5080
6439
  };
6440
+ if (frameDiff.maxChangedPixelRatio === void 0 && frameDiff.minChangedPixelRatio === void 0) {
6441
+ throw invalidScenario(scenarioPath, `'${objectPath}' must set maxChangedPixelRatio or minChangedPixelRatio; a frameDiff that bounds no ratio accepts every frame.`);
6442
+ }
6443
+ return frameDiff;
5081
6444
  }
5082
6445
  function isSafeProjectRelativePng(value) {
5083
6446
  if (typeof value !== "string" || !value.toLowerCase().endsWith(".png") || value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value)) {
@@ -5135,7 +6498,7 @@ function optionalBoolean(value, key, scenarioPath, objectPath) {
5135
6498
  }
5136
6499
  return raw;
5137
6500
  }
5138
- function optionalNumber(value, key, scenarioPath, objectPath) {
6501
+ function optionalNumber2(value, key, scenarioPath, objectPath) {
5139
6502
  const raw = value[key];
5140
6503
  if (raw === void 0) return void 0;
5141
6504
  if (typeof raw !== "number" || !Number.isFinite(raw)) {
@@ -5224,7 +6587,7 @@ function validateDeviceMetricsAssertion(value, scenarioPath, objectPath) {
5224
6587
  function validatePerformanceAssertion(value, scenarioPath, objectPath) {
5225
6588
  const record4 = requireRecord(value, scenarioPath, objectPath);
5226
6589
  rejectUnknownKeys(record4, ["maxDrawCalls", "maxFrameMsP95", "maxPassDrawCalls", "maxPassTriangles", "maxPhaseMsP95", "maxTriangles", "minFps"], scenarioPath, objectPath);
5227
- return {
6590
+ const assertion = {
5228
6591
  ...present("maxDrawCalls", optionalNonNegativeNumber(record4, "maxDrawCalls", scenarioPath, objectPath)),
5229
6592
  ...present("maxFrameMsP95", optionalNonNegativeNumber(record4, "maxFrameMsP95", scenarioPath, objectPath)),
5230
6593
  ...present("maxPassDrawCalls", validatePassBudget(record4.maxPassDrawCalls, scenarioPath, `${objectPath}.maxPassDrawCalls`)),
@@ -5233,15 +6596,22 @@ function validatePerformanceAssertion(value, scenarioPath, objectPath) {
5233
6596
  ...present("maxTriangles", optionalNonNegativeNumber(record4, "maxTriangles", scenarioPath, objectPath)),
5234
6597
  ...present("minFps", optionalNonNegativeNumber(record4, "minFps", scenarioPath, objectPath))
5235
6598
  };
6599
+ if (Object.keys(assertion).length === 0) {
6600
+ throw invalidScenario(
6601
+ scenarioPath,
6602
+ `'${objectPath}' must set at least one of maxDrawCalls, maxFrameMsP95, maxPassDrawCalls, maxPassTriangles, maxPhaseMsP95, maxTriangles, or minFps.`
6603
+ );
6604
+ }
6605
+ return assertion;
5236
6606
  }
5237
6607
  function validateParityAssertion(value, scenarioPath, objectPath) {
5238
6608
  const record4 = requireRecord(value, scenarioPath, objectPath);
5239
6609
  rejectUnknownKeys(record4, ["minFpsRatio", "minRenderParity", "reference", "referenceReport", "referenceSide"], scenarioPath, objectPath);
5240
- const minFpsRatio = optionalNumber(record4, "minFpsRatio", scenarioPath, objectPath);
6610
+ const minFpsRatio = optionalNumber2(record4, "minFpsRatio", scenarioPath, objectPath);
5241
6611
  if (minFpsRatio === void 0 || minFpsRatio <= 0) {
5242
6612
  throw invalidScenario(scenarioPath, `'${objectPath}.minFpsRatio' must be a positive number (Tier 2's Floor is 0.85).`);
5243
6613
  }
5244
- const minRenderParity = optionalNumber(record4, "minRenderParity", scenarioPath, objectPath);
6614
+ const minRenderParity = optionalNumber2(record4, "minRenderParity", scenarioPath, objectPath);
5245
6615
  if (minRenderParity !== void 0 && minRenderParity <= 0) {
5246
6616
  throw invalidScenario(scenarioPath, `'${objectPath}.minRenderParity' must be a positive number when present.`);
5247
6617
  }
@@ -5254,11 +6624,11 @@ function validateParityAssertion(value, scenarioPath, objectPath) {
5254
6624
  throw invalidScenario(scenarioPath, `'${objectPath}.referenceSide' must be 'browser' or 'native' \u2014 the directed native \xF7 web ratio needs to know which side the reference is.`);
5255
6625
  }
5256
6626
  const reference = record4.reference === void 0 ? void 0 : requireRecord(record4.reference, scenarioPath, `${objectPath}.reference`);
5257
- const referenceFps = reference === void 0 ? void 0 : optionalNumber(reference, "fps", scenarioPath, `${objectPath}.reference`);
6627
+ const referenceFps = reference === void 0 ? void 0 : optionalNumber2(reference, "fps", scenarioPath, `${objectPath}.reference`);
5258
6628
  if (referenceFps !== void 0 && referenceFps <= 0) {
5259
6629
  throw invalidScenario(scenarioPath, `'${objectPath}.reference.fps' must be a positive number.`);
5260
6630
  }
5261
- const referenceRenderP95 = reference === void 0 ? void 0 : optionalNumber(reference, "renderP95", scenarioPath, `${objectPath}.reference`);
6631
+ const referenceRenderP95 = reference === void 0 ? void 0 : optionalNumber2(reference, "renderP95", scenarioPath, `${objectPath}.reference`);
5262
6632
  if (referenceRenderP95 !== void 0 && referenceRenderP95 <= 0) {
5263
6633
  throw invalidScenario(scenarioPath, `'${objectPath}.reference.renderP95' must be a positive number.`);
5264
6634
  }
@@ -5299,10 +6669,10 @@ function validateRenderChainPerAdapter(value, scenarioPath, objectPath) {
5299
6669
  }
5300
6670
  const result = {};
5301
6671
  for (const [kind, branch] of entries) {
5302
- if (kind !== "hardware" && kind !== "software") {
6672
+ if (!PLAYTEST_PER_ADAPTER_KEYS.includes(kind)) {
5303
6673
  throw invalidScenario(
5304
6674
  scenarioPath,
5305
- `'${objectPath}.${kind}' is not an adapter class this harness can classify; expected hardware or software.`
6675
+ `'${objectPath}.${kind}' is not an adapter class this harness can classify; expected ${PLAYTEST_PER_ADAPTER_KEYS.join(", ")}.`
5306
6676
  );
5307
6677
  }
5308
6678
  result[kind] = validateRenderChainExpectation(
@@ -5339,7 +6709,7 @@ function validateRenderChainExpectation(record4, scenarioPath, objectPath) {
5339
6709
  const velocityValue = record4.velocity;
5340
6710
  const velocity = velocityValue === void 0 ? void 0 : requireRecord(velocityValue, scenarioPath, `${objectPath}.velocity`);
5341
6711
  if (velocity !== void 0) {
5342
- const maxRejectionFraction = optionalNumber(velocity, "maxRejectionFraction", scenarioPath, `${objectPath}.velocity`);
6712
+ const maxRejectionFraction = optionalNumber2(velocity, "maxRejectionFraction", scenarioPath, `${objectPath}.velocity`);
5343
6713
  if (maxRejectionFraction === void 0 || maxRejectionFraction < 0 || maxRejectionFraction > 1) {
5344
6714
  throw invalidScenario(scenarioPath, `'${objectPath}.velocity.maxRejectionFraction' must be a finite number between 0 and 1.`);
5345
6715
  }
@@ -5392,6 +6762,36 @@ function validateStartupAssertion(value, scenarioPath, objectPath) {
5392
6762
  }
5393
6763
  return result;
5394
6764
  }
6765
+ var PIPELINE_CENSUS_CEILINGS = [
6766
+ "maxNodeBuildsAfterWarmUpSettled",
6767
+ "maxRenderPipelineCreationsAfterWarmUpSettled",
6768
+ "maxNodeBuildsAfterWarmUpScope",
6769
+ "maxRenderPipelineCreationsAfterWarmUpScope"
6770
+ ];
6771
+ function validatePipelineCensusAssertion(value, scenarioPath, objectPath) {
6772
+ const record4 = requireRecord(value, scenarioPath, objectPath);
6773
+ rejectUnknownKeys(record4, [...PIPELINE_CENSUS_CEILINGS, "warmUpScope"], scenarioPath, objectPath);
6774
+ const result = {};
6775
+ if (record4.warmUpScope !== void 0) {
6776
+ if (typeof record4.warmUpScope !== "string" || record4.warmUpScope.trim() === "")
6777
+ throw invalidScenario(scenarioPath, `'${objectPath}.warmUpScope' must be a non-empty string`);
6778
+ result.warmUpScope = record4.warmUpScope;
6779
+ }
6780
+ for (const key of PIPELINE_CENSUS_CEILINGS) {
6781
+ const ceiling = optionalNonNegativeInteger(record4, key, scenarioPath, objectPath);
6782
+ if (ceiling !== void 0) result[key] = ceiling;
6783
+ }
6784
+ const hasScopeCeiling = result.maxNodeBuildsAfterWarmUpScope !== void 0 || result.maxRenderPipelineCreationsAfterWarmUpScope !== void 0;
6785
+ if (hasScopeCeiling && result.warmUpScope === void 0)
6786
+ throw invalidScenario(scenarioPath, `'${objectPath}.warmUpScope' is required for a scoped pipeline census ceiling`);
6787
+ if (!PIPELINE_CENSUS_CEILINGS.some((key) => result[key] !== void 0)) {
6788
+ throw invalidScenario(
6789
+ scenarioPath,
6790
+ `'${objectPath}' must set at least one of ${PIPELINE_CENSUS_CEILINGS.join(", ")}; an empty pipeline census assertion observes nothing.`
6791
+ );
6792
+ }
6793
+ return result;
6794
+ }
5395
6795
  function validatePassBudget(value, scenarioPath, objectPath) {
5396
6796
  if (value === void 0) return void 0;
5397
6797
  const record4 = requireRecord(value, scenarioPath, objectPath);
@@ -5507,7 +6907,7 @@ function validateContactAssertion(value, scenarioPath, objectPath) {
5507
6907
  ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
5508
6908
  ...present("kind", optionalString(record4, "kind", scenarioPath, objectPath)),
5509
6909
  ...present("maxCount", optionalNonNegativeInteger(record4, "maxCount", scenarioPath, objectPath)),
5510
- ...present("minCount", optionalNumber(record4, "minCount", scenarioPath, objectPath)),
6910
+ ...present("minCount", optionalNumber2(record4, "minCount", scenarioPath, objectPath)),
5511
6911
  ...present("requiredOn", optionalTargetArray(record4, "requiredOn", scenarioPath, objectPath)),
5512
6912
  ...present("with", optionalString(record4, "with", scenarioPath, objectPath))
5513
6913
  };
@@ -5540,6 +6940,20 @@ function validateSceneAssertion(value, scenarioPath, objectPath) {
5540
6940
  `'${objectPath}' must set at least one of ${[...SCENE_FLAGS, "minVisibleLights"].join(", ")}; an empty scene assertion observes nothing.`
5541
6941
  );
5542
6942
  }
6943
+ for (const flag of SCENE_FLAGS) {
6944
+ if (result[flag] === false) {
6945
+ throw invalidScenario(
6946
+ scenarioPath,
6947
+ `${objectPath}.${flag} may only be true; remove the key to stop requiring it.`
6948
+ );
6949
+ }
6950
+ }
6951
+ if (result.minVisibleLights === 0) {
6952
+ throw invalidScenario(
6953
+ scenarioPath,
6954
+ `${objectPath}.minVisibleLights must be at least 1; a floor of zero is met by an unlit scene.`
6955
+ );
6956
+ }
5543
6957
  return result;
5544
6958
  }
5545
6959
  var SCENE_NODE_SELECTOR_KEYS = ["limit", "name", "nameContains", "pathContains", "type"];
@@ -5596,6 +7010,11 @@ function validateCausedByAssertion(value, scenarioPath, objectPath) {
5596
7010
  scenarioPath,
5597
7011
  `'${objectPath}' must set neverBefore or withinTicks; without one it asserts only that both events happened, which assert.states and assert.contacts already do separately.`
5598
7012
  );
7013
+ if (result.neverBefore === false)
7014
+ throw invalidScenario(
7015
+ scenarioPath,
7016
+ `${objectPath}.neverBefore may only be true; remove the key and set withinTicks to keep the row.`
7017
+ );
5599
7018
  return result;
5600
7019
  }
5601
7020
  function validateSceneNodeSelector(value, scenarioPath, objectPath) {
@@ -5641,19 +7060,24 @@ function validateSceneNodesAssertion(value, scenarioPath, objectPath) {
5641
7060
  scenarioPath,
5642
7061
  `'${objectPath}' must set at least one of ${SCENE_NODE_BOUNDS.join(", ")}; selecting nodes without bounding them observes nothing.`
5643
7062
  );
7063
+ if (result.texturesLoaded === false)
7064
+ throw invalidScenario(
7065
+ scenarioPath,
7066
+ `${objectPath}.texturesLoaded may only be true; remove the key to stop requiring loaded textures.`
7067
+ );
5644
7068
  return result;
5645
7069
  }
5646
7070
  function validateAnimationAssertion(value, scenarioPath, objectPath) {
5647
7071
  const record4 = requireRecord(value, scenarioPath, objectPath);
5648
7072
  rejectUnknownKeys(record4, ["advancedFrames", "allowTrivial", "clip", "entered", "entity", "finished", "maxFootSlide", "strideSynced"], scenarioPath, objectPath);
5649
7073
  return {
5650
- ...present("advancedFrames", optionalNumber(record4, "advancedFrames", scenarioPath, objectPath)),
7074
+ ...present("advancedFrames", optionalNumber2(record4, "advancedFrames", scenarioPath, objectPath)),
5651
7075
  ...present("allowTrivial", optionalTrivialityReason(record4, "allowTrivial", scenarioPath, objectPath)),
5652
7076
  ...present("clip", optionalString(record4, "clip", scenarioPath, objectPath)),
5653
7077
  ...present("entered", optionalBoolean(record4, "entered", scenarioPath, objectPath)),
5654
7078
  ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
5655
7079
  ...present("finished", optionalBoolean(record4, "finished", scenarioPath, objectPath)),
5656
- ...present("maxFootSlide", optionalNumber(record4, "maxFootSlide", scenarioPath, objectPath)),
7080
+ ...present("maxFootSlide", optionalNonNegativeNumber(record4, "maxFootSlide", scenarioPath, objectPath)),
5657
7081
  ...present("strideSynced", optionalBoolean(record4, "strideSynced", scenarioPath, objectPath))
5658
7082
  };
5659
7083
  }
@@ -5663,24 +7087,32 @@ function validateVisibilityAssertion(value, scenarioPath, objectPath) {
5663
7087
  return {
5664
7088
  ...present("allowTrivial", optionalTrivialityReason(record4, "allowTrivial", scenarioPath, objectPath)),
5665
7089
  ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
5666
- ...present("maxOffscreenRatio", optionalNumber(record4, "maxOffscreenRatio", scenarioPath, objectPath)),
5667
- ...present("minProjectedPixels", optionalNumber(record4, "minProjectedPixels", scenarioPath, objectPath)),
7090
+ ...present("maxOffscreenRatio", optionalRatio(record4, "maxOffscreenRatio", scenarioPath, objectPath)),
7091
+ ...present("minProjectedPixels", optionalNonNegativeNumber(record4, "minProjectedPixels", scenarioPath, objectPath)),
5668
7092
  ...present("present", optionalBoolean(record4, "present", scenarioPath, objectPath))
5669
7093
  };
5670
7094
  }
5671
7095
  function validatePathAssertion(value, scenarioPath, objectPath) {
5672
7096
  const record4 = requireRecord(value, scenarioPath, objectPath);
5673
- const gte = optionalNumber(record4, "gte", scenarioPath, objectPath);
5674
- const lte = optionalNumber(record4, "lte", scenarioPath, objectPath);
7097
+ const gte = optionalNumber2(record4, "gte", scenarioPath, objectPath);
7098
+ const lte = optionalNumber2(record4, "lte", scenarioPath, objectPath);
7099
+ if (record4.atSteps !== void 0 && (!Array.isArray(record4.atSteps) || record4.atSteps.length === 0)) {
7100
+ throw invalidScenario(scenarioPath, `'${objectPath}.atSteps' must be a non-empty array of expected labeled-step values; an empty one asserts nothing.`);
7101
+ }
7102
+ const atSteps = Array.isArray(record4.atSteps) ? record4.atSteps.map((step, index) => {
7103
+ const stepPath = `${objectPath}.atSteps[${index}]`;
7104
+ 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.`);
7107
+ }
7108
+ return {
7109
+ ...hasKey(entry, "equals") ? { equals: entry.equals } : {},
7110
+ label: requireString(entry, "label", scenarioPath, stepPath),
7111
+ ...present("textIncludes", optionalString(entry, "textIncludes", scenarioPath, stepPath))
7112
+ };
7113
+ }) : void 0;
5675
7114
  return {
5676
- ...Array.isArray(record4.atSteps) ? { atSteps: record4.atSteps.map((step, index) => {
5677
- const entry = requireRecord(step, scenarioPath, `${objectPath}.atSteps[${index}]`);
5678
- return {
5679
- ...hasKey(entry, "equals") ? { equals: entry.equals } : {},
5680
- label: requireString(entry, "label", scenarioPath, `${objectPath}.atSteps[${index}]`),
5681
- ...present("textIncludes", optionalString(entry, "textIncludes", scenarioPath, `${objectPath}.atSteps[${index}]`))
5682
- };
5683
- }) } : {},
7115
+ ...atSteps === void 0 ? {} : { atSteps },
5684
7116
  ...present("changed", optionalBoolean(record4, "changed", scenarioPath, objectPath)),
5685
7117
  ...present("allowTrivial", optionalTrivialityReason(record4, "allowTrivial", scenarioPath, objectPath)),
5686
7118
  ...hasKey(record4, "equals") ? { equals: record4.equals } : {},
@@ -5720,8 +7152,8 @@ function validateResourcePathAlternative(value, scenarioPath, objectPath) {
5720
7152
  const record4 = requireRecord(value, scenarioPath, objectPath);
5721
7153
  rejectUnknownKeys(record4, ["changed", "equals", ...NUMERIC_COMPARISON_KEYS, "path", "textIncludes"], scenarioPath, objectPath);
5722
7154
  const changed = optionalBoolean(record4, "changed", scenarioPath, objectPath);
5723
- const gte = optionalNumber(record4, "gte", scenarioPath, objectPath);
5724
- const lte = optionalNumber(record4, "lte", scenarioPath, objectPath);
7155
+ const gte = optionalNumber2(record4, "gte", scenarioPath, objectPath);
7156
+ const lte = optionalNumber2(record4, "lte", scenarioPath, objectPath);
5725
7157
  const textIncludes = optionalString(record4, "textIncludes", scenarioPath, objectPath);
5726
7158
  if (!hasKey(record4, "equals") && changed === void 0 && gte === void 0 && lte === void 0 && textIncludes === void 0) {
5727
7159
  throw invalidScenario(scenarioPath, `'${objectPath}' must declare equals, gte, lte, textIncludes, or changed.`);
@@ -5741,17 +7173,17 @@ function validateViewport(value, scenarioPath = "scenario") {
5741
7173
  }
5742
7174
  const record4 = requireRecord(value, scenarioPath, "viewport");
5743
7175
  rejectUnknownKeys(record4, ["height", "width"], scenarioPath, "viewport");
5744
- const width = positiveInteger(record4.width);
7176
+ const width = positiveInteger2(record4.width);
5745
7177
  if (width === void 0) {
5746
7178
  throw invalidScenario(scenarioPath, `'viewport.width' must be a positive integer, received ${describeValue(record4.width)}.`);
5747
7179
  }
5748
- const height = positiveInteger(record4.height);
7180
+ const height = positiveInteger2(record4.height);
5749
7181
  if (height === void 0) {
5750
7182
  throw invalidScenario(scenarioPath, `'viewport.height' must be a positive integer, received ${describeValue(record4.height)}.`);
5751
7183
  }
5752
7184
  return { height, width };
5753
7185
  }
5754
- function positiveInteger(value) {
7186
+ function positiveInteger2(value) {
5755
7187
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
5756
7188
  }
5757
7189
  function validateOptionalNumberTuple(value, key, length, scenarioPath, index) {
@@ -5880,7 +7312,7 @@ function validateNestedAssertionKeys(kind, value, scenarioPath, suffix) {
5880
7312
  rejectRenderChainExpectationKeys(value, scenarioPath, `assert.${kind}${suffix}`);
5881
7313
  if (isRecord3(value.perAdapter)) {
5882
7314
  const branchPath = `assert.renderChain${suffix}.perAdapter`;
5883
- rejectUnknownKeys(value.perAdapter, ["hardware", "software"], scenarioPath, branchPath);
7315
+ rejectUnknownKeys(value.perAdapter, [...PLAYTEST_PER_ADAPTER_KEYS], scenarioPath, branchPath);
5884
7316
  for (const [adapterKind, branch] of Object.entries(value.perAdapter)) {
5885
7317
  if (isRecord3(branch)) {
5886
7318
  rejectUnknownKeys(branch, ["contributions", "stages", "tier", "velocity"], scenarioPath, `${branchPath}.${adapterKind}`);
@@ -5913,8 +7345,10 @@ var PLAYTEST_ROOT_KEYS = [
5913
7345
  "inputDelivery",
5914
7346
  "name",
5915
7347
  "parity",
7348
+ "reducedMotion",
5916
7349
  "schemaVersion",
5917
7350
  "setup",
7351
+ "startTick",
5918
7352
  "steps",
5919
7353
  "subject",
5920
7354
  "target",
@@ -5939,6 +7373,9 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
5939
7373
  if (value.awaitStartup !== void 0 && typeof value.awaitStartup !== "boolean") {
5940
7374
  throw invalidScenario(scenarioPath, "Scenario awaitStartup must be a boolean when present.");
5941
7375
  }
7376
+ if (value.startTick !== void 0 && (!Number.isSafeInteger(value.startTick) || value.startTick < 0)) {
7377
+ throw invalidScenario(scenarioPath, "Scenario startTick must be a nonnegative safe integer when present.");
7378
+ }
5942
7379
  if (value.bootFailure !== void 0 && value.bootFailure !== "renderer-no-adapter") {
5943
7380
  throw invalidScenario(scenarioPath, "Scenario bootFailure must be 'renderer-no-adapter' when present.");
5944
7381
  }
@@ -5949,6 +7386,12 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
5949
7386
  if (value.bootFailure !== void 0 && target !== "web") {
5950
7387
  throw invalidScenario(scenarioPath, "Scenario bootFailure is browser-only and requires target 'web'.");
5951
7388
  }
7389
+ if (value.reducedMotion !== void 0 && value.reducedMotion !== "reduce") {
7390
+ throw invalidScenario(scenarioPath, "Scenario reducedMotion must be 'reduce' when present.");
7391
+ }
7392
+ if (value.reducedMotion !== void 0 && target !== "web") {
7393
+ throw invalidScenario(scenarioPath, "Scenario reducedMotion is browser-only and requires target 'web'.");
7394
+ }
5952
7395
  const inputDelivery = value.inputDelivery ?? "deterministic";
5953
7396
  if (inputDelivery !== "deterministic" && inputDelivery !== "focused-dom") {
5954
7397
  throw invalidScenario(scenarioPath, "Scenario inputDelivery must be deterministic or focused-dom.");
@@ -5959,7 +7402,10 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
5959
7402
  if (!Array.isArray(value.steps) || value.steps.length === 0) {
5960
7403
  throw invalidStep(scenarioPath, "Scenario steps[] must contain at least one step.");
5961
7404
  }
5962
- const subject = typeof value.subject === "string" && value.subject.trim() !== "" ? value.subject : void 0;
7405
+ if (value.subject !== void 0 && (typeof value.subject !== "string" || value.subject.trim() === "")) {
7406
+ throw invalidScenario(scenarioPath, "Scenario subject must be a non-empty entity id when present.");
7407
+ }
7408
+ const subject = typeof value.subject === "string" ? value.subject : void 0;
5963
7409
  const steps = value.steps.map((step, index) => validateStep(step, scenarioPath, index));
5964
7410
  if (steps.some(({ kind }) => kind === "aimAt") && subject === void 0) {
5965
7411
  throw invalidScenario(scenarioPath, "A step with kind 'aimAt' aims the subject player start; declare scenario.subject or replace the step.");
@@ -5968,25 +7414,38 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
5968
7414
  validateStepLabels(steps, assertions, scenarioPath);
5969
7415
  return {
5970
7416
  ...typeof value.acceptanceId === "string" ? { acceptanceId: value.acceptanceId } : {},
5971
- ...isRecord3(value.artifacts) ? { artifacts: validateArtifacts(value.artifacts, scenarioPath) } : {},
7417
+ ...value.artifacts === void 0 ? {} : { artifacts: validateArtifacts(requireRecord(value.artifacts, scenarioPath, "artifacts"), scenarioPath) },
5972
7418
  ...assertions === void 0 ? {} : { assert: assertions },
5973
7419
  ...typeof value.awaitStartup === "boolean" ? { awaitStartup: value.awaitStartup } : {},
5974
7420
  ...value.bootFailure === "renderer-no-adapter" ? { bootFailure: value.bootFailure } : {},
5975
7421
  inputDelivery,
5976
7422
  name,
5977
- ...isRecord3(value.parity) ? { parity: validateParityConfig(value.parity, scenarioPath) } : {},
7423
+ ...value.parity === void 0 ? {} : { parity: validateParityConfig(requireRecord(value.parity, scenarioPath, "parity"), scenarioPath) },
7424
+ ...value.reducedMotion === "reduce" ? { reducedMotion: value.reducedMotion } : {},
5978
7425
  schemaVersion: 1,
5979
- ...isRecord3(value.setup) ? { setup: validateSetup(value.setup, scenarioPath, subject) } : {},
7426
+ ...value.setup === void 0 ? {} : { setup: validateSetup(requireRecord(value.setup, scenarioPath, "setup"), scenarioPath, subject) },
5980
7427
  ...absolutePath === void 0 ? {} : { sourcePath: absolutePath },
7428
+ ...value.startTick === void 0 ? {} : { startTick: value.startTick },
5981
7429
  steps,
5982
- ...typeof value.subject === "string" ? { subject: value.subject } : {},
7430
+ ...subject === void 0 ? {} : { subject },
5983
7431
  target,
5984
7432
  viewport: validateViewport(value.viewport, scenarioPath),
5985
- warmupFrames: positiveInteger(value.warmupFrames) ?? 0
7433
+ warmupFrames: optionalNonNegativeInteger(value, "warmupFrames", scenarioPath, "scenario") ?? 0
5986
7434
  };
5987
7435
  }
5988
7436
  function validateArtifacts(value, scenarioPath) {
5989
7437
  rejectUnknownKeys(value, ["console", "contactSheet", "effectLog", "network", "runtimeTrace", "screenshots"], scenarioPath, "artifacts");
7438
+ for (const key of ["console", "contactSheet", "network", "runtimeTrace"]) {
7439
+ optionalBoolean(value, key, scenarioPath, "artifacts");
7440
+ }
7441
+ const effectLog = value.effectLog;
7442
+ if (effectLog !== void 0 && effectLog !== "focused" && typeof effectLog !== "boolean") {
7443
+ throw invalidScenario(scenarioPath, `'artifacts.effectLog' must be true, false or 'focused', received ${describeValue(effectLog)}.`);
7444
+ }
7445
+ const screenshots = value.screenshots;
7446
+ if (screenshots !== void 0 && screenshots !== "before-after" && screenshots !== "after" && typeof screenshots !== "boolean") {
7447
+ throw invalidScenario(scenarioPath, `'artifacts.screenshots' must be 'before-after', 'after', true or false, received ${describeValue(screenshots)}.`);
7448
+ }
5990
7449
  return value;
5991
7450
  }
5992
7451
  function validateParityConfig(value, scenarioPath) {
@@ -6092,9 +7551,9 @@ function validateSpawnRequest(value, scenarioPath) {
6092
7551
  if (value === void 0) return void 0;
6093
7552
  const record4 = requireRecord(value, scenarioPath, "setup.spawn");
6094
7553
  rejectUnknownKeys(record4, ["x", "y", "z"], scenarioPath, "setup.spawn");
6095
- const x = optionalNumber(record4, "x", scenarioPath, "setup.spawn");
6096
- const y = optionalNumber(record4, "y", scenarioPath, "setup.spawn");
6097
- const z = optionalNumber(record4, "z", scenarioPath, "setup.spawn");
7554
+ const x = optionalNumber2(record4, "x", scenarioPath, "setup.spawn");
7555
+ const y = optionalNumber2(record4, "y", scenarioPath, "setup.spawn");
7556
+ const z = optionalNumber2(record4, "z", scenarioPath, "setup.spawn");
6098
7557
  if (x === void 0 || z === void 0) {
6099
7558
  throw invalidScenario(scenarioPath, "'setup.spawn' must define finite x and z; y is optional and preserves the game's current height when absent.");
6100
7559
  }
@@ -6104,8 +7563,8 @@ function validateAimRequest(value, scenarioPath) {
6104
7563
  if (value === void 0) return void 0;
6105
7564
  const record4 = requireRecord(value, scenarioPath, "setup.aim");
6106
7565
  rejectUnknownKeys(record4, ["pitch", "yaw"], scenarioPath, "setup.aim");
6107
- const pitch = optionalNumber(record4, "pitch", scenarioPath, "setup.aim");
6108
- const yaw = optionalNumber(record4, "yaw", scenarioPath, "setup.aim");
7566
+ const pitch = optionalNumber2(record4, "pitch", scenarioPath, "setup.aim");
7567
+ const yaw = optionalNumber2(record4, "yaw", scenarioPath, "setup.aim");
6109
7568
  if (pitch === void 0 || yaw === void 0) {
6110
7569
  throw invalidScenario(scenarioPath, "'setup.aim' must define finite yaw and pitch angles in radians.");
6111
7570
  }
@@ -6130,7 +7589,7 @@ function validatePlaceRequest(value, scenarioPath, index) {
6130
7589
  const facingYaw = record4.facing === void 0 ? void 0 : (() => {
6131
7590
  const facingRecord = requireRecord(record4.facing, scenarioPath, `${objectPath}.facing`);
6132
7591
  rejectUnknownKeys(facingRecord, ["yaw"], scenarioPath, `${objectPath}.facing`);
6133
- const yaw = optionalNumber(facingRecord, "yaw", scenarioPath, `${objectPath}.facing`);
7592
+ const yaw = optionalNumber2(facingRecord, "yaw", scenarioPath, `${objectPath}.facing`);
6134
7593
  if (yaw === void 0) {
6135
7594
  throw invalidScenario(scenarioPath, `'${objectPath}.facing.yaw' must be a finite angle in radians.`);
6136
7595
  }
@@ -6151,9 +7610,9 @@ function validatePlaceRequest(value, scenarioPath, index) {
6151
7610
  function validatePoint(value, scenarioPath, objectPath, requirement) {
6152
7611
  const record4 = requireRecord(value, scenarioPath, objectPath);
6153
7612
  rejectUnknownKeys(record4, ["x", "y", "z"], scenarioPath, objectPath);
6154
- const x = optionalNumber(record4, "x", scenarioPath, objectPath);
6155
- const y = optionalNumber(record4, "y", scenarioPath, objectPath);
6156
- const z = optionalNumber(record4, "z", scenarioPath, objectPath);
7613
+ const x = optionalNumber2(record4, "x", scenarioPath, objectPath);
7614
+ const y = optionalNumber2(record4, "y", scenarioPath, objectPath);
7615
+ const z = optionalNumber2(record4, "z", scenarioPath, objectPath);
6157
7616
  if (x === void 0 || y === void 0 || z === void 0) {
6158
7617
  throw invalidScenario(scenarioPath, `'${objectPath}' must define finite x, y, and z; ${requirement}.`);
6159
7618
  }
@@ -6201,6 +7660,7 @@ var PLAYTEST_STEP_KEYS = [
6201
7660
  "kind",
6202
7661
  "label",
6203
7662
  "lifecycle",
7663
+ "media",
6204
7664
  "overlayMessage",
6205
7665
  "pitch",
6206
7666
  "pointerPosition",
@@ -6223,7 +7683,7 @@ function validateStep(value, scenarioPath, index) {
6223
7683
  }
6224
7684
  rejectUnknownKeys(value, PLAYTEST_STEP_KEYS, scenarioPath, `steps[${index}]`);
6225
7685
  const waitForResource = value.waitForResource === void 0 ? void 0 : validateResourceWait(value.waitForResource, scenarioPath, index);
6226
- const timeoutMs = positiveInteger(value.timeoutMs);
7686
+ const timeoutMs = positiveInteger2(value.timeoutMs);
6227
7687
  if (waitForResource === void 0) {
6228
7688
  if (value.timeoutMs !== void 0) {
6229
7689
  throw invalidStep(scenarioPath, `Scenario step ${index} timeoutMs belongs to waitForResource.`);
@@ -6238,6 +7698,7 @@ function validateStep(value, scenarioPath, index) {
6238
7698
  "holdTicks",
6239
7699
  "kind",
6240
7700
  "lifecycle",
7701
+ "media",
6241
7702
  "overlayMessage",
6242
7703
  "pitch",
6243
7704
  "pointerPosition",
@@ -6267,9 +7728,11 @@ function validateStep(value, scenarioPath, index) {
6267
7728
  y: value.pointerPosition.y
6268
7729
  } : void 0;
6269
7730
  const pointers = Array.isArray(value.pointers) ? value.pointers.map((pointer, pointerIndex) => validatePointer(pointer, scenarioPath, index, pointerIndex)) : void 0;
6270
- const wheel = isRecord3(value.wheel) && typeof value.wheel.deltaY === "number" && Number.isFinite(value.wheel.deltaY) && (value.wheel.deltaX === void 0 || typeof value.wheel.deltaX === "number" && Number.isFinite(value.wheel.deltaX)) ? {
7731
+ const unit = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= 1;
7732
+ const wheel = isRecord3(value.wheel) && typeof value.wheel.deltaY === "number" && Number.isFinite(value.wheel.deltaY) && (value.wheel.deltaX === void 0 || typeof value.wheel.deltaX === "number" && Number.isFinite(value.wheel.deltaX)) && (value.wheel.x === void 0 && value.wheel.y === void 0 || unit(value.wheel.x) && unit(value.wheel.y)) ? {
6271
7733
  ...typeof value.wheel.deltaX === "number" ? { deltaX: value.wheel.deltaX } : {},
6272
- deltaY: value.wheel.deltaY
7734
+ deltaY: value.wheel.deltaY,
7735
+ ...unit(value.wheel.x) && unit(value.wheel.y) ? { x: value.wheel.x, y: value.wheel.y } : {}
6273
7736
  } : void 0;
6274
7737
  if (isRecord3(value.overlayMessage)) {
6275
7738
  rejectUnknownKeys(value.overlayMessage, ["overlayId", "payload", "type"], scenarioPath, `steps[${index}].overlayMessage`);
@@ -6278,15 +7741,16 @@ function validateStep(value, scenarioPath, index) {
6278
7741
  rejectUnknownKeys(value.pointerPosition, ["buttons", "x", "y"], scenarioPath, `steps[${index}].pointerPosition`);
6279
7742
  }
6280
7743
  if (isRecord3(value.wheel)) {
6281
- rejectUnknownKeys(value.wheel, ["deltaX", "deltaY"], scenarioPath, `steps[${index}].wheel`);
7744
+ rejectUnknownKeys(value.wheel, ["deltaX", "deltaY", "x", "y"], scenarioPath, `steps[${index}].wheel`);
6282
7745
  }
7746
+ const media = validateMedia(value.media, scenarioPath, index);
6283
7747
  if (pointers !== void 0 && new Set(pointers.map(({ id }) => id)).size !== pointers.length) {
6284
7748
  throw invalidStep(scenarioPath, `Scenario step ${index} pointers must use unique ids.`);
6285
7749
  }
6286
- const holdFrames = positiveInteger(value.holdFrames);
6287
- const holdTicks = positiveInteger(value.holdTicks);
6288
- const waitFrames = positiveInteger(value.waitFrames);
6289
- const waitTicks = positiveInteger(value.waitTicks);
7750
+ const holdFrames = positiveInteger2(value.holdFrames);
7751
+ const holdTicks = positiveInteger2(value.holdTicks);
7752
+ const waitFrames = positiveInteger2(value.waitFrames);
7753
+ const waitTicks = positiveInteger2(value.waitTicks);
6290
7754
  const kind = value.kind === "aimAt" ? "aimAt" : value.kind === "click" ? "click" : value.kind === "lifecycle" ? "lifecycle" : value.kind === "wait" ? "wait" : value.kind === "input" ? "input" : void 0;
6291
7755
  if (value.kind !== void 0 && kind === void 0) {
6292
7756
  throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'input', 'lifecycle', or 'wait'.`);
@@ -6314,7 +7778,7 @@ function validateStep(value, scenarioPath, index) {
6314
7778
  if (at === void 0) {
6315
7779
  throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'click' must define at as { x, y } or { entity }.`);
6316
7780
  }
6317
- for (const forbidden of ["overlayMessage", "pointerPosition", "pointers", "press", "target", "wheel", "window"]) {
7781
+ for (const forbidden of ["media", "overlayMessage", "pointerPosition", "pointers", "press", "target", "wheel", "window"]) {
6318
7782
  if (value[forbidden] !== void 0) {
6319
7783
  throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'click' cannot define ${forbidden}.`);
6320
7784
  }
@@ -6333,7 +7797,7 @@ function validateStep(value, scenarioPath, index) {
6333
7797
  if (target === void 0) {
6334
7798
  throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'aimAt' must define target as { x, z } or { entity }.`);
6335
7799
  }
6336
- for (const forbidden of ["overlayMessage", "pointerPosition", "pointers", "press", "wheel", "window"]) {
7800
+ for (const forbidden of ["media", "overlayMessage", "pointerPosition", "pointers", "press", "wheel", "window"]) {
6337
7801
  if (value[forbidden] !== void 0) {
6338
7802
  throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'aimAt' cannot define ${forbidden}; apply aim in its own step.`);
6339
7803
  }
@@ -6362,7 +7826,7 @@ function validateStep(value, scenarioPath, index) {
6362
7826
  throw invalidStep(scenarioPath, `Scenario step ${index} pointers must be an array.`);
6363
7827
  }
6364
7828
  if (value.wheel !== void 0 && wheel === void 0) {
6365
- throw invalidStep(scenarioPath, `Scenario step ${index} wheel must define finite deltaY and optional finite deltaX values.`);
7829
+ throw invalidStep(scenarioPath, `Scenario step ${index} wheel must define finite deltaY, optional finite deltaX, and optionally both normalized x and y from 0 through 1.`);
6366
7830
  }
6367
7831
  if (value.screenshot !== void 0 && screenshot === void 0) {
6368
7832
  throw invalidStep(scenarioPath, `Scenario step ${index} screenshot must be a stable file-safe name.`);
@@ -6370,6 +7834,9 @@ function validateStep(value, scenarioPath, index) {
6370
7834
  if (value.label !== void 0 && (typeof value.label !== "string" || value.label.trim() === "")) {
6371
7835
  throw invalidStep(scenarioPath, `Scenario step ${index} label must be a non-empty string.`);
6372
7836
  }
7837
+ if (value.release !== void 0 && typeof value.release !== "boolean") {
7838
+ throw invalidStep(scenarioPath, `Scenario step ${index} release must be a boolean, received ${describeValue(value.release)}.`);
7839
+ }
6373
7840
  if (value.window !== void 0 && window === void 0) {
6374
7841
  throw invalidStep(scenarioPath, `Scenario step ${index} window must define minimize, restore, or resize with positive width and height.`);
6375
7842
  }
@@ -6387,6 +7854,7 @@ function validateStep(value, scenarioPath, index) {
6387
7854
  "holdFrames",
6388
7855
  "holdTicks",
6389
7856
  "label",
7857
+ "media",
6390
7858
  "overlayMessage",
6391
7859
  "pointerPosition",
6392
7860
  "pointers",
@@ -6403,8 +7871,8 @@ function validateStep(value, scenarioPath, index) {
6403
7871
  }
6404
7872
  }
6405
7873
  }
6406
- if (at === void 0 && press === void 0 && overlayMessage === void 0 && pointerPosition === void 0 && pointers === void 0 && wheel === void 0 && window === void 0 && waitFrames === void 0 && waitTicks === void 0 && target === void 0 && waitForResource === void 0 && lifecycle === void 0) {
6407
- throw invalidStep(scenarioPath, `Scenario step ${index} must define click at, press, overlayMessage, pointerPosition, pointers, wheel, window, aimAt target, lifecycle operation, or waitFrames/waitTicks.`);
7874
+ if (at === void 0 && press === void 0 && overlayMessage === void 0 && pointerPosition === void 0 && pointers === void 0 && wheel === void 0 && media === void 0 && window === void 0 && waitFrames === void 0 && waitTicks === void 0 && target === void 0 && waitForResource === void 0 && lifecycle === void 0) {
7875
+ throw invalidStep(scenarioPath, `Scenario step ${index} must define click at, press, overlayMessage, pointerPosition, pointers, wheel, media, window, aimAt target, lifecycle operation, or waitFrames/waitTicks.`);
6408
7876
  }
6409
7877
  if (value.holdFrames !== void 0 && holdFrames === void 0) {
6410
7878
  throw invalidStep(scenarioPath, `Scenario step ${index} holdFrames must be a positive integer.`);
@@ -6434,6 +7902,7 @@ function validateStep(value, scenarioPath, index) {
6434
7902
  ...typeof value.label === "string" ? { label: value.label } : {},
6435
7903
  ...at === void 0 ? {} : { at },
6436
7904
  ...lifecycle === void 0 ? {} : { lifecycle },
7905
+ ...media === void 0 ? {} : { media },
6437
7906
  ...overlayMessage === void 0 ? {} : { overlayMessage },
6438
7907
  ...pitch === void 0 ? {} : { pitch },
6439
7908
  ...pointerPosition === void 0 ? {} : { pointerPosition },
@@ -6450,6 +7919,25 @@ function validateStep(value, scenarioPath, index) {
6450
7919
  ...window === void 0 ? {} : { window }
6451
7920
  };
6452
7921
  }
7922
+ function validateMedia(value, scenarioPath, index) {
7923
+ if (value === void 0) return void 0;
7924
+ if (!isRecord3(value)) throw invalidStep(scenarioPath, `Scenario step ${index} media must be an object.`);
7925
+ rejectUnknownKeys(value, ["colorScheme", "reducedMotion"], scenarioPath, `steps[${index}].media`);
7926
+ const { colorScheme, reducedMotion } = value;
7927
+ if (colorScheme !== void 0 && colorScheme !== "dark" && colorScheme !== "light") {
7928
+ throw invalidStep(scenarioPath, `Scenario step ${index} media.colorScheme must be 'dark' or 'light'.`);
7929
+ }
7930
+ if (reducedMotion !== void 0 && reducedMotion !== "reduce" && reducedMotion !== "no-preference") {
7931
+ throw invalidStep(scenarioPath, `Scenario step ${index} media.reducedMotion must be 'reduce' or 'no-preference'.`);
7932
+ }
7933
+ if (colorScheme === void 0 && reducedMotion === void 0) {
7934
+ throw invalidStep(scenarioPath, `Scenario step ${index} media must set colorScheme or reducedMotion.`);
7935
+ }
7936
+ return {
7937
+ ...colorScheme === void 0 ? {} : { colorScheme },
7938
+ ...reducedMotion === void 0 ? {} : { reducedMotion }
7939
+ };
7940
+ }
6453
7941
  function validateLifecycleStep(value, scenarioPath, index) {
6454
7942
  if (!isRecord3(value)) return void 0;
6455
7943
  const rotation = value.rotation;
@@ -6478,8 +7966,8 @@ function validateResourceWait(value, scenarioPath, index) {
6478
7966
  if (Number(hasEquals) + Number(hasGte) + Number(hasLte) !== 1) {
6479
7967
  throw invalidStep(scenarioPath, `Scenario step ${index} waitForResource must define exactly one of equals, gte, or lte.`);
6480
7968
  }
6481
- const gte = hasGte ? optionalNumber(value, "gte", scenarioPath, objectPath) : void 0;
6482
- const lte = hasLte ? optionalNumber(value, "lte", scenarioPath, objectPath) : void 0;
7969
+ const gte = hasGte ? optionalNumber2(value, "gte", scenarioPath, objectPath) : void 0;
7970
+ const lte = hasLte ? optionalNumber2(value, "lte", scenarioPath, objectPath) : void 0;
6483
7971
  if (hasGte && gte === void 0) {
6484
7972
  throw invalidStep(scenarioPath, `Scenario step ${index} waitForResource.gte must be a finite number.`);
6485
7973
  }
@@ -6506,6 +7994,18 @@ function validateClickTarget(value, scenarioPath, index) {
6506
7994
  return value.entity.length === 0 ? void 0 : { entity: value.entity };
6507
7995
  }
6508
7996
  if (value.entity !== void 0) return void 0;
7997
+ if (value.element !== void 0) {
7998
+ const objectPath = `steps[${index}].at`;
7999
+ rejectUnknownKeys(value, ["element"], scenarioPath, objectPath);
8000
+ const element = requireRecord(value.element, scenarioPath, `${objectPath}.element`);
8001
+ rejectUnknownKeys(element, ["id", "selector"], scenarioPath, `${objectPath}.element`);
8002
+ const id = optionalString(element, "id", scenarioPath, `${objectPath}.element`);
8003
+ const selector = optionalString(element, "selector", scenarioPath, `${objectPath}.element`);
8004
+ if (id === void 0 === (selector === void 0)) {
8005
+ throw invalidStep(scenarioPath, `Scenario ${objectPath}.element must name exactly one of id or selector.`);
8006
+ }
8007
+ return { element: id === void 0 ? { selector } : { id } };
8008
+ }
6509
8009
  rejectUnknownKeys(value, ["x", "y"], scenarioPath, `steps[${index}].at`);
6510
8010
  return typeof value.x === "number" && Number.isFinite(value.x) && value.x >= 0 && typeof value.y === "number" && Number.isFinite(value.y) && value.y >= 0 ? { x: value.x, y: value.y } : void 0;
6511
8011
  }
@@ -6523,8 +8023,8 @@ function validateAimTarget(value, scenarioPath, stepIndex) {
6523
8023
  return { entity: requireString(value, "entity", scenarioPath, objectPath) };
6524
8024
  }
6525
8025
  rejectUnknownKeys(value, ["x", "z"], scenarioPath, objectPath);
6526
- const x = optionalNumber(value, "x", scenarioPath, objectPath);
6527
- const z = optionalNumber(value, "z", scenarioPath, objectPath);
8026
+ const x = optionalNumber2(value, "x", scenarioPath, objectPath);
8027
+ const z = optionalNumber2(value, "z", scenarioPath, objectPath);
6528
8028
  if (x === void 0 || z === void 0) {
6529
8029
  throw invalidStep(scenarioPath, `Scenario ${objectPath} must define finite x and z world coordinates.`);
6530
8030
  }
@@ -6578,6 +8078,9 @@ function validateStepLabels(steps, assertions, scenarioPath) {
6578
8078
  requireLabel(step.label, `assert.components[${index}].atSteps[${stepIndex}].label`);
6579
8079
  }
6580
8080
  }
8081
+ for (const [index, assertion] of (assertions.tone ?? []).entries()) {
8082
+ requireLabel(assertion.atStep, `assert.tone[${index}].atStep`);
8083
+ }
6581
8084
  for (const [index, assertion] of (assertions.signals ?? []).entries()) {
6582
8085
  requireLabel(assertion.atStep, `assert.signals[${index}].atStep`);
6583
8086
  }
@@ -6618,7 +8121,13 @@ function validateAssertions(value, scenarioPath) {
6618
8121
  if (Array.isArray(value.signals) && value.signals.length === 0) {
6619
8122
  throw invalidScenario(scenarioPath, "Assertion 'assert.signals' must contain at least one signal assertion.");
6620
8123
  }
8124
+ if (Array.isArray(value.tone) && value.tone.length === 0) {
8125
+ throw invalidScenario(scenarioPath, "Assertion 'assert.tone' must contain at least one tone assertion.");
8126
+ }
6621
8127
  const movement = isRecord3(value.movement) ? value.movement : void 0;
8128
+ if (movement !== void 0) {
8129
+ validateMovementBounds(movement, scenarioPath);
8130
+ }
6622
8131
  const camera = isRecord3(value.camera) ? value.camera : void 0;
6623
8132
  if (camera !== void 0 && !(typeof camera.within === "number" && Number.isFinite(camera.within) || camera.targetInViewport === true)) {
6624
8133
  throw invalidScenario(
@@ -6637,6 +8146,7 @@ function validateAssertions(value, scenarioPath) {
6637
8146
  ) : void 0;
6638
8147
  const renderChain = value.renderChain === void 0 ? void 0 : validateRenderChainAssertion(value.renderChain, scenarioPath, "assert.renderChain");
6639
8148
  const startup = value.startup === void 0 ? void 0 : validateStartupAssertion(value.startup, scenarioPath, "assert.startup");
8149
+ const pipelineCensus = value.pipelineCensus === void 0 ? void 0 : validatePipelineCensusAssertion(value.pipelineCensus, scenarioPath, "assert.pipelineCensus");
6640
8150
  const scene = value.scene === void 0 ? void 0 : validateSceneAssertion(value.scene, scenarioPath, "assert.scene");
6641
8151
  const geometry = value.geometry === void 0 ? void 0 : validateGeometryCaptureRequest(value.geometry, scenarioPath, "assert.geometry");
6642
8152
  const world = isRecord3(value.world) ? value.world : void 0;
@@ -6688,6 +8198,7 @@ function validateAssertions(value, scenarioPath) {
6688
8198
  ...performance === void 0 ? {} : { performance },
6689
8199
  ...renderChain === void 0 ? {} : { renderChain },
6690
8200
  ...startup === void 0 ? {} : { startup },
8201
+ ...pipelineCensus === void 0 ? {} : { pipelineCensus },
6691
8202
  ...scene === void 0 ? {} : { scene },
6692
8203
  ...geometry === void 0 ? {} : { geometry },
6693
8204
  ...hasKey(value, "causedBy") ? {
@@ -6745,10 +8256,30 @@ function validateAssertions(value, scenarioPath) {
6745
8256
  ...Array.isArray(value.states) ? { states: value.states.map((entry, index) => validateStateAssertion(entry, scenarioPath, `assert.states[${index}]`)) } : {},
6746
8257
  ...Array.isArray(value.tags) ? { tags: value.tags.map((entry, index) => validateTagCountAssertion(entry, scenarioPath, `assert.tags[${index}]`)) } : {},
6747
8258
  ...Array.isArray(value.visibility) ? { visibility: value.visibility.map((entry, index) => validateVisibilityAssertion(entry, scenarioPath, `assert.visibility[${index}]`)) } : {},
8259
+ ...Array.isArray(value.tone) ? { tone: value.tone.map((entry, index) => validateToneAssertion(entry, scenarioPath, `assert.tone[${index}]`)) } : {},
6748
8260
  ...Array.isArray(value.visual) ? { visual: value.visual.map((entry, index) => validateVisualAssertion(entry, scenarioPath, `assert.visual[${index}]`)) } : {},
6749
8261
  ...world === void 0 ? {} : { world: validateWorldAssertion(world, scenarioPath) }
6750
8262
  };
6751
8263
  }
8264
+ function validateMovementBounds(movement, scenarioPath) {
8265
+ for (const [key, unit] of [["maxDistance", "a non-negative distance"], ["pathLength", "a non-negative distance"]]) {
8266
+ const raw = movement[key];
8267
+ if (raw !== void 0 && (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0)) {
8268
+ throw invalidScenario(scenarioPath, `Assertion 'assert.movement.${key}' must be ${unit}, received ${describeValue(raw)}.`);
8269
+ }
8270
+ }
8271
+ for (const key of ["closesDistanceToPosition", "minAxisDelta", "minResolvedAxisDelta", "notFacing", "notFacingPosition", "reachesPositionWithin"]) {
8272
+ if (movement[key] !== void 0) {
8273
+ requireRecord(movement[key], scenarioPath, `assert.movement.${key}`);
8274
+ }
8275
+ }
8276
+ if (movement.rotationChanged === false) {
8277
+ throw invalidScenario(
8278
+ scenarioPath,
8279
+ "assert.movement.rotationChanged may only be true; remove the key to stop requiring rotation."
8280
+ );
8281
+ }
8282
+ }
6752
8283
  function validateAudioAssertion(value, scenarioPath, objectPath) {
6753
8284
  const record4 = requireRecord(value, scenarioPath, objectPath);
6754
8285
  rejectUnknownKeys(record4, ["cue", "maxPlays", "minGapMs", "minPlays"], scenarioPath, objectPath);
@@ -6790,7 +8321,7 @@ function validateWorldAssertion(value, scenarioPath) {
6790
8321
  if (portable !== void 0 && typeof portable !== "boolean") {
6791
8322
  throw invalidScenario(scenarioPath, "'assert.world.runtime.portable' must be a boolean.");
6792
8323
  }
6793
- const randomState = optionalNumber(runtime, "randomState", scenarioPath, "assert.world.runtime");
8324
+ const randomState = optionalNumber2(runtime, "randomState", scenarioPath, "assert.world.runtime");
6794
8325
  if (randomState === void 0 || !Number.isInteger(randomState)) {
6795
8326
  throw invalidScenario(scenarioPath, "'assert.world.runtime.randomState' must be an integer.");
6796
8327
  }
@@ -6876,8 +8407,8 @@ function validateComponentAssertion(value, scenarioPath, objectPath) {
6876
8407
  ...present("allowTrivial", optionalTrivialityReason(record4, "allowTrivial", scenarioPath, objectPath)),
6877
8408
  // As above: any JSON value is a legal comparison target.
6878
8409
  ...hasKey(record4, "equals") ? { equals: record4.equals } : {},
6879
- ...present("gte", optionalNumber(record4, "gte", scenarioPath, objectPath)),
6880
- ...present("lte", optionalNumber(record4, "lte", scenarioPath, objectPath)),
8410
+ ...present("gte", optionalNumber2(record4, "gte", scenarioPath, objectPath)),
8411
+ ...present("lte", optionalNumber2(record4, "lte", scenarioPath, objectPath)),
6881
8412
  ...present("path", optionalString(record4, "path", scenarioPath, objectPath))
6882
8413
  };
6883
8414
  }
@@ -6961,6 +8492,60 @@ function validateGeometryCaptureRequest(value, scenarioPath, objectPath) {
6961
8492
  ...record4.timeoutMs === void 0 ? {} : { timeoutMs: record4.timeoutMs }
6962
8493
  };
6963
8494
  }
8495
+ function validateToneAssertion(value, scenarioPath, objectPath) {
8496
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8497
+ rejectUnknownKeys(record4, ["atStep", "region", "compare", ...TONE_METRICS], scenarioPath, objectPath);
8498
+ const result = {};
8499
+ if (record4.region !== void 0) result.region = validateToneRegion(record4.region, scenarioPath, `${objectPath}.region`);
8500
+ if (record4.compare !== void 0) {
8501
+ if (result.region === void 0) throw invalidScenario(scenarioPath, `${objectPath}.compare requires region.`);
8502
+ const compare = requireRecord(record4.compare, scenarioPath, `${objectPath}.compare`);
8503
+ rejectUnknownKeys(compare, ["region", "metric", "minDelta"], scenarioPath, `${objectPath}.compare`);
8504
+ if (!TONE_METRICS.includes(compare.metric)) throw invalidScenario(scenarioPath, `${objectPath}.compare.metric is unsupported.`);
8505
+ const metric = compare.metric;
8506
+ const maximum = metric.endsWith("Fraction") ? 1 : 255;
8507
+ if (typeof compare.minDelta !== "number" || !Number.isFinite(compare.minDelta) || Math.abs(compare.minDelta) > maximum) throw invalidScenario(scenarioPath, `${objectPath}.compare.minDelta must be finite in [-${maximum}, ${maximum}].`);
8508
+ result.compare = { region: validateToneRegion(compare.region, scenarioPath, `${objectPath}.compare.region`), metric, minDelta: compare.minDelta };
8509
+ }
8510
+ if (record4.atStep !== void 0) result.atStep = requireString(record4, "atStep", scenarioPath, objectPath);
8511
+ for (const metric of TONE_METRICS) {
8512
+ if (record4[metric] === void 0) continue;
8513
+ const path = `${objectPath}.${metric}`;
8514
+ const bound = requireRecord(record4[metric], scenarioPath, path);
8515
+ rejectUnknownKeys(bound, ["min", "max"], scenarioPath, path);
8516
+ if (bound.min === void 0 && bound.max === void 0) throw invalidScenario(scenarioPath, `${path} requires min or max.`);
8517
+ const maximum = metric.endsWith("Fraction") ? 1 : 255;
8518
+ for (const key of ["min", "max"]) {
8519
+ if (bound[key] !== void 0 && (typeof bound[key] !== "number" || !Number.isFinite(bound[key]) || bound[key] < 0 || bound[key] > maximum)) {
8520
+ throw invalidScenario(scenarioPath, `${path}.${key} must be a finite number in [0, ${maximum}].`);
8521
+ }
8522
+ }
8523
+ if (typeof bound.min === "number" && typeof bound.max === "number" && bound.min > bound.max) {
8524
+ throw invalidScenario(scenarioPath, `${path}: min must not exceed max.`);
8525
+ }
8526
+ result[metric] = { ...present("min", bound.min), ...present("max", bound.max) };
8527
+ }
8528
+ if (result.compare === void 0 && !TONE_METRICS.some((key) => result[key] !== void 0)) throw invalidScenario(scenarioPath, `${objectPath} requires at least one metric bound.`);
8529
+ return result;
8530
+ }
8531
+ function validateToneRegion(value, scenarioPath, objectPath) {
8532
+ const record4 = requireRecord(value, scenarioPath, objectPath);
8533
+ rejectUnknownKeys(record4, ["x", "y", "width", "height"], scenarioPath, objectPath);
8534
+ for (const key of ["x", "y", "width", "height"]) {
8535
+ const minimum = key === "x" || key === "y" ? 0 : 1;
8536
+ if (typeof record4[key] !== "number" || !Number.isSafeInteger(record4[key]) || record4[key] < minimum)
8537
+ throw invalidScenario(
8538
+ scenarioPath,
8539
+ `${objectPath}.${key} must be a safe integer >= ${minimum}.`
8540
+ );
8541
+ }
8542
+ return {
8543
+ x: record4.x,
8544
+ y: record4.y,
8545
+ width: record4.width,
8546
+ height: record4.height
8547
+ };
8548
+ }
6964
8549
 
6965
8550
  // src/scenario.ts
6966
8551
  async function loadPlaytestScenario(projectPath, scenarioPath) {