@threenative/playtest 0.3.3 → 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);
@@ -242,7 +247,24 @@ function formatNumber(value) {
242
247
  return Number.isInteger(value) ? String(value) : value.toFixed(3);
243
248
  }
244
249
  function jsonEqual(left, right) {
245
- return JSON.stringify(left) === JSON.stringify(right);
250
+ return JSON.stringify(sortedKeys(left)) === JSON.stringify(sortedKeys(right));
251
+ }
252
+ function sortedKeys(value) {
253
+ if (Array.isArray(value)) {
254
+ return value.map(sortedKeys);
255
+ }
256
+ if (!isRecord(value)) {
257
+ return value;
258
+ }
259
+ const prototype = Object.getPrototypeOf(value);
260
+ if (prototype !== Object.prototype && prototype !== null) {
261
+ return value;
262
+ }
263
+ const sorted = {};
264
+ for (const key of Object.keys(value).sort()) {
265
+ sorted[key] = sortedKeys(value[key]);
266
+ }
267
+ return sorted;
246
268
  }
247
269
  function isRecord(value) {
248
270
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -250,6 +272,24 @@ function isRecord(value) {
250
272
 
251
273
  // src/assertion-schema.ts
252
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
+ },
253
293
  {
254
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.",
255
295
  example: { deviceMetrics: { maxTemperatureRiseC: 5, notThermallyConfounded: true } },
@@ -553,7 +593,7 @@ var PLAYTEST_ASSERTION_REGISTRY = [
553
593
  observationPath: "runtimeDiagnostics",
554
594
  requiredCapabilities: ["browser.console", "browser.network", "runtime.diagnostics"],
555
595
  resultIdPrefix: "diagnostics",
556
- supportedOn: ["web"],
596
+ supportedOn: ["web", "desktop"],
557
597
  triviality: "not-applicable",
558
598
  trivialityRationale: "It evaluates captured error and readiness channels across the run; no initial scalar value can satisfy those diagnostics by itself."
559
599
  },
@@ -816,6 +856,25 @@ var PLAYTEST_ASSERTION_REGISTRY = [
816
856
  triviality: "not-applicable",
817
857
  trivialityRationale: "The timeline is stamped by the runtime as milestones happen; a missing milestone fails the ceiling rather than passing it."
818
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
+ },
819
878
  {
820
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.",
821
880
  example: { renderChain: { tier: "high", stages: { includes: ["outline", "kuwahara", "watercolor"], order: ["outline", "kuwahara", "watercolor"] }, contributions: { graphOutputChanged: ["outline", "kuwahara", "watercolor"] } } },
@@ -823,7 +882,8 @@ var PLAYTEST_ASSERTION_REGISTRY = [
823
882
  { description: "Exact render-chain quality tier required after the chain applies.", name: "tier", type: "string" },
824
883
  { description: "Stage ids to include, exclude, or find as an ordered subsequence in the applied chain.", name: "stages", type: "object" },
825
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" },
826
- { description: "Temporal history rejection ceiling as a fraction from 0 to 1.", name: "velocity", type: "object" }
885
+ { description: "Temporal history rejection ceiling as a fraction from 0 to 1.", name: "velocity", 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" }
827
887
  ],
828
888
  cardinality: "object",
829
889
  kind: "renderChain",
@@ -864,6 +924,7 @@ var PLAYTEST_SETUP_REGISTRY = [
864
924
  ];
865
925
  function requiredPlaytestCapabilities(scenario, target) {
866
926
  const required = /* @__PURE__ */ new Set();
927
+ if (scenario.startTick !== void 0) required.add("runtime.fixedStep");
867
928
  if (scenario.steps.some((step) => step.waitForResource !== void 0)) {
868
929
  required.add("runtime.resources");
869
930
  }
@@ -884,13 +945,14 @@ function requiredPlaytestCapabilities(scenario, target) {
884
945
  if (entry.kind === "diagnostics") {
885
946
  const policy = resolveDiagnosticsPolicy(scenario.assert.diagnostics, target);
886
947
  if (policy.noConsoleErrors) required.add("browser.console");
887
- if (policy.noNetworkErrors) required.add("browser.network");
948
+ if (policy.noNetworkErrors) required.add(target === "desktop" ? "runtime.network" : "browser.network");
888
949
  if (policy.noRuntimeDiagnostics) required.add("runtime.diagnostics");
889
950
  } else {
890
951
  entry.requiredCapabilities.forEach((capability2) => required.add(capability2));
891
952
  }
892
953
  }
893
954
  }
955
+ if (target === "desktop" && resolveDiagnosticsPolicy(scenario.assert?.diagnostics, target).noNetworkErrors) required.add("runtime.network");
894
956
  for (const entry of PLAYTEST_SETUP_REGISTRY) {
895
957
  if (scenario.setup?.[entry.kind] !== void 0) {
896
958
  entry.requiredCapabilities.forEach((capability2) => required.add(capability2));
@@ -899,6 +961,87 @@ function requiredPlaytestCapabilities(scenario, target) {
899
961
  return [...required].sort();
900
962
  }
901
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
+
902
1045
  // src/evaluators/device-metrics.ts
903
1046
  function emitDeviceMetrics(ctx) {
904
1047
  const assertion = ctx.scenarioAssertions.deviceMetrics;
@@ -1293,6 +1436,14 @@ function evaluateDiagnosticsPolicy(report, policy) {
1293
1436
  suggestion: "Inspect runtime diagnostics and bundle validation output before replaying the scenario."
1294
1437
  });
1295
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
+ }
1296
1447
  const capturedConsoleErrors = consoleErrors(report.observations?.console ?? []);
1297
1448
  if (policy.noConsoleErrors && capturedConsoleErrors.length > 0) {
1298
1449
  diagnostics.push({
@@ -1341,6 +1492,14 @@ function projectedOffscreenRatio(min, max) {
1341
1492
  const visibleHeight = Math.max(0, Math.min(max[1], 1) - Math.max(min[1], -1));
1342
1493
  return 1 - Math.max(0, visibleWidth * visibleHeight) / area;
1343
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
+ }
1344
1503
  function hasNativeReadinessSamples(runtimeDiagnosticsValue) {
1345
1504
  return isRecord(runtimeDiagnosticsValue) && Array.isArray(runtimeDiagnosticsValue.readiness);
1346
1505
  }
@@ -1357,7 +1516,7 @@ function evaluateVisibilityAssertion(assertion, entity, viewport, runtimeDiagnos
1357
1516
  const initialBounds = isRecord(initialRendered?.projectedBounds) ? initialRendered.projectedBounds : void 0;
1358
1517
  const initialMin = Array.isArray(initialBounds?.min) ? initialBounds.min : void 0;
1359
1518
  const initialMax = Array.isArray(initialBounds?.max) ? initialBounds.max : void 0;
1360
- 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);
1361
1520
  const initialOffscreenRatio = initialMin === void 0 || initialMax === void 0 ? void 0 : projectedOffscreenRatio([Number(initialMin[0]), Number(initialMin[1])], [Number(initialMax[0]), Number(initialMax[1])]);
1362
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);
1363
1522
  const guarded = (comparisonPass, details, failure) => {
@@ -1405,7 +1564,7 @@ function evaluateVisibilityAssertion(assertion, entity, viewport, runtimeDiagnos
1405
1564
  const bounds = isRecord(rendered?.projectedBounds) ? rendered.projectedBounds : void 0;
1406
1565
  const min = Array.isArray(bounds?.min) ? bounds.min : void 0;
1407
1566
  const max = Array.isArray(bounds?.max) ? bounds.max : void 0;
1408
- 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);
1409
1568
  const offscreenRatio = min === void 0 || max === void 0 ? void 0 : projectedOffscreenRatio([Number(min[0]), Number(min[1])], [Number(max[0]), Number(max[1])]);
1410
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);
1411
1570
  return guarded(pass, { entity, maxOffscreenRatio, minProjectedPixels, offscreenRatio, present: present2, projectedPixels }, {
@@ -1558,7 +1717,7 @@ function evaluateAudioAssertion(assertion, observations) {
1558
1717
  const minimum = assertion.minPlays ?? 1;
1559
1718
  const recent = Array.isArray(audio?.recentCues) ? audio.recentCues : [];
1560
1719
  const gap = smallestGapBefore(recent, assertion.cue);
1561
- 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;
1562
1721
  const pass = cues !== void 0 && plays >= minimum && (assertion.maxPlays === void 0 || plays <= assertion.maxPlays) && gapPass;
1563
1722
  const result = {
1564
1723
  details: {
@@ -1576,7 +1735,7 @@ function evaluateAudioAssertion(assertion, observations) {
1576
1735
  assertion: result,
1577
1736
  diagnostic: {
1578
1737
  code: "TN_PLAYTEST_AUDIO_ASSERTION_FAILED",
1579
- 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.`,
1580
1739
  observedRuntimePath: "observations.json/runtimeObservations/gameplay/audio/cues",
1581
1740
  severity: "error",
1582
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."
@@ -1801,7 +1960,7 @@ function projectedPixelsForEntity(snapshot, entity, viewport) {
1801
1960
  const bounds = isRecord(rendered?.projectedBounds) ? rendered.projectedBounds : void 0;
1802
1961
  const min = Array.isArray(bounds?.min) ? bounds.min : void 0;
1803
1962
  const max = Array.isArray(bounds?.max) ? bounds.max : void 0;
1804
- 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);
1805
1964
  }
1806
1965
  function countMatchingEntries(effectLog, tokens) {
1807
1966
  if (tokens.length === 0 || !isRecord(effectLog) || !Array.isArray(effectLog.entries)) {
@@ -1820,7 +1979,6 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
1820
1979
  const drawCalls = observed.flatMap(({ drawCalls: value }) => value === void 0 ? [] : [value]);
1821
1980
  const triangles = observed.flatMap(({ triangles: value }) => value === void 0 ? [] : [value]);
1822
1981
  const frameMsP95 = nearestRank(frameTimes, 0.95);
1823
- const frameMsP50 = nearestRank(frameTimes, 0.5);
1824
1982
  const maxObservedDrawCalls = drawCalls.length === 0 ? void 0 : Math.max(...drawCalls);
1825
1983
  const maxObservedTriangles = triangles.length === 0 ? void 0 : Math.max(...triangles);
1826
1984
  const results = [];
@@ -1872,8 +2030,9 @@ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
1872
2030
  );
1873
2031
  }
1874
2032
  if (assertion.minFps !== void 0) {
1875
- const observed2 = frameMsP50 === void 0 || frameMsP50 <= 0 ? void 0 : Math.round(1e3 / frameMsP50 * 100) / 100;
1876
- 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;
1877
2036
  results.push({
1878
2037
  details: { actual: observed2 ?? null, expected: assertion.minFps, sampleCount: samples.length, unit: "fps" },
1879
2038
  id: "performance.minFps",
@@ -1969,6 +2128,10 @@ function nearestRank(values, percentile) {
1969
2128
  const sorted = [...values].sort((left, right) => left - right);
1970
2129
  return sorted[Math.max(0, Math.ceil(values.length * percentile) - 1)];
1971
2130
  }
2131
+ function fpsFromFrameTimes(frameTimes) {
2132
+ const frameMs = nearestRank(frameTimes, 0.5);
2133
+ return frameMs === void 0 || frameMs <= 0 ? void 0 : 1e3 / frameMs;
2134
+ }
1972
2135
  function mergeEffectLogs(effectLog, series) {
1973
2136
  return {
1974
2137
  entries: [effectLog, ...(series ?? []).map((sample) => sample.snapshot)].flatMap((log) => isRecord(log) && Array.isArray(log.entries) ? log.entries : [])
@@ -2337,14 +2500,15 @@ function emitMovementEvidence(ctx) {
2337
2500
  }
2338
2501
  if (scenarioAssertions.movement?.minVelocity !== void 0) {
2339
2502
  const velocity = input.report.frames <= 0 ? 0 : input.report.distance / input.report.frames;
2340
- const pass = velocity >= scenarioAssertions.movement.minVelocity;
2341
- 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 });
2342
2506
  if (!pass) {
2343
2507
  diagnostics.push({
2344
2508
  code: "TN_PLAYTEST_VELOCITY_ASSERTION_FAILED",
2345
- 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.`,
2346
2510
  severity: "error",
2347
- 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."
2348
2512
  });
2349
2513
  }
2350
2514
  }
@@ -2386,14 +2550,15 @@ function emitMovementEvidence(ctx) {
2386
2550
  }
2387
2551
  if (scenarioAssertions.movement?.pathLength !== void 0) {
2388
2552
  const pathLength = input.report.pathLength ?? input.report.distance;
2389
- const pass = pathLength >= scenarioAssertions.movement.pathLength;
2390
- 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 });
2391
2556
  if (!pass) {
2392
2557
  diagnostics.push({
2393
2558
  code: "TN_PLAYTEST_PATH_LENGTH_ASSERTION_FAILED",
2394
- 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.`,
2395
2560
  severity: "error",
2396
- 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."
2397
2562
  });
2398
2563
  }
2399
2564
  }
@@ -2973,8 +3138,7 @@ function emitParity(ctx) {
2973
3138
  });
2974
3139
  return;
2975
3140
  }
2976
- const median = (values) => [...values].sort((left, right) => left - right)[Math.floor(values.length / 2)];
2977
- const thisFps = 1e3 / median(frameTimes);
3141
+ const thisFps = fpsFromFrameTimes(frameTimes);
2978
3142
  const ratio = assertion.referenceSide === "native" ? reference.fps / thisFps : thisFps / reference.fps;
2979
3143
  assertions.push({
2980
3144
  details: { referenceFps: reference.fps, referenceSide: assertion.referenceSide, ratio, unit: "ratio" },
@@ -3264,11 +3428,10 @@ function emitWorldGameplay(ctx) {
3264
3428
  ];
3265
3429
  const checks = [
3266
3430
  ...valueChecks,
3267
- // Same absent-value trap as evaluatePathAssertion: a component that was
3268
- // never observed must not satisfy "this value did not change".
3269
- ...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))]
3270
3433
  ];
3271
- 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);
3272
3435
  const pass = checks.length > 0 && checks.every(Boolean) && (!trivial || typeof assertion.allowTrivial === "string");
3273
3436
  assertions.push({
3274
3437
  details: {
@@ -3767,34 +3930,131 @@ function emitWorldTopology(value, assertions, diagnostics) {
3767
3930
  }
3768
3931
  }
3769
3932
 
3933
+ // src/runner/browser.ts
3934
+ [
3935
+ "--ozone-platform=x11",
3936
+ "--enable-unsafe-webgpu",
3937
+ "--disable-gpu-sandbox",
3938
+ "--ignore-gpu-blocklist",
3939
+ // Keep Vulkan available on both hardware and software adapters.
3940
+ "--enable-features=Vulkan",
3941
+ // Forced ANGLE/Vulkan selects NVIDIA locally but breaks hosted software adapters, especially headed.
3942
+ // Apply that workaround only when the caller explicitly requests the host display.
3943
+ ...typeof process !== "undefined" && process.env.TN_PLAYTEST_HOST_DISPLAY === "1" ? ["--use-angle=vulkan", "--use-vulkan", "--disable-vulkan-surface"] : []
3944
+ ];
3945
+ var SOFTWARE_ADAPTER = /swiftshader|llvmpipe|lavapipe|softwarerasterizer|software adapter|basic render/i;
3946
+ function softwareAdapterName(adapter) {
3947
+ if (adapter === void 0) return void 0;
3948
+ for (const value of Object.values(adapter)) {
3949
+ if (typeof value === "string" && SOFTWARE_ADAPTER.test(value)) return value;
3950
+ }
3951
+ return void 0;
3952
+ }
3953
+
3954
+ // src/evaluators/adapter-class.ts
3955
+ function classifyAdapter(report) {
3956
+ const capture = report.capture;
3957
+ if (capture === void 0 || capture.rendererKind !== "webgpu") return {};
3958
+ if (adapterIdentity(capture.adapter) === void 0) return {};
3959
+ const software = softwareAdapterName(capture.adapter);
3960
+ if (software !== void 0) return { adapterClass: "software", softwareAdapter: software };
3961
+ const gpuFamily = gpuFamilyOf(capture.adapter);
3962
+ return gpuFamily === void 0 ? { adapterClass: "hardware" } : { adapterClass: "hardware", gpuFamily };
3963
+ }
3964
+ var ADAPTER_IDENTITY_KEYS = ["architecture", "description", "device", "vendor"];
3965
+ function adapterIdentity(adapter) {
3966
+ if (adapter === void 0) return void 0;
3967
+ for (const key of ADAPTER_IDENTITY_KEYS) {
3968
+ const value = adapter[key];
3969
+ if (typeof value === "string" && value.trim() !== "") return value;
3970
+ }
3971
+ return void 0;
3972
+ }
3973
+ var MALI_MODEL = /\bmali[\s_-]*g?[\s-]*(\d{2,3})/i;
3974
+ var ADRENO_MODEL = /\badreno\W*(?:tm\W*)?(\d)(\d\d|xx)/i;
3975
+ var AMD_INTEGRATED = /radeon(?:\(tm\))?\s+(?:graphics|\d{3}m)\b/i;
3976
+ var INTEL_DISCRETE = /\barc\b|xe2?-hpg|battlemage|alchemist/i;
3977
+ var FAMILY_RULES = [
3978
+ ({ architecture, description, device }) => {
3979
+ const number = [description, device, architecture].map((value) => MALI_MODEL.exec(value)?.[1]).find((value) => value !== void 0);
3980
+ if (number === void 0) return void 0;
3981
+ const model = Number(number);
3982
+ if (model >= 710) return "mobile-high";
3983
+ return model < 57 || model === 71 || model === 72 ? "mobile-low" : "mobile-mid";
3984
+ },
3985
+ ({ architecture, vendor }) => {
3986
+ if (!/\barm\b/i.test(vendor)) return void 0;
3987
+ if (/midgard|bifrost/i.test(architecture)) return "mobile-low";
3988
+ if (/valhall/i.test(architecture)) return "mobile-mid";
3989
+ return /5th-?gen|immortalis/i.test(architecture) ? "mobile-high" : void 0;
3990
+ },
3991
+ ({ architecture, description, device }) => {
3992
+ const match = [description, device, architecture].map((value) => ADRENO_MODEL.exec(value)).find((value) => value !== null && value !== void 0);
3993
+ if (match === null || match === void 0) return void 0;
3994
+ const generation = Number(match[1]);
3995
+ if (generation <= 4) return "mobile-low";
3996
+ if (generation === 5) return "mobile-mid";
3997
+ if (generation === 6) return match[2] !== "xx" && Number(match[2]) >= 30 ? "mobile-high" : "mobile-mid";
3998
+ return "mobile-high";
3999
+ },
4000
+ ({ architecture, description, device, vendor }) => /nvidia/i.test(vendor) && ![architecture, description, device].some((value) => /tegra/i.test(value)) ? "discrete" : void 0,
4001
+ ({ architecture, description, device, vendor }) => {
4002
+ if (!/intel/i.test(vendor)) return void 0;
4003
+ return [architecture, description, device].some((value) => INTEL_DISCRETE.test(value)) ? "discrete" : "integrated";
4004
+ },
4005
+ // An APU and a card share an architecture name, so an AMD adapter that names no iGPU is `discrete`.
4006
+ ({ description, vendor }) => /\b(?:amd|ati)\b/i.test(vendor) ? AMD_INTEGRATED.test(description) ? "integrated" : "discrete" : void 0
4007
+ ];
4008
+ function gpuFamilyOf(adapter) {
4009
+ if (adapter === void 0) return void 0;
4010
+ const field = (key) => {
4011
+ const value = adapter[key];
4012
+ return typeof value === "string" ? value : "";
4013
+ };
4014
+ const fields = {
4015
+ architecture: field("architecture"),
4016
+ description: field("description"),
4017
+ device: field("device"),
4018
+ vendor: field("vendor")
4019
+ };
4020
+ for (const rule of FAMILY_RULES) {
4021
+ const family = rule(fields);
4022
+ if (family !== void 0) return family;
4023
+ }
4024
+ return void 0;
4025
+ }
4026
+
3770
4027
  // src/evaluators/render-chain.ts
3771
4028
  function emitRenderChain(ctx) {
3772
4029
  const assertion = ctx.scenarioAssertions.renderChain;
3773
4030
  if (assertion === void 0) return;
3774
4031
  const observed = ctx.input.report.observations?.renderChain;
3775
- if (assertion.tier !== void 0) {
3776
- const pass = observed?.tier === assertion.tier;
4032
+ const selected = selectExpectation(ctx, assertion);
4033
+ const expected = selected.expectation;
4034
+ if (expected.tier !== void 0) {
4035
+ const pass = observed?.tier === expected.tier;
3777
4036
  ctx.assertions.push({
3778
- details: { expected: assertion.tier, observed: observed?.tier },
4037
+ details: { ...selected.provenance, expected: expected.tier, observed: observed?.tier },
3779
4038
  id: "renderChain.tier",
3780
4039
  pass
3781
4040
  });
3782
4041
  if (!pass) {
3783
4042
  ctx.diagnostics.push({
3784
4043
  code: observed === void 0 ? "TN_PLAYTEST_RENDER_CHAIN_UNOBSERVABLE" : "TN_PLAYTEST_RENDER_CHAIN_TIER_FAILED",
3785
- message: observed === void 0 ? "Render-chain tier was not observed because the TN_RENDER_CHAIN marker was absent." : `Render-chain tier '${observed.tier}' did not match the asserted tier '${assertion.tier}'.`,
4044
+ message: observed === void 0 ? "Render-chain tier was not observed because the TN_RENDER_CHAIN marker was absent." : `Render-chain tier '${observed.tier}' did not match the asserted tier '${expected.tier}'.`,
3786
4045
  observedRuntimePath: "observations.json/renderChain/tier",
3787
4046
  severity: "error",
3788
4047
  suggestion: "Install the RenderChain through the renderer seam and keep its marker callback connected to the playtest bridge."
3789
4048
  });
3790
4049
  }
3791
4050
  }
3792
- const stageAssertion = assertion.stages;
4051
+ const stageAssertion = expected.stages;
3793
4052
  if (stageAssertion !== void 0) {
3794
4053
  const observedStages = observed?.stages;
3795
4054
  if (stageAssertion.includes !== void 0) {
3796
4055
  emitStageCheck(
3797
4056
  ctx,
4057
+ selected.provenance,
3798
4058
  observedStages,
3799
4059
  "includes",
3800
4060
  stageAssertion.includes,
@@ -3804,6 +4064,7 @@ function emitRenderChain(ctx) {
3804
4064
  if (stageAssertion.excludes !== void 0) {
3805
4065
  emitStageCheck(
3806
4066
  ctx,
4067
+ selected.provenance,
3807
4068
  observedStages,
3808
4069
  "excludes",
3809
4070
  stageAssertion.excludes,
@@ -3813,6 +4074,7 @@ function emitRenderChain(ctx) {
3813
4074
  if (stageAssertion.order !== void 0) {
3814
4075
  emitStageCheck(
3815
4076
  ctx,
4077
+ selected.provenance,
3816
4078
  observedStages,
3817
4079
  "order",
3818
4080
  stageAssertion.order,
@@ -3820,7 +4082,7 @@ function emitRenderChain(ctx) {
3820
4082
  );
3821
4083
  }
3822
4084
  }
3823
- const contributionAssertion = assertion.contributions;
4085
+ const contributionAssertion = expected.contributions;
3824
4086
  if (contributionAssertion !== void 0) {
3825
4087
  const observedContributions = observed?.contributions;
3826
4088
  const pass = Array.isArray(observedContributions) && contributionAssertion.graphOutputChanged.every(
@@ -3828,6 +4090,7 @@ function emitRenderChain(ctx) {
3828
4090
  );
3829
4091
  ctx.assertions.push({
3830
4092
  details: {
4093
+ ...selected.provenance,
3831
4094
  expected: contributionAssertion.graphOutputChanged,
3832
4095
  observed: observedContributions
3833
4096
  },
@@ -3844,14 +4107,15 @@ function emitRenderChain(ctx) {
3844
4107
  });
3845
4108
  }
3846
4109
  }
3847
- if (assertion.velocity !== void 0) {
4110
+ if (expected.velocity !== void 0) {
3848
4111
  const rejectionFraction = observed?.velocity.rejectionFraction;
3849
4112
  const measurementFrame = observed?.velocity.measurementFrame;
3850
4113
  const hasMeasurement = rejectionFraction !== void 0 && Number.isFinite(rejectionFraction) && typeof measurementFrame === "number" && Number.isInteger(measurementFrame) && measurementFrame >= 0;
3851
- const pass = hasMeasurement && rejectionFraction !== void 0 && rejectionFraction <= assertion.velocity.maxRejectionFraction;
4114
+ const pass = hasMeasurement && rejectionFraction !== void 0 && rejectionFraction <= expected.velocity.maxRejectionFraction;
3852
4115
  ctx.assertions.push({
3853
4116
  details: {
3854
- expected: assertion.velocity.maxRejectionFraction,
4117
+ ...selected.provenance,
4118
+ expected: expected.velocity.maxRejectionFraction,
3855
4119
  measurementFrame,
3856
4120
  observed: rejectionFraction
3857
4121
  },
@@ -3861,17 +4125,47 @@ function emitRenderChain(ctx) {
3861
4125
  if (!pass) {
3862
4126
  ctx.diagnostics.push({
3863
4127
  code: observed === void 0 || !hasMeasurement ? "TN_PLAYTEST_RENDER_CHAIN_UNOBSERVABLE" : "TN_PLAYTEST_RENDER_CHAIN_REJECTION_FAILED",
3864
- message: observed === void 0 ? "Render-chain velocity rejection was not observed because the TN_RENDER_CHAIN marker was absent." : !hasMeasurement ? "Render-chain velocity was provisioned without a fresh completed-frame history-rejection measurement." : `Render-chain history rejection fraction ${rejectionFraction ?? "missing"} exceeded the asserted ceiling ${assertion.velocity.maxRejectionFraction}.`,
4128
+ message: observed === void 0 ? "Render-chain velocity rejection was not observed because the TN_RENDER_CHAIN marker was absent." : !hasMeasurement ? "Render-chain velocity was provisioned without a fresh completed-frame history-rejection measurement." : `Render-chain history rejection fraction ${rejectionFraction ?? "missing"} exceeded the asserted ceiling ${expected.velocity.maxRejectionFraction}.`,
3865
4129
  observedRuntimePath: "observations.json/renderChain/velocity/rejectionFraction",
3866
4130
  severity: "error",
3867
4131
  suggestion: "Publish the temporal stage's measured rejection fraction on the same render-chain marker used for tier reporting."
3868
4132
  });
3869
4133
  }
3870
4134
  }
4135
+ if (assertion.perAdapter !== void 0 && selected.classification === void 0) {
4136
+ ctx.assertions.push({
4137
+ details: { ...selected.provenance, expected: Object.keys(assertion.perAdapter) },
4138
+ id: "renderChain.adapterClass",
4139
+ pass: false
4140
+ });
4141
+ ctx.diagnostics.push({
4142
+ code: "TN_PLAYTEST_RENDER_CHAIN_ADAPTER_UNCLASSIFIED",
4143
+ message: "No adapter.info field named a software rasteriser, so this run is not proven to be either adapter class and was held to the flat render-chain expectation.",
4144
+ observedRuntimePath: "observations.json/capture/adapter",
4145
+ severity: "error",
4146
+ suggestion: "Run on a lane that reports adapter.info, or drop perAdapter and assert one policy for every adapter."
4147
+ });
4148
+ }
4149
+ }
4150
+ function selectExpectation(ctx, assertion) {
4151
+ const flat = {
4152
+ ...assertion.tier === void 0 ? {} : { tier: assertion.tier },
4153
+ ...assertion.stages === void 0 ? {} : { stages: assertion.stages },
4154
+ ...assertion.contributions === void 0 ? {} : { contributions: assertion.contributions },
4155
+ ...assertion.velocity === void 0 ? {} : { velocity: assertion.velocity }
4156
+ };
4157
+ const provenance = classifyAdapter(ctx.input.report);
4158
+ const { adapterClass, gpuFamily } = provenance;
4159
+ const branch = adapterClass === void 0 ? void 0 : (gpuFamily === void 0 ? void 0 : assertion.perAdapter?.[gpuFamily]) ?? assertion.perAdapter?.[adapterClass];
4160
+ return {
4161
+ classification: adapterClass,
4162
+ expectation: branch ?? flat,
4163
+ provenance
4164
+ };
3871
4165
  }
3872
- function emitStageCheck(ctx, observed, kind, expected, pass) {
4166
+ function emitStageCheck(ctx, provenance, observed, kind, expected, pass) {
3873
4167
  ctx.assertions.push({
3874
- details: { expected, observed },
4168
+ details: { ...provenance, expected, observed },
3875
4169
  id: `renderChain.stages.${kind}`,
3876
4170
  pass
3877
4171
  });
@@ -4092,7 +4386,7 @@ function emitOne2(ctx, assertion, index, observation) {
4092
4386
  observation,
4093
4387
  sampled,
4094
4388
  true,
4095
- (node) => (node.materials ?? []).every((material) => material.mapsUnloaded.length === 0),
4389
+ (node) => (node.materials?.length ?? 0) > 0 && (node.materials ?? []).every((material) => material.mapsUnloaded.length === 0),
4096
4390
  {
4097
4391
  code: "TN_PLAYTEST_SCENE_NODE_TEXTURE_UNLOADED",
4098
4392
  failure: (names, nodes) => {
@@ -4302,12 +4596,1138 @@ function emitStartup(ctx) {
4302
4596
  }
4303
4597
  }
4304
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
+
4305
5724
  // src/assertion-evaluators.ts
4306
5725
  function evaluateRichPlaytestAssertions(input) {
4307
5726
  const assertions = [];
4308
5727
  const diagnostics = [];
4309
5728
  const scenarioAssertions = input.scenario.assert ?? {};
4310
5729
  const ctx = { assertions, diagnostics, input, scenarioAssertions };
5730
+ emitTone(ctx);
4311
5731
  emitDeviceMetrics(ctx);
4312
5732
  emitDisplayFamilies(ctx);
4313
5733
  emitEvidenceFamilies(ctx);
@@ -4315,6 +5735,7 @@ function evaluateRichPlaytestAssertions(input) {
4315
5735
  emitPerfSignalsWorld(ctx);
4316
5736
  emitWorldGameplay(ctx);
4317
5737
  emitRenderChain(ctx);
5738
+ emitPipelineCensus(ctx);
4318
5739
  emitScene(ctx);
4319
5740
  emitSceneNodes(ctx);
4320
5741
  if (scenarioAssertions.geometry !== void 0) {
@@ -4681,12 +6102,25 @@ function rejectUnknownKeys(value, allowedKeys, scenarioPath, objectPath) {
4681
6102
  }
4682
6103
  var NUMERIC_COMPARISON_KEYS = ["gte", "lte"];
4683
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];
4684
6107
 
4685
6108
  // src/scenario/generated-assertion-validators.ts
4686
6109
  function isRecord2(value) {
4687
6110
  return typeof value === "object" && value !== null && !Array.isArray(value);
4688
6111
  }
4689
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
+ }),
4690
6124
  "deviceMetrics": Object.freeze({
4691
6125
  "maxTemperatureRiseC": (value) => typeof value === "number" && Number.isFinite(value) && value >= 0,
4692
6126
  "maxThermalStatus": (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 6,
@@ -4901,18 +6335,26 @@ var GENERATED_ASSERTION_FIELD_VALIDATORS = Object.freeze({
4901
6335
  "maxCompileSettledMs": (value) => typeof value === "number" && Number.isFinite(value),
4902
6336
  "maxReadyMs": (value) => typeof value === "number" && Number.isFinite(value)
4903
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
+ }),
4904
6345
  "renderChain": Object.freeze({
4905
6346
  "tier": (value) => typeof value === "string" && value.trim() !== "",
4906
6347
  "stages": (value) => isRecord2(value),
4907
6348
  "contributions": (value) => isRecord2(value),
4908
- "velocity": (value) => isRecord2(value)
6349
+ "velocity": (value) => isRecord2(value),
6350
+ "perAdapter": (value) => isRecord2(value)
4909
6351
  })
4910
6352
  });
4911
6353
 
4912
6354
  // src/scenario/schema-accessors.ts
4913
6355
  function validateVisualAssertion(value, scenarioPath, objectPath) {
4914
6356
  const record4 = requireRecord(value, scenarioPath, objectPath);
4915
- 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`);
4916
6358
  const regionRecord = record4.region === void 0 ? void 0 : requireRecord(record4.region, scenarioPath, `${objectPath}.region`);
4917
6359
  let region;
4918
6360
  if (regionRecord !== void 0) {
@@ -4926,9 +6368,9 @@ function validateVisualAssertion(value, scenarioPath, objectPath) {
4926
6368
  region = {
4927
6369
  element,
4928
6370
  ...present("maxDarkPixelRatio", optionalRatio(regionRecord, "maxDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
4929
- ...present("maxLuminance", optionalNumber(regionRecord, "maxLuminance", scenarioPath, `${objectPath}.region`)),
4930
- ...present("minDarkPixelRatio", optionalNumber(regionRecord, "minDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
4931
- ...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`))
4932
6374
  };
4933
6375
  } else {
4934
6376
  const edges = { height: 0, width: 0, x: 0, y: 0 };
@@ -4942,17 +6384,17 @@ function validateVisualAssertion(value, scenarioPath, objectPath) {
4942
6384
  region = {
4943
6385
  ...edges,
4944
6386
  ...present("maxDarkPixelRatio", optionalRatio(regionRecord, "maxDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
4945
- ...present("maxLuminance", optionalNumber(regionRecord, "maxLuminance", scenarioPath, `${objectPath}.region`)),
4946
- ...present("minDarkPixelRatio", optionalNumber(regionRecord, "minDarkPixelRatio", scenarioPath, `${objectPath}.region`)),
4947
- ...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`))
4948
6390
  };
4949
6391
  }
4950
6392
  }
4951
6393
  const entityVisibleRecord = record4.entityVisible === void 0 ? void 0 : requireRecord(record4.entityVisible, scenarioPath, `${objectPath}.entityVisible`);
4952
6394
  let entityVisible;
4953
6395
  if (entityVisibleRecord !== void 0) {
4954
- if (typeof entityVisibleRecord.minProjectedPixels !== "number") {
4955
- 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)}.`);
4956
6398
  }
4957
6399
  entityVisible = {
4958
6400
  entity: requireString(entityVisibleRecord, "entity", scenarioPath, `${objectPath}.entityVisible`),
@@ -4985,15 +6427,20 @@ function validateVisualRegionTarget(value, scenarioPath, objectPath) {
4985
6427
  ...selector === void 0 ? {} : { selector }
4986
6428
  };
4987
6429
  }
4988
- function validateVisualFrameDiff(record4, scenarioPath, objectPath) {
6430
+ function validateVisualFrameDiff(value, scenarioPath, objectPath) {
6431
+ const record4 = requireRecord(value, scenarioPath, objectPath);
4989
6432
  if (record4.baselineImage !== void 0 && !isSafeProjectRelativePng(record4.baselineImage)) {
4990
6433
  throw invalidScenario(scenarioPath, `'${objectPath}.baselineImage' must be a project-relative .png path without '..' or absolute segments, received ${describeValue(record4.baselineImage)}.`);
4991
6434
  }
4992
- return {
6435
+ const frameDiff = {
4993
6436
  ...present("baselineImage", optionalString(record4, "baselineImage", scenarioPath, objectPath)),
4994
- ...present("maxChangedPixelRatio", optionalNumber(record4, "maxChangedPixelRatio", scenarioPath, objectPath)),
4995
- ...present("minChangedPixelRatio", optionalNumber(record4, "minChangedPixelRatio", scenarioPath, objectPath))
6437
+ ...present("maxChangedPixelRatio", optionalRatio(record4, "maxChangedPixelRatio", scenarioPath, objectPath)),
6438
+ ...present("minChangedPixelRatio", optionalRatio(record4, "minChangedPixelRatio", scenarioPath, objectPath))
4996
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;
4997
6444
  }
4998
6445
  function isSafeProjectRelativePng(value) {
4999
6446
  if (typeof value !== "string" || !value.toLowerCase().endsWith(".png") || value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value)) {
@@ -5051,7 +6498,7 @@ function optionalBoolean(value, key, scenarioPath, objectPath) {
5051
6498
  }
5052
6499
  return raw;
5053
6500
  }
5054
- function optionalNumber(value, key, scenarioPath, objectPath) {
6501
+ function optionalNumber2(value, key, scenarioPath, objectPath) {
5055
6502
  const raw = value[key];
5056
6503
  if (raw === void 0) return void 0;
5057
6504
  if (typeof raw !== "number" || !Number.isFinite(raw)) {
@@ -5140,7 +6587,7 @@ function validateDeviceMetricsAssertion(value, scenarioPath, objectPath) {
5140
6587
  function validatePerformanceAssertion(value, scenarioPath, objectPath) {
5141
6588
  const record4 = requireRecord(value, scenarioPath, objectPath);
5142
6589
  rejectUnknownKeys(record4, ["maxDrawCalls", "maxFrameMsP95", "maxPassDrawCalls", "maxPassTriangles", "maxPhaseMsP95", "maxTriangles", "minFps"], scenarioPath, objectPath);
5143
- return {
6590
+ const assertion = {
5144
6591
  ...present("maxDrawCalls", optionalNonNegativeNumber(record4, "maxDrawCalls", scenarioPath, objectPath)),
5145
6592
  ...present("maxFrameMsP95", optionalNonNegativeNumber(record4, "maxFrameMsP95", scenarioPath, objectPath)),
5146
6593
  ...present("maxPassDrawCalls", validatePassBudget(record4.maxPassDrawCalls, scenarioPath, `${objectPath}.maxPassDrawCalls`)),
@@ -5149,15 +6596,22 @@ function validatePerformanceAssertion(value, scenarioPath, objectPath) {
5149
6596
  ...present("maxTriangles", optionalNonNegativeNumber(record4, "maxTriangles", scenarioPath, objectPath)),
5150
6597
  ...present("minFps", optionalNonNegativeNumber(record4, "minFps", scenarioPath, objectPath))
5151
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;
5152
6606
  }
5153
6607
  function validateParityAssertion(value, scenarioPath, objectPath) {
5154
6608
  const record4 = requireRecord(value, scenarioPath, objectPath);
5155
6609
  rejectUnknownKeys(record4, ["minFpsRatio", "minRenderParity", "reference", "referenceReport", "referenceSide"], scenarioPath, objectPath);
5156
- const minFpsRatio = optionalNumber(record4, "minFpsRatio", scenarioPath, objectPath);
6610
+ const minFpsRatio = optionalNumber2(record4, "minFpsRatio", scenarioPath, objectPath);
5157
6611
  if (minFpsRatio === void 0 || minFpsRatio <= 0) {
5158
6612
  throw invalidScenario(scenarioPath, `'${objectPath}.minFpsRatio' must be a positive number (Tier 2's Floor is 0.85).`);
5159
6613
  }
5160
- const minRenderParity = optionalNumber(record4, "minRenderParity", scenarioPath, objectPath);
6614
+ const minRenderParity = optionalNumber2(record4, "minRenderParity", scenarioPath, objectPath);
5161
6615
  if (minRenderParity !== void 0 && minRenderParity <= 0) {
5162
6616
  throw invalidScenario(scenarioPath, `'${objectPath}.minRenderParity' must be a positive number when present.`);
5163
6617
  }
@@ -5170,11 +6624,11 @@ function validateParityAssertion(value, scenarioPath, objectPath) {
5170
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.`);
5171
6625
  }
5172
6626
  const reference = record4.reference === void 0 ? void 0 : requireRecord(record4.reference, scenarioPath, `${objectPath}.reference`);
5173
- 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`);
5174
6628
  if (referenceFps !== void 0 && referenceFps <= 0) {
5175
6629
  throw invalidScenario(scenarioPath, `'${objectPath}.reference.fps' must be a positive number.`);
5176
6630
  }
5177
- 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`);
5178
6632
  if (referenceRenderP95 !== void 0 && referenceRenderP95 <= 0) {
5179
6633
  throw invalidScenario(scenarioPath, `'${objectPath}.reference.renderP95' must be a positive number.`);
5180
6634
  }
@@ -5203,6 +6657,33 @@ function validateParityAssertion(value, scenarioPath, objectPath) {
5203
6657
  }
5204
6658
  function validateRenderChainAssertion(value, scenarioPath, objectPath) {
5205
6659
  const record4 = requireRecord(value, scenarioPath, objectPath);
6660
+ const perAdapter = record4.perAdapter === void 0 ? void 0 : validateRenderChainPerAdapter(record4.perAdapter, scenarioPath, `${objectPath}.perAdapter`);
6661
+ const expectation = validateRenderChainExpectation(record4, scenarioPath, objectPath);
6662
+ return perAdapter === void 0 ? expectation : { ...expectation, perAdapter };
6663
+ }
6664
+ function validateRenderChainPerAdapter(value, scenarioPath, objectPath) {
6665
+ const record4 = requireRecord(value, scenarioPath, objectPath);
6666
+ const entries = Object.entries(record4);
6667
+ if (entries.length === 0) {
6668
+ throw invalidScenario(scenarioPath, `'${objectPath}' must name at least one adapter class.`);
6669
+ }
6670
+ const result = {};
6671
+ for (const [kind, branch] of entries) {
6672
+ if (!PLAYTEST_PER_ADAPTER_KEYS.includes(kind)) {
6673
+ throw invalidScenario(
6674
+ scenarioPath,
6675
+ `'${objectPath}.${kind}' is not an adapter class this harness can classify; expected ${PLAYTEST_PER_ADAPTER_KEYS.join(", ")}.`
6676
+ );
6677
+ }
6678
+ result[kind] = validateRenderChainExpectation(
6679
+ requireRecord(branch, scenarioPath, `${objectPath}.${kind}`),
6680
+ scenarioPath,
6681
+ `${objectPath}.${kind}`
6682
+ );
6683
+ }
6684
+ return result;
6685
+ }
6686
+ function validateRenderChainExpectation(record4, scenarioPath, objectPath) {
5206
6687
  const tier = record4.tier;
5207
6688
  if (tier !== void 0 && tier !== "high" && tier !== "medium" && tier !== "low" && tier !== "off") {
5208
6689
  throw invalidScenario(scenarioPath, `'${objectPath}.tier' must be high, medium, low, or off, received ${describeValue(tier)}.`);
@@ -5228,7 +6709,7 @@ function validateRenderChainAssertion(value, scenarioPath, objectPath) {
5228
6709
  const velocityValue = record4.velocity;
5229
6710
  const velocity = velocityValue === void 0 ? void 0 : requireRecord(velocityValue, scenarioPath, `${objectPath}.velocity`);
5230
6711
  if (velocity !== void 0) {
5231
- const maxRejectionFraction = optionalNumber(velocity, "maxRejectionFraction", scenarioPath, `${objectPath}.velocity`);
6712
+ const maxRejectionFraction = optionalNumber2(velocity, "maxRejectionFraction", scenarioPath, `${objectPath}.velocity`);
5232
6713
  if (maxRejectionFraction === void 0 || maxRejectionFraction < 0 || maxRejectionFraction > 1) {
5233
6714
  throw invalidScenario(scenarioPath, `'${objectPath}.velocity.maxRejectionFraction' must be a finite number between 0 and 1.`);
5234
6715
  }
@@ -5281,6 +6762,36 @@ function validateStartupAssertion(value, scenarioPath, objectPath) {
5281
6762
  }
5282
6763
  return result;
5283
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
+ }
5284
6795
  function validatePassBudget(value, scenarioPath, objectPath) {
5285
6796
  if (value === void 0) return void 0;
5286
6797
  const record4 = requireRecord(value, scenarioPath, objectPath);
@@ -5396,7 +6907,7 @@ function validateContactAssertion(value, scenarioPath, objectPath) {
5396
6907
  ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
5397
6908
  ...present("kind", optionalString(record4, "kind", scenarioPath, objectPath)),
5398
6909
  ...present("maxCount", optionalNonNegativeInteger(record4, "maxCount", scenarioPath, objectPath)),
5399
- ...present("minCount", optionalNumber(record4, "minCount", scenarioPath, objectPath)),
6910
+ ...present("minCount", optionalNumber2(record4, "minCount", scenarioPath, objectPath)),
5400
6911
  ...present("requiredOn", optionalTargetArray(record4, "requiredOn", scenarioPath, objectPath)),
5401
6912
  ...present("with", optionalString(record4, "with", scenarioPath, objectPath))
5402
6913
  };
@@ -5429,6 +6940,20 @@ function validateSceneAssertion(value, scenarioPath, objectPath) {
5429
6940
  `'${objectPath}' must set at least one of ${[...SCENE_FLAGS, "minVisibleLights"].join(", ")}; an empty scene assertion observes nothing.`
5430
6941
  );
5431
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
+ }
5432
6957
  return result;
5433
6958
  }
5434
6959
  var SCENE_NODE_SELECTOR_KEYS = ["limit", "name", "nameContains", "pathContains", "type"];
@@ -5485,6 +7010,11 @@ function validateCausedByAssertion(value, scenarioPath, objectPath) {
5485
7010
  scenarioPath,
5486
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.`
5487
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
+ );
5488
7018
  return result;
5489
7019
  }
5490
7020
  function validateSceneNodeSelector(value, scenarioPath, objectPath) {
@@ -5530,19 +7060,24 @@ function validateSceneNodesAssertion(value, scenarioPath, objectPath) {
5530
7060
  scenarioPath,
5531
7061
  `'${objectPath}' must set at least one of ${SCENE_NODE_BOUNDS.join(", ")}; selecting nodes without bounding them observes nothing.`
5532
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
+ );
5533
7068
  return result;
5534
7069
  }
5535
7070
  function validateAnimationAssertion(value, scenarioPath, objectPath) {
5536
7071
  const record4 = requireRecord(value, scenarioPath, objectPath);
5537
7072
  rejectUnknownKeys(record4, ["advancedFrames", "allowTrivial", "clip", "entered", "entity", "finished", "maxFootSlide", "strideSynced"], scenarioPath, objectPath);
5538
7073
  return {
5539
- ...present("advancedFrames", optionalNumber(record4, "advancedFrames", scenarioPath, objectPath)),
7074
+ ...present("advancedFrames", optionalNumber2(record4, "advancedFrames", scenarioPath, objectPath)),
5540
7075
  ...present("allowTrivial", optionalTrivialityReason(record4, "allowTrivial", scenarioPath, objectPath)),
5541
7076
  ...present("clip", optionalString(record4, "clip", scenarioPath, objectPath)),
5542
7077
  ...present("entered", optionalBoolean(record4, "entered", scenarioPath, objectPath)),
5543
7078
  ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
5544
7079
  ...present("finished", optionalBoolean(record4, "finished", scenarioPath, objectPath)),
5545
- ...present("maxFootSlide", optionalNumber(record4, "maxFootSlide", scenarioPath, objectPath)),
7080
+ ...present("maxFootSlide", optionalNonNegativeNumber(record4, "maxFootSlide", scenarioPath, objectPath)),
5546
7081
  ...present("strideSynced", optionalBoolean(record4, "strideSynced", scenarioPath, objectPath))
5547
7082
  };
5548
7083
  }
@@ -5552,24 +7087,32 @@ function validateVisibilityAssertion(value, scenarioPath, objectPath) {
5552
7087
  return {
5553
7088
  ...present("allowTrivial", optionalTrivialityReason(record4, "allowTrivial", scenarioPath, objectPath)),
5554
7089
  ...present("entity", optionalString(record4, "entity", scenarioPath, objectPath)),
5555
- ...present("maxOffscreenRatio", optionalNumber(record4, "maxOffscreenRatio", scenarioPath, objectPath)),
5556
- ...present("minProjectedPixels", optionalNumber(record4, "minProjectedPixels", scenarioPath, objectPath)),
7090
+ ...present("maxOffscreenRatio", optionalRatio(record4, "maxOffscreenRatio", scenarioPath, objectPath)),
7091
+ ...present("minProjectedPixels", optionalNonNegativeNumber(record4, "minProjectedPixels", scenarioPath, objectPath)),
5557
7092
  ...present("present", optionalBoolean(record4, "present", scenarioPath, objectPath))
5558
7093
  };
5559
7094
  }
5560
7095
  function validatePathAssertion(value, scenarioPath, objectPath) {
5561
7096
  const record4 = requireRecord(value, scenarioPath, objectPath);
5562
- const gte = optionalNumber(record4, "gte", scenarioPath, objectPath);
5563
- 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;
5564
7114
  return {
5565
- ...Array.isArray(record4.atSteps) ? { atSteps: record4.atSteps.map((step, index) => {
5566
- const entry = requireRecord(step, scenarioPath, `${objectPath}.atSteps[${index}]`);
5567
- return {
5568
- ...hasKey(entry, "equals") ? { equals: entry.equals } : {},
5569
- label: requireString(entry, "label", scenarioPath, `${objectPath}.atSteps[${index}]`),
5570
- ...present("textIncludes", optionalString(entry, "textIncludes", scenarioPath, `${objectPath}.atSteps[${index}]`))
5571
- };
5572
- }) } : {},
7115
+ ...atSteps === void 0 ? {} : { atSteps },
5573
7116
  ...present("changed", optionalBoolean(record4, "changed", scenarioPath, objectPath)),
5574
7117
  ...present("allowTrivial", optionalTrivialityReason(record4, "allowTrivial", scenarioPath, objectPath)),
5575
7118
  ...hasKey(record4, "equals") ? { equals: record4.equals } : {},
@@ -5609,8 +7152,8 @@ function validateResourcePathAlternative(value, scenarioPath, objectPath) {
5609
7152
  const record4 = requireRecord(value, scenarioPath, objectPath);
5610
7153
  rejectUnknownKeys(record4, ["changed", "equals", ...NUMERIC_COMPARISON_KEYS, "path", "textIncludes"], scenarioPath, objectPath);
5611
7154
  const changed = optionalBoolean(record4, "changed", scenarioPath, objectPath);
5612
- const gte = optionalNumber(record4, "gte", scenarioPath, objectPath);
5613
- const lte = optionalNumber(record4, "lte", scenarioPath, objectPath);
7155
+ const gte = optionalNumber2(record4, "gte", scenarioPath, objectPath);
7156
+ const lte = optionalNumber2(record4, "lte", scenarioPath, objectPath);
5614
7157
  const textIncludes = optionalString(record4, "textIncludes", scenarioPath, objectPath);
5615
7158
  if (!hasKey(record4, "equals") && changed === void 0 && gte === void 0 && lte === void 0 && textIncludes === void 0) {
5616
7159
  throw invalidScenario(scenarioPath, `'${objectPath}' must declare equals, gte, lte, textIncludes, or changed.`);
@@ -5630,17 +7173,17 @@ function validateViewport(value, scenarioPath = "scenario") {
5630
7173
  }
5631
7174
  const record4 = requireRecord(value, scenarioPath, "viewport");
5632
7175
  rejectUnknownKeys(record4, ["height", "width"], scenarioPath, "viewport");
5633
- const width = positiveInteger(record4.width);
7176
+ const width = positiveInteger2(record4.width);
5634
7177
  if (width === void 0) {
5635
7178
  throw invalidScenario(scenarioPath, `'viewport.width' must be a positive integer, received ${describeValue(record4.width)}.`);
5636
7179
  }
5637
- const height = positiveInteger(record4.height);
7180
+ const height = positiveInteger2(record4.height);
5638
7181
  if (height === void 0) {
5639
7182
  throw invalidScenario(scenarioPath, `'viewport.height' must be a positive integer, received ${describeValue(record4.height)}.`);
5640
7183
  }
5641
7184
  return { height, width };
5642
7185
  }
5643
- function positiveInteger(value) {
7186
+ function positiveInteger2(value) {
5644
7187
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
5645
7188
  }
5646
7189
  function validateOptionalNumberTuple(value, key, length, scenarioPath, index) {
@@ -5765,29 +7308,30 @@ function validateNestedAssertionKeys(kind, value, scenarioPath, suffix) {
5765
7308
  `assert.${kind}${suffix}.runtime`
5766
7309
  );
5767
7310
  }
5768
- if (kind === "renderChain" && isRecord3(value.velocity)) {
5769
- rejectUnknownKeys(
5770
- value.velocity,
5771
- ["maxRejectionFraction"],
5772
- scenarioPath,
5773
- `assert.${kind}${suffix}.velocity`
5774
- );
5775
- }
5776
- if (kind === "renderChain" && isRecord3(value.contributions)) {
5777
- rejectUnknownKeys(
5778
- value.contributions,
5779
- ["graphOutputChanged"],
5780
- scenarioPath,
5781
- `assert.${kind}${suffix}.contributions`
5782
- );
7311
+ if (kind === "renderChain") {
7312
+ rejectRenderChainExpectationKeys(value, scenarioPath, `assert.${kind}${suffix}`);
7313
+ if (isRecord3(value.perAdapter)) {
7314
+ const branchPath = `assert.renderChain${suffix}.perAdapter`;
7315
+ rejectUnknownKeys(value.perAdapter, [...PLAYTEST_PER_ADAPTER_KEYS], scenarioPath, branchPath);
7316
+ for (const [adapterKind, branch] of Object.entries(value.perAdapter)) {
7317
+ if (isRecord3(branch)) {
7318
+ rejectUnknownKeys(branch, ["contributions", "stages", "tier", "velocity"], scenarioPath, `${branchPath}.${adapterKind}`);
7319
+ rejectRenderChainExpectationKeys(branch, scenarioPath, `${branchPath}.${adapterKind}`);
7320
+ }
7321
+ }
7322
+ }
5783
7323
  }
5784
- if (kind === "renderChain" && isRecord3(value.stages)) {
5785
- rejectUnknownKeys(
5786
- value.stages,
5787
- ["excludes", "includes", "order"],
5788
- scenarioPath,
5789
- `assert.${kind}${suffix}.stages`
5790
- );
7324
+ }
7325
+ var RENDER_CHAIN_NESTED_KEYS = {
7326
+ contributions: ["graphOutputChanged"],
7327
+ stages: ["excludes", "includes", "order"],
7328
+ velocity: ["maxRejectionFraction"]
7329
+ };
7330
+ function rejectRenderChainExpectationKeys(value, scenarioPath, objectPath) {
7331
+ for (const [field, keys] of Object.entries(RENDER_CHAIN_NESTED_KEYS)) {
7332
+ if (isRecord3(value[field])) {
7333
+ rejectUnknownKeys(value[field], keys, scenarioPath, `${objectPath}.${field}`);
7334
+ }
5791
7335
  }
5792
7336
  }
5793
7337
 
@@ -5801,8 +7345,10 @@ var PLAYTEST_ROOT_KEYS = [
5801
7345
  "inputDelivery",
5802
7346
  "name",
5803
7347
  "parity",
7348
+ "reducedMotion",
5804
7349
  "schemaVersion",
5805
7350
  "setup",
7351
+ "startTick",
5806
7352
  "steps",
5807
7353
  "subject",
5808
7354
  "target",
@@ -5827,6 +7373,9 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
5827
7373
  if (value.awaitStartup !== void 0 && typeof value.awaitStartup !== "boolean") {
5828
7374
  throw invalidScenario(scenarioPath, "Scenario awaitStartup must be a boolean when present.");
5829
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
+ }
5830
7379
  if (value.bootFailure !== void 0 && value.bootFailure !== "renderer-no-adapter") {
5831
7380
  throw invalidScenario(scenarioPath, "Scenario bootFailure must be 'renderer-no-adapter' when present.");
5832
7381
  }
@@ -5837,6 +7386,12 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
5837
7386
  if (value.bootFailure !== void 0 && target !== "web") {
5838
7387
  throw invalidScenario(scenarioPath, "Scenario bootFailure is browser-only and requires target 'web'.");
5839
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
+ }
5840
7395
  const inputDelivery = value.inputDelivery ?? "deterministic";
5841
7396
  if (inputDelivery !== "deterministic" && inputDelivery !== "focused-dom") {
5842
7397
  throw invalidScenario(scenarioPath, "Scenario inputDelivery must be deterministic or focused-dom.");
@@ -5847,7 +7402,10 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
5847
7402
  if (!Array.isArray(value.steps) || value.steps.length === 0) {
5848
7403
  throw invalidStep(scenarioPath, "Scenario steps[] must contain at least one step.");
5849
7404
  }
5850
- 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;
5851
7409
  const steps = value.steps.map((step, index) => validateStep(step, scenarioPath, index));
5852
7410
  if (steps.some(({ kind }) => kind === "aimAt") && subject === void 0) {
5853
7411
  throw invalidScenario(scenarioPath, "A step with kind 'aimAt' aims the subject player start; declare scenario.subject or replace the step.");
@@ -5856,25 +7414,38 @@ function validatePlaytestScenario(value, scenarioPath, absolutePath) {
5856
7414
  validateStepLabels(steps, assertions, scenarioPath);
5857
7415
  return {
5858
7416
  ...typeof value.acceptanceId === "string" ? { acceptanceId: value.acceptanceId } : {},
5859
- ...isRecord3(value.artifacts) ? { artifacts: validateArtifacts(value.artifacts, scenarioPath) } : {},
7417
+ ...value.artifacts === void 0 ? {} : { artifacts: validateArtifacts(requireRecord(value.artifacts, scenarioPath, "artifacts"), scenarioPath) },
5860
7418
  ...assertions === void 0 ? {} : { assert: assertions },
5861
7419
  ...typeof value.awaitStartup === "boolean" ? { awaitStartup: value.awaitStartup } : {},
5862
7420
  ...value.bootFailure === "renderer-no-adapter" ? { bootFailure: value.bootFailure } : {},
5863
7421
  inputDelivery,
5864
7422
  name,
5865
- ...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 } : {},
5866
7425
  schemaVersion: 1,
5867
- ...isRecord3(value.setup) ? { setup: validateSetup(value.setup, scenarioPath, subject) } : {},
7426
+ ...value.setup === void 0 ? {} : { setup: validateSetup(requireRecord(value.setup, scenarioPath, "setup"), scenarioPath, subject) },
5868
7427
  ...absolutePath === void 0 ? {} : { sourcePath: absolutePath },
7428
+ ...value.startTick === void 0 ? {} : { startTick: value.startTick },
5869
7429
  steps,
5870
- ...typeof value.subject === "string" ? { subject: value.subject } : {},
7430
+ ...subject === void 0 ? {} : { subject },
5871
7431
  target,
5872
7432
  viewport: validateViewport(value.viewport, scenarioPath),
5873
- warmupFrames: positiveInteger(value.warmupFrames) ?? 0
7433
+ warmupFrames: optionalNonNegativeInteger(value, "warmupFrames", scenarioPath, "scenario") ?? 0
5874
7434
  };
5875
7435
  }
5876
7436
  function validateArtifacts(value, scenarioPath) {
5877
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
+ }
5878
7449
  return value;
5879
7450
  }
5880
7451
  function validateParityConfig(value, scenarioPath) {
@@ -5980,9 +7551,9 @@ function validateSpawnRequest(value, scenarioPath) {
5980
7551
  if (value === void 0) return void 0;
5981
7552
  const record4 = requireRecord(value, scenarioPath, "setup.spawn");
5982
7553
  rejectUnknownKeys(record4, ["x", "y", "z"], scenarioPath, "setup.spawn");
5983
- const x = optionalNumber(record4, "x", scenarioPath, "setup.spawn");
5984
- const y = optionalNumber(record4, "y", scenarioPath, "setup.spawn");
5985
- 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");
5986
7557
  if (x === void 0 || z === void 0) {
5987
7558
  throw invalidScenario(scenarioPath, "'setup.spawn' must define finite x and z; y is optional and preserves the game's current height when absent.");
5988
7559
  }
@@ -5992,8 +7563,8 @@ function validateAimRequest(value, scenarioPath) {
5992
7563
  if (value === void 0) return void 0;
5993
7564
  const record4 = requireRecord(value, scenarioPath, "setup.aim");
5994
7565
  rejectUnknownKeys(record4, ["pitch", "yaw"], scenarioPath, "setup.aim");
5995
- const pitch = optionalNumber(record4, "pitch", scenarioPath, "setup.aim");
5996
- 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");
5997
7568
  if (pitch === void 0 || yaw === void 0) {
5998
7569
  throw invalidScenario(scenarioPath, "'setup.aim' must define finite yaw and pitch angles in radians.");
5999
7570
  }
@@ -6018,7 +7589,7 @@ function validatePlaceRequest(value, scenarioPath, index) {
6018
7589
  const facingYaw = record4.facing === void 0 ? void 0 : (() => {
6019
7590
  const facingRecord = requireRecord(record4.facing, scenarioPath, `${objectPath}.facing`);
6020
7591
  rejectUnknownKeys(facingRecord, ["yaw"], scenarioPath, `${objectPath}.facing`);
6021
- const yaw = optionalNumber(facingRecord, "yaw", scenarioPath, `${objectPath}.facing`);
7592
+ const yaw = optionalNumber2(facingRecord, "yaw", scenarioPath, `${objectPath}.facing`);
6022
7593
  if (yaw === void 0) {
6023
7594
  throw invalidScenario(scenarioPath, `'${objectPath}.facing.yaw' must be a finite angle in radians.`);
6024
7595
  }
@@ -6039,9 +7610,9 @@ function validatePlaceRequest(value, scenarioPath, index) {
6039
7610
  function validatePoint(value, scenarioPath, objectPath, requirement) {
6040
7611
  const record4 = requireRecord(value, scenarioPath, objectPath);
6041
7612
  rejectUnknownKeys(record4, ["x", "y", "z"], scenarioPath, objectPath);
6042
- const x = optionalNumber(record4, "x", scenarioPath, objectPath);
6043
- const y = optionalNumber(record4, "y", scenarioPath, objectPath);
6044
- 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);
6045
7616
  if (x === void 0 || y === void 0 || z === void 0) {
6046
7617
  throw invalidScenario(scenarioPath, `'${objectPath}' must define finite x, y, and z; ${requirement}.`);
6047
7618
  }
@@ -6088,6 +7659,8 @@ var PLAYTEST_STEP_KEYS = [
6088
7659
  "holdTicks",
6089
7660
  "kind",
6090
7661
  "label",
7662
+ "lifecycle",
7663
+ "media",
6091
7664
  "overlayMessage",
6092
7665
  "pitch",
6093
7666
  "pointerPosition",
@@ -6110,7 +7683,7 @@ function validateStep(value, scenarioPath, index) {
6110
7683
  }
6111
7684
  rejectUnknownKeys(value, PLAYTEST_STEP_KEYS, scenarioPath, `steps[${index}]`);
6112
7685
  const waitForResource = value.waitForResource === void 0 ? void 0 : validateResourceWait(value.waitForResource, scenarioPath, index);
6113
- const timeoutMs = positiveInteger(value.timeoutMs);
7686
+ const timeoutMs = positiveInteger2(value.timeoutMs);
6114
7687
  if (waitForResource === void 0) {
6115
7688
  if (value.timeoutMs !== void 0) {
6116
7689
  throw invalidStep(scenarioPath, `Scenario step ${index} timeoutMs belongs to waitForResource.`);
@@ -6124,6 +7697,8 @@ function validateStep(value, scenarioPath, index) {
6124
7697
  "holdFrames",
6125
7698
  "holdTicks",
6126
7699
  "kind",
7700
+ "lifecycle",
7701
+ "media",
6127
7702
  "overlayMessage",
6128
7703
  "pitch",
6129
7704
  "pointerPosition",
@@ -6153,9 +7728,11 @@ function validateStep(value, scenarioPath, index) {
6153
7728
  y: value.pointerPosition.y
6154
7729
  } : void 0;
6155
7730
  const pointers = Array.isArray(value.pointers) ? value.pointers.map((pointer, pointerIndex) => validatePointer(pointer, scenarioPath, index, pointerIndex)) : void 0;
6156
- 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)) ? {
6157
7733
  ...typeof value.wheel.deltaX === "number" ? { deltaX: value.wheel.deltaX } : {},
6158
- 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 } : {}
6159
7736
  } : void 0;
6160
7737
  if (isRecord3(value.overlayMessage)) {
6161
7738
  rejectUnknownKeys(value.overlayMessage, ["overlayId", "payload", "type"], scenarioPath, `steps[${index}].overlayMessage`);
@@ -6164,18 +7741,19 @@ function validateStep(value, scenarioPath, index) {
6164
7741
  rejectUnknownKeys(value.pointerPosition, ["buttons", "x", "y"], scenarioPath, `steps[${index}].pointerPosition`);
6165
7742
  }
6166
7743
  if (isRecord3(value.wheel)) {
6167
- rejectUnknownKeys(value.wheel, ["deltaX", "deltaY"], scenarioPath, `steps[${index}].wheel`);
7744
+ rejectUnknownKeys(value.wheel, ["deltaX", "deltaY", "x", "y"], scenarioPath, `steps[${index}].wheel`);
6168
7745
  }
7746
+ const media = validateMedia(value.media, scenarioPath, index);
6169
7747
  if (pointers !== void 0 && new Set(pointers.map(({ id }) => id)).size !== pointers.length) {
6170
7748
  throw invalidStep(scenarioPath, `Scenario step ${index} pointers must use unique ids.`);
6171
7749
  }
6172
- const holdFrames = positiveInteger(value.holdFrames);
6173
- const holdTicks = positiveInteger(value.holdTicks);
6174
- const waitFrames = positiveInteger(value.waitFrames);
6175
- const waitTicks = positiveInteger(value.waitTicks);
6176
- const kind = value.kind === "aimAt" ? "aimAt" : value.kind === "click" ? "click" : value.kind === "wait" ? "wait" : value.kind === "input" ? "input" : void 0;
7750
+ const holdFrames = positiveInteger2(value.holdFrames);
7751
+ const holdTicks = positiveInteger2(value.holdTicks);
7752
+ const waitFrames = positiveInteger2(value.waitFrames);
7753
+ const waitTicks = positiveInteger2(value.waitTicks);
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;
6177
7755
  if (value.kind !== void 0 && kind === void 0) {
6178
- throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'input', or 'wait'.`);
7756
+ throw invalidStep(scenarioPath, `Scenario step ${index} kind must be 'aimAt', 'click', 'input', 'lifecycle', or 'wait'.`);
6179
7757
  }
6180
7758
  const at = validateClickTarget(value.at, scenarioPath, index);
6181
7759
  const target = validateAimTarget(value.target, scenarioPath, index);
@@ -6189,6 +7767,10 @@ function validateStep(value, scenarioPath, index) {
6189
7767
  if (isRecord3(value.window)) {
6190
7768
  rejectUnknownKeys(value.window, ["height", "operation", "width"], scenarioPath, `steps[${index}].window`);
6191
7769
  }
7770
+ if (isRecord3(value.lifecycle)) {
7771
+ rejectUnknownKeys(value.lifecycle, ["operation", "rotation"], scenarioPath, `steps[${index}].lifecycle`);
7772
+ }
7773
+ const lifecycle = validateLifecycleStep(value.lifecycle, scenarioPath, index);
6192
7774
  if (kind !== "click" && (at !== void 0 || value.at !== void 0)) {
6193
7775
  throw invalidStep(scenarioPath, `Scenario step ${index} declares at, which belongs to kind 'click'.`);
6194
7776
  }
@@ -6196,7 +7778,7 @@ function validateStep(value, scenarioPath, index) {
6196
7778
  if (at === void 0) {
6197
7779
  throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'click' must define at as { x, y } or { entity }.`);
6198
7780
  }
6199
- for (const forbidden of ["overlayMessage", "pointerPosition", "pointers", "press", "target", "wheel", "window"]) {
7781
+ for (const forbidden of ["media", "overlayMessage", "pointerPosition", "pointers", "press", "target", "wheel", "window"]) {
6200
7782
  if (value[forbidden] !== void 0) {
6201
7783
  throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'click' cannot define ${forbidden}.`);
6202
7784
  }
@@ -6215,7 +7797,7 @@ function validateStep(value, scenarioPath, index) {
6215
7797
  if (target === void 0) {
6216
7798
  throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'aimAt' must define target as { x, z } or { entity }.`);
6217
7799
  }
6218
- for (const forbidden of ["overlayMessage", "pointerPosition", "pointers", "press", "wheel", "window"]) {
7800
+ for (const forbidden of ["media", "overlayMessage", "pointerPosition", "pointers", "press", "wheel", "window"]) {
6219
7801
  if (value[forbidden] !== void 0) {
6220
7802
  throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'aimAt' cannot define ${forbidden}; apply aim in its own step.`);
6221
7803
  }
@@ -6244,7 +7826,7 @@ function validateStep(value, scenarioPath, index) {
6244
7826
  throw invalidStep(scenarioPath, `Scenario step ${index} pointers must be an array.`);
6245
7827
  }
6246
7828
  if (value.wheel !== void 0 && wheel === void 0) {
6247
- 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.`);
6248
7830
  }
6249
7831
  if (value.screenshot !== void 0 && screenshot === void 0) {
6250
7832
  throw invalidStep(scenarioPath, `Scenario step ${index} screenshot must be a stable file-safe name.`);
@@ -6252,11 +7834,45 @@ function validateStep(value, scenarioPath, index) {
6252
7834
  if (value.label !== void 0 && (typeof value.label !== "string" || value.label.trim() === "")) {
6253
7835
  throw invalidStep(scenarioPath, `Scenario step ${index} label must be a non-empty string.`);
6254
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
+ }
6255
7840
  if (value.window !== void 0 && window === void 0) {
6256
7841
  throw invalidStep(scenarioPath, `Scenario step ${index} window must define minimize, restore, or resize with positive width and height.`);
6257
7842
  }
6258
- 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) {
6259
- throw invalidStep(scenarioPath, `Scenario step ${index} must define click at, press, overlayMessage, pointerPosition, pointers, wheel, window, aimAt target, or waitFrames/waitTicks.`);
7843
+ if (value.lifecycle !== void 0 && lifecycle === void 0) {
7844
+ throw invalidStep(scenarioPath, `Scenario step ${index} lifecycle must define an operation of 'background', 'foreground', or 'rotate', and 'rotate' must name a rotation from 0 through 3.`);
7845
+ }
7846
+ if (kind !== "lifecycle" && value.lifecycle !== void 0) {
7847
+ throw invalidStep(scenarioPath, `Scenario step ${index} declares lifecycle, which belongs to kind 'lifecycle'.`);
7848
+ }
7849
+ if (kind === "lifecycle") {
7850
+ if (lifecycle === void 0) {
7851
+ throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'lifecycle' must define lifecycle.operation.`);
7852
+ }
7853
+ for (const forbidden of [
7854
+ "holdFrames",
7855
+ "holdTicks",
7856
+ "label",
7857
+ "media",
7858
+ "overlayMessage",
7859
+ "pointerPosition",
7860
+ "pointers",
7861
+ "press",
7862
+ "screenshot",
7863
+ "target",
7864
+ "waitFrames",
7865
+ "waitTicks",
7866
+ "wheel",
7867
+ "window"
7868
+ ]) {
7869
+ if (value[forbidden] !== void 0) {
7870
+ throw invalidStep(scenarioPath, `Scenario step ${index} with kind 'lifecycle' cannot define ${forbidden}; a lifecycle step is one device operation and nothing else.`);
7871
+ }
7872
+ }
7873
+ }
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.`);
6260
7876
  }
6261
7877
  if (value.holdFrames !== void 0 && holdFrames === void 0) {
6262
7878
  throw invalidStep(scenarioPath, `Scenario step ${index} holdFrames must be a positive integer.`);
@@ -6285,6 +7901,8 @@ function validateStep(value, scenarioPath, index) {
6285
7901
  ...holdTicks === void 0 ? {} : { holdTicks },
6286
7902
  ...typeof value.label === "string" ? { label: value.label } : {},
6287
7903
  ...at === void 0 ? {} : { at },
7904
+ ...lifecycle === void 0 ? {} : { lifecycle },
7905
+ ...media === void 0 ? {} : { media },
6288
7906
  ...overlayMessage === void 0 ? {} : { overlayMessage },
6289
7907
  ...pitch === void 0 ? {} : { pitch },
6290
7908
  ...pointerPosition === void 0 ? {} : { pointerPosition },
@@ -6301,6 +7919,41 @@ function validateStep(value, scenarioPath, index) {
6301
7919
  ...window === void 0 ? {} : { window }
6302
7920
  };
6303
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
+ }
7941
+ function validateLifecycleStep(value, scenarioPath, index) {
7942
+ if (!isRecord3(value)) return void 0;
7943
+ const rotation = value.rotation;
7944
+ const rotationValue = typeof rotation === "number" && Number.isInteger(rotation) && rotation >= 0 && rotation <= 3 ? rotation : void 0;
7945
+ if (value.operation === "rotate") {
7946
+ if (rotationValue === void 0) {
7947
+ throw invalidStep(scenarioPath, `Scenario step ${index} lifecycle.operation 'rotate' must name a rotation from 0 through 3.`);
7948
+ }
7949
+ return { operation: "rotate", rotation: rotationValue };
7950
+ }
7951
+ if (value.operation !== "background" && value.operation !== "foreground") return void 0;
7952
+ if (rotation !== void 0) {
7953
+ throw invalidStep(scenarioPath, `Scenario step ${index} lifecycle.operation '${value.operation}' cannot define rotation; only 'rotate' takes one.`);
7954
+ }
7955
+ return { operation: value.operation };
7956
+ }
6304
7957
  function validateResourceWait(value, scenarioPath, index) {
6305
7958
  const objectPath = `steps[${index}].waitForResource`;
6306
7959
  if (!isRecord3(value)) {
@@ -6313,8 +7966,8 @@ function validateResourceWait(value, scenarioPath, index) {
6313
7966
  if (Number(hasEquals) + Number(hasGte) + Number(hasLte) !== 1) {
6314
7967
  throw invalidStep(scenarioPath, `Scenario step ${index} waitForResource must define exactly one of equals, gte, or lte.`);
6315
7968
  }
6316
- const gte = hasGte ? optionalNumber(value, "gte", scenarioPath, objectPath) : void 0;
6317
- 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;
6318
7971
  if (hasGte && gte === void 0) {
6319
7972
  throw invalidStep(scenarioPath, `Scenario step ${index} waitForResource.gte must be a finite number.`);
6320
7973
  }
@@ -6341,6 +7994,18 @@ function validateClickTarget(value, scenarioPath, index) {
6341
7994
  return value.entity.length === 0 ? void 0 : { entity: value.entity };
6342
7995
  }
6343
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
+ }
6344
8009
  rejectUnknownKeys(value, ["x", "y"], scenarioPath, `steps[${index}].at`);
6345
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;
6346
8011
  }
@@ -6358,8 +8023,8 @@ function validateAimTarget(value, scenarioPath, stepIndex) {
6358
8023
  return { entity: requireString(value, "entity", scenarioPath, objectPath) };
6359
8024
  }
6360
8025
  rejectUnknownKeys(value, ["x", "z"], scenarioPath, objectPath);
6361
- const x = optionalNumber(value, "x", scenarioPath, objectPath);
6362
- const z = optionalNumber(value, "z", scenarioPath, objectPath);
8026
+ const x = optionalNumber2(value, "x", scenarioPath, objectPath);
8027
+ const z = optionalNumber2(value, "z", scenarioPath, objectPath);
6363
8028
  if (x === void 0 || z === void 0) {
6364
8029
  throw invalidStep(scenarioPath, `Scenario ${objectPath} must define finite x and z world coordinates.`);
6365
8030
  }
@@ -6413,6 +8078,9 @@ function validateStepLabels(steps, assertions, scenarioPath) {
6413
8078
  requireLabel(step.label, `assert.components[${index}].atSteps[${stepIndex}].label`);
6414
8079
  }
6415
8080
  }
8081
+ for (const [index, assertion] of (assertions.tone ?? []).entries()) {
8082
+ requireLabel(assertion.atStep, `assert.tone[${index}].atStep`);
8083
+ }
6416
8084
  for (const [index, assertion] of (assertions.signals ?? []).entries()) {
6417
8085
  requireLabel(assertion.atStep, `assert.signals[${index}].atStep`);
6418
8086
  }
@@ -6453,7 +8121,13 @@ function validateAssertions(value, scenarioPath) {
6453
8121
  if (Array.isArray(value.signals) && value.signals.length === 0) {
6454
8122
  throw invalidScenario(scenarioPath, "Assertion 'assert.signals' must contain at least one signal assertion.");
6455
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
+ }
6456
8127
  const movement = isRecord3(value.movement) ? value.movement : void 0;
8128
+ if (movement !== void 0) {
8129
+ validateMovementBounds(movement, scenarioPath);
8130
+ }
6457
8131
  const camera = isRecord3(value.camera) ? value.camera : void 0;
6458
8132
  if (camera !== void 0 && !(typeof camera.within === "number" && Number.isFinite(camera.within) || camera.targetInViewport === true)) {
6459
8133
  throw invalidScenario(
@@ -6472,6 +8146,7 @@ function validateAssertions(value, scenarioPath) {
6472
8146
  ) : void 0;
6473
8147
  const renderChain = value.renderChain === void 0 ? void 0 : validateRenderChainAssertion(value.renderChain, scenarioPath, "assert.renderChain");
6474
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");
6475
8150
  const scene = value.scene === void 0 ? void 0 : validateSceneAssertion(value.scene, scenarioPath, "assert.scene");
6476
8151
  const geometry = value.geometry === void 0 ? void 0 : validateGeometryCaptureRequest(value.geometry, scenarioPath, "assert.geometry");
6477
8152
  const world = isRecord3(value.world) ? value.world : void 0;
@@ -6523,6 +8198,7 @@ function validateAssertions(value, scenarioPath) {
6523
8198
  ...performance === void 0 ? {} : { performance },
6524
8199
  ...renderChain === void 0 ? {} : { renderChain },
6525
8200
  ...startup === void 0 ? {} : { startup },
8201
+ ...pipelineCensus === void 0 ? {} : { pipelineCensus },
6526
8202
  ...scene === void 0 ? {} : { scene },
6527
8203
  ...geometry === void 0 ? {} : { geometry },
6528
8204
  ...hasKey(value, "causedBy") ? {
@@ -6580,10 +8256,30 @@ function validateAssertions(value, scenarioPath) {
6580
8256
  ...Array.isArray(value.states) ? { states: value.states.map((entry, index) => validateStateAssertion(entry, scenarioPath, `assert.states[${index}]`)) } : {},
6581
8257
  ...Array.isArray(value.tags) ? { tags: value.tags.map((entry, index) => validateTagCountAssertion(entry, scenarioPath, `assert.tags[${index}]`)) } : {},
6582
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}]`)) } : {},
6583
8260
  ...Array.isArray(value.visual) ? { visual: value.visual.map((entry, index) => validateVisualAssertion(entry, scenarioPath, `assert.visual[${index}]`)) } : {},
6584
8261
  ...world === void 0 ? {} : { world: validateWorldAssertion(world, scenarioPath) }
6585
8262
  };
6586
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
+ }
6587
8283
  function validateAudioAssertion(value, scenarioPath, objectPath) {
6588
8284
  const record4 = requireRecord(value, scenarioPath, objectPath);
6589
8285
  rejectUnknownKeys(record4, ["cue", "maxPlays", "minGapMs", "minPlays"], scenarioPath, objectPath);
@@ -6625,7 +8321,7 @@ function validateWorldAssertion(value, scenarioPath) {
6625
8321
  if (portable !== void 0 && typeof portable !== "boolean") {
6626
8322
  throw invalidScenario(scenarioPath, "'assert.world.runtime.portable' must be a boolean.");
6627
8323
  }
6628
- const randomState = optionalNumber(runtime, "randomState", scenarioPath, "assert.world.runtime");
8324
+ const randomState = optionalNumber2(runtime, "randomState", scenarioPath, "assert.world.runtime");
6629
8325
  if (randomState === void 0 || !Number.isInteger(randomState)) {
6630
8326
  throw invalidScenario(scenarioPath, "'assert.world.runtime.randomState' must be an integer.");
6631
8327
  }
@@ -6711,8 +8407,8 @@ function validateComponentAssertion(value, scenarioPath, objectPath) {
6711
8407
  ...present("allowTrivial", optionalTrivialityReason(record4, "allowTrivial", scenarioPath, objectPath)),
6712
8408
  // As above: any JSON value is a legal comparison target.
6713
8409
  ...hasKey(record4, "equals") ? { equals: record4.equals } : {},
6714
- ...present("gte", optionalNumber(record4, "gte", scenarioPath, objectPath)),
6715
- ...present("lte", optionalNumber(record4, "lte", scenarioPath, objectPath)),
8410
+ ...present("gte", optionalNumber2(record4, "gte", scenarioPath, objectPath)),
8411
+ ...present("lte", optionalNumber2(record4, "lte", scenarioPath, objectPath)),
6716
8412
  ...present("path", optionalString(record4, "path", scenarioPath, objectPath))
6717
8413
  };
6718
8414
  }
@@ -6796,6 +8492,60 @@ function validateGeometryCaptureRequest(value, scenarioPath, objectPath) {
6796
8492
  ...record4.timeoutMs === void 0 ? {} : { timeoutMs: record4.timeoutMs }
6797
8493
  };
6798
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
+ }
6799
8549
 
6800
8550
  // src/scenario.ts
6801
8551
  async function loadPlaytestScenario(projectPath, scenarioPath) {