@threenative/playtest 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { writeFile, mkdtemp, rm, mkdir, access, readFile, unlink, rename } from 'fs/promises';
1
+ import { writeFile, stat, mkdtemp, rm, mkdir, access, readFile, unlink, rename, readdir, copyFile } from 'fs/promises';
2
2
  import { join, resolve, basename, dirname } from 'path';
3
3
  import { execFile, spawn } from 'child_process';
4
4
  import { existsSync } from 'fs';
@@ -25,10 +25,11 @@ var PLAYTEST_CAPABILITY_REGISTRY = [
25
25
  capability("runtime.audio", "Samples application-owned audio runtime state."),
26
26
  capability("runtime.components", "Samples registered JSON-safe component state."),
27
27
  capability("runtime.contacts", "Samples bounded collision and trigger contacts."),
28
- capability("runtime.diagnostics", "Samples application-owned runtime diagnostics."),
28
+ capability("runtime.diagnostics", "Captures application runtime errors."),
29
29
  capability("runtime.events", "Drains bounded application event observations."),
30
30
  capability("runtime.fixedStep", "Advances an application-owned deterministic tick."),
31
31
  capability("runtime.physics", "Samples bounded application-owned physics observations."),
32
+ capability("runtime.performance", "Samples bounded per-render frame cost and renderer counts."),
32
33
  capability("runtime.resources", "Reads and writes registered JSON-safe application state."),
33
34
  capability("runtime.state", "Samples application-owned state-machine state."),
34
35
  capability("runtime.tags", "Samples bounded application-owned entity tags."),
@@ -49,6 +50,30 @@ function capability(name, description) {
49
50
 
50
51
  // src/assertions.ts
51
52
  var PLAYTEST_ASSERTION_REGISTRY = [
53
+ {
54
+ description: "Samples the framebuffer on every render frame inside a labeled loading window and requires every coarse-grid RGB sample to match the declared backdrop.",
55
+ example: {
56
+ framebufferCoverage: {
57
+ backdrop: [5, 7, 11],
58
+ grid: { columns: 32, rows: 18 },
59
+ tolerance: 8,
60
+ window: { endStep: "loading-end", startStep: "loading-start" }
61
+ }
62
+ },
63
+ fields: [
64
+ { description: "Backdrop RGB byte channels every sampled pixel must match.", name: "backdrop", required: true, type: "[integer 0..255, integer 0..255, integer 0..255]" },
65
+ { description: "Coarse sample grid. Defaults to 32x18, which catches the loading leak while limiting synchronous readback work.", name: "grid", type: "{ columns: positive integer <= 256, rows: positive integer <= 256 }" },
66
+ { description: "Maximum absolute difference allowed for each RGB channel.", name: "tolerance", required: true, type: "integer 0..255" },
67
+ { description: "Inclusive labeled-step boundaries for the loading-covered interval.", name: "window", required: true, type: "{ startStep: string, endStep: string }" }
68
+ ],
69
+ cardinality: "object",
70
+ kind: "framebufferCoverage",
71
+ observationPath: "framebufferCoverage",
72
+ requiredCapabilities: ["browser.screenshot"],
73
+ resultIdPrefix: "framebufferCoverage",
74
+ supportedOn: ["web", "desktop", "bevy"],
75
+ triviality: "not-applicable"
76
+ },
52
77
  {
53
78
  description: "Checks every consecutive platform against a measured static movement-envelope fit; it does not simulate traversal, walls, ceilings, run-up, or air control.",
54
79
  example: { reachability: { artifact: "artifacts/character-envelope/player.json", entities: ["platform.a", "platform.b"] } },
@@ -101,7 +126,7 @@ var PLAYTEST_ASSERTION_REGISTRY = [
101
126
  description: "Proves the subject moved, reached a minimum velocity, or changed rotation during held input.",
102
127
  example: { movement: { entity: "player", minDistance: 0.5, minVelocity: 0.01, rotationChanged: true } },
103
128
  fields: [
104
- { description: "Entity id to measure. Defaults to scenario subject.", name: "entity", type: "string" },
129
+ { description: "Optional entity id to measure; when omitted, choose an observed mover.", name: "entity", type: "string" },
105
130
  { description: "Require distance to a fixed world position to decrease by at least min.", name: "closesDistanceToPosition", type: "{ position: [number, number, number], min: number }" },
106
131
  { description: "Maximum yaw error from resolved movement direction.", name: "facesMovementWithinDegrees", type: "number" },
107
132
  { description: "Expected movement axis: x, y, or z.", name: "axis", type: "string" },
@@ -221,10 +246,10 @@ var PLAYTEST_ASSERTION_REGISTRY = [
221
246
  triviality: "not-applicable"
222
247
  },
223
248
  {
224
- description: "Proves an entity's final runtime-owned state-machine state.",
225
- example: { states: [{ entity: "guard", equals: "chase" }] },
249
+ description: "Proves an observed entity's final runtime-owned state-machine state.",
250
+ example: { states: [{ equals: "completed" }] },
226
251
  fields: [
227
- { description: "Entity carrying the StateMachine component.", name: "entity", required: true, type: "string" },
252
+ { description: "Optional entity id; when omitted, choose an observed state candidate.", name: "entity", type: "string" },
228
253
  { description: "Expected current state name.", name: "equals", required: true, type: "string" }
229
254
  ],
230
255
  cardinality: "array",
@@ -281,6 +306,8 @@ var PLAYTEST_ASSERTION_REGISTRY = [
281
306
  { description: "Fail on captured console errors.", name: "noConsoleErrors", type: "boolean" },
282
307
  { description: "Fail on captured network errors.", name: "noNetworkErrors", type: "boolean" },
283
308
  { description: "Fail on runtime diagnostics.", name: "noRuntimeDiagnostics", type: "boolean" },
309
+ { description: "Required bounded justification when noConsoleErrors is false.", name: "consoleErrorsOptOutReason", type: "non-empty string" },
310
+ { description: "Required bounded justification when noNetworkErrors is false.", name: "networkErrorsOptOutReason", type: "non-empty string" },
284
311
  { description: "Required bounded justification when noRuntimeDiagnostics is false.", name: "runtimeDiagnosticsOptOutReason", type: "non-empty string" },
285
312
  { description: "Require runtime readiness.", name: "runtimeReady", type: "boolean" }
286
313
  ],
@@ -292,6 +319,22 @@ var PLAYTEST_ASSERTION_REGISTRY = [
292
319
  supportedOn: ["web"],
293
320
  triviality: "not-applicable"
294
321
  },
322
+ {
323
+ description: "Proves a live render sample exists and optionally bounds frame time, draw calls, and triangles.",
324
+ example: { performance: { maxDrawCalls: 100, maxFrameMsP95: 33, maxTriangles: 1e4 } },
325
+ fields: [
326
+ { description: "Maximum nearest-rank 95th-percentile frame time in milliseconds.", name: "maxFrameMsP95", type: "number" },
327
+ { description: "Maximum observed renderer draw-call count.", name: "maxDrawCalls", type: "number" },
328
+ { description: "Maximum observed renderer triangle count.", name: "maxTriangles", type: "number" }
329
+ ],
330
+ cardinality: "object",
331
+ kind: "performance",
332
+ observationPath: "performanceSeries",
333
+ requiredCapabilities: ["runtime.performance"],
334
+ resultIdPrefix: "performance.",
335
+ supportedOn: ["web", "desktop", "bevy"],
336
+ triviality: "not-applicable"
337
+ },
295
338
  {
296
339
  description: "Proves projected entity visibility in the viewport.",
297
340
  example: { visibility: [{ entity: "player", minProjectedPixels: 1200, maxOffscreenRatio: 0.05 }] },
@@ -329,7 +372,7 @@ var PLAYTEST_ASSERTION_REGISTRY = [
329
372
  example: { contacts: [{ entity: "player", with: "pickup", kind: "trigger", minCount: 1 }] },
330
373
  fields: [
331
374
  { description: "Retained step label to inspect instead of the full observation history.", name: "atStep", type: "string" },
332
- { description: "Entity id. Defaults to scenario subject.", name: "entity", type: "string" },
375
+ { description: "Optional entity id; when omitted, choose an observed contact candidate.", name: "entity", type: "string" },
333
376
  { description: "Other entity or tag token expected in the contact evidence.", name: "with", type: "string" },
334
377
  { description: "Contact kind token, such as contact or trigger.", name: "kind", type: "string" },
335
378
  { description: "Minimum number of matching observations.", name: "minCount", type: "number" },
@@ -345,10 +388,10 @@ var PLAYTEST_ASSERTION_REGISTRY = [
345
388
  triviality: "not-applicable"
346
389
  },
347
390
  {
348
- description: "Proves matching physics bodies are asleep in a retained physics-debug sample.",
349
- example: { settled: [{ atStep: "fall-and-settle", entity: "enemy.default/0/", minBodies: 15 }] },
391
+ description: "Proves an observed cohort of matching physics bodies is asleep in a retained physics-debug sample.",
392
+ example: { settled: [{ atStep: "fall-and-settle", minBodies: 15 }] },
350
393
  fields: [
351
- { description: "Exact entity id or stable entity-id prefix.", name: "entity", required: true, type: "string" },
394
+ { description: "Optional exact entity id or stable entity-id prefix; when omitted, choose an observed cohort.", name: "entity", type: "string" },
352
395
  { description: "Optional labeled step whose physics-debug sample must be used.", name: "atStep", type: "string" },
353
396
  { description: "Minimum number of matching bodies required.", name: "minBodies", type: "positive integer" },
354
397
  { description: "Optional earlier labeled step whose matching body positions are compared.", name: "compareToStep", type: "string" },
@@ -410,7 +453,7 @@ var PLAYTEST_SETUP_REGISTRY = [
410
453
  ];
411
454
  function requiredPlaytestCapabilities(scenario) {
412
455
  const required = /* @__PURE__ */ new Set();
413
- if (scenario.steps.some((step) => step.kind !== "wait" && (step.press !== void 0 || step.pointerPosition !== void 0))) {
456
+ if (scenario.steps.some((step) => step.kind !== "wait" && (step.press !== void 0 || step.pointerPosition !== void 0 || step.pointers !== void 0))) {
414
457
  required.add("browser.input");
415
458
  }
416
459
  if (scenario.artifacts?.screenshots !== false) {
@@ -435,10 +478,75 @@ function requiredPlaytestCapabilities(scenario) {
435
478
  }
436
479
  return [...required].sort();
437
480
  }
481
+ function resolveDiagnosticsPolicy(policy) {
482
+ return {
483
+ ...policy?.consoleErrorsOptOutReason === void 0 ? {} : { consoleErrorsOptOutReason: policy.consoleErrorsOptOutReason },
484
+ ...policy?.networkErrorsOptOutReason === void 0 ? {} : { networkErrorsOptOutReason: policy.networkErrorsOptOutReason },
485
+ noConsoleErrors: policy?.noConsoleErrors ?? true,
486
+ noNetworkErrors: policy?.noNetworkErrors ?? true,
487
+ noRuntimeDiagnostics: policy?.noRuntimeDiagnostics ?? true,
488
+ ...policy?.runtimeReady === void 0 ? {} : { runtimeReady: policy.runtimeReady },
489
+ ...policy?.runtimeDiagnosticsOptOutReason === void 0 ? {} : { runtimeDiagnosticsOptOutReason: policy.runtimeDiagnosticsOptOutReason }
490
+ };
491
+ }
438
492
  function evaluateRichPlaytestAssertions(input) {
439
493
  const assertions = [];
440
494
  const diagnostics = [];
441
495
  const scenarioAssertions = input.scenario.assert ?? {};
496
+ if (scenarioAssertions.framebufferCoverage !== void 0) {
497
+ const observation = input.report.observations?.framebufferCoverage;
498
+ const started = observation?.windowStarted === true;
499
+ const completed = observation?.windowCompleted === true;
500
+ const framesObserved = (observation?.frameCount ?? 0) > 0;
501
+ const readable = observation?.unreadableReason === void 0;
502
+ const violation = observation?.firstViolation;
503
+ const evidenceComplete = violation === void 0 || violation.grid.samples.length === violation.grid.columns * violation.grid.rows && violation.screenshotPath.length > 0;
504
+ const pass = started && completed && framesObserved && readable && violation === void 0 && evidenceComplete;
505
+ assertions.push({
506
+ details: {
507
+ boundarySource: observation?.boundarySource ?? null,
508
+ evidenceComplete,
509
+ firstViolation: violation ?? null,
510
+ frameCount: observation?.frameCount ?? 0,
511
+ unreadableReason: observation?.unreadableReason ?? null,
512
+ windowCompleted: completed,
513
+ windowStarted: started
514
+ },
515
+ id: "framebufferCoverage",
516
+ pass
517
+ });
518
+ if (!readable) {
519
+ diagnostics.push({
520
+ code: "TN_PLAYTEST_FRAMEBUFFER_PIXELS_UNREADABLE",
521
+ message: `Framebuffer pixels could not be read: ${observation?.unreadableReason}.`,
522
+ severity: "error",
523
+ suggestion: "On headless Linux, prefix the command with xvfb-run -a -s '-screen 0 1600x900x24'."
524
+ });
525
+ } else if (!started || !completed) {
526
+ diagnostics.push({
527
+ code: "TN_PLAYTEST_FRAMEBUFFER_WINDOW_NOT_REACHED",
528
+ message: !started ? "The run never reached the declared framebuffer coverage window." : "The run entered but never completed the declared framebuffer coverage window.",
529
+ severity: "error",
530
+ suggestion: "Check the assertion's startStep/endStep labels and keep the run alive through the complete loading interval."
531
+ });
532
+ } else if (!framesObserved) {
533
+ diagnostics.push({
534
+ code: "TN_PLAYTEST_FRAMEBUFFER_FRAMES_MISSING",
535
+ message: "The framebuffer coverage window completed without observing any render frames.",
536
+ severity: "error",
537
+ suggestion: "Keep at least one requestAnimationFrame-driven frame inside the labeled loading window."
538
+ });
539
+ } else if (violation !== void 0) {
540
+ diagnostics.push({
541
+ artifactPath: violation.screenshotPath,
542
+ code: evidenceComplete ? "TN_PLAYTEST_FRAMEBUFFER_COVERAGE_FAILED" : "TN_PLAYTEST_FRAMEBUFFER_EVIDENCE_MISSING",
543
+ message: evidenceComplete ? `Framebuffer coverage first diverged from the declared backdrop at frame ${violation.frameIndex}.` : `Framebuffer coverage diverged at frame ${violation.frameIndex}, but its grid or screenshot evidence is incomplete.`,
544
+ observedRuntimePath: "observations.json/framebufferCoverage/firstViolation/grid",
545
+ severity: "error",
546
+ suggestion: "Inspect the violating-frame screenshot and RGB sample grid; fix the render pass that drew during the loading-covered window."
547
+ });
548
+ }
549
+ }
442
550
  if (scenarioAssertions.reachability !== void 0) {
443
551
  const { entities, envelope } = scenarioAssertions.reachability;
444
552
  for (let index = 0; index < entities.length - 1; index += 1) {
@@ -492,8 +600,17 @@ function evaluateRichPlaytestAssertions(input) {
492
600
  suggestion: "Inspect observations.json/overlayNodes and verify the overlay subscription, selector, attribute, and computed style."
493
601
  });
494
602
  }
495
- const hasVisualSamples = input.report.observations?.visual !== void 0;
496
- if ((scenarioAssertions.visual?.length ?? 0) > 0 && !hasVisualSamples) {
603
+ const captureFailure = input.report.observations?.visual?.captureFailure;
604
+ const hasVisualSamples = input.report.observations?.visual !== void 0 && captureFailure === void 0;
605
+ if ((scenarioAssertions.visual?.length ?? 0) > 0 && captureFailure !== void 0) {
606
+ for (const [index] of scenarioAssertions.visual.entries()) {
607
+ assertions.push({
608
+ details: { captureFailure, reason: "not-evaluated" },
609
+ id: `visual.${index}`,
610
+ pass: true
611
+ });
612
+ }
613
+ } else if ((scenarioAssertions.visual?.length ?? 0) > 0 && !hasVisualSamples) {
497
614
  for (const [index] of scenarioAssertions.visual.entries()) {
498
615
  assertions.push({ id: `visual.${index}`, pass: false, details: { reason: "target-unsupported", target: input.scenario.target } });
499
616
  diagnostics.push(assertionNotEvaluatedDiagnostic(`visual.${index}`, `target '${input.scenario.target}' does not expose visual assertion samples`));
@@ -542,6 +659,15 @@ function evaluateRichPlaytestAssertions(input) {
542
659
  if (!pass) diagnostics.push({ code: "TN_PLAYTEST_ENTITY_VISIBILITY_DROPPED", message: `Entity '${visual.entityVisible.entity}' dropped below ${visual.entityVisible.minProjectedPixels} projected pixels.`, severity: "error", suggestion: "Check per-frame visibility, camera clipping, scale, and renderer state." });
543
660
  }
544
661
  }
662
+ if (scenarioAssertions.performance !== void 0) {
663
+ const result = evaluatePerformanceAssertion(
664
+ scenarioAssertions.performance,
665
+ input.report.observations?.performanceSeries,
666
+ input.scenario.sourcePath
667
+ );
668
+ assertions.push(...result.assertions);
669
+ diagnostics.push(...result.diagnostics);
670
+ }
545
671
  for (const assertion of scenarioAssertions.resources ?? []) {
546
672
  if (assertion.anyOf !== void 0) {
547
673
  const result = evaluateResourceAnyOfAssertion(assertion, input.report.observations?.resources[assertion.id], {
@@ -721,31 +847,27 @@ function evaluateRichPlaytestAssertions(input) {
721
847
  diagnostics.push(result.diagnostic);
722
848
  }
723
849
  }
724
- for (const assertion of scenarioAssertions.states ?? []) {
725
- const result = evaluateStateAssertion(assertion, input.report.observations?.runtimeObservations);
850
+ for (const [stateIndex, assertion] of (scenarioAssertions.states ?? []).entries()) {
851
+ const result = evaluateStateAssertion(assertion, input.report.observations, input.scenario, stateIndex);
726
852
  assertions.push(result.assertion);
727
853
  if (result.diagnostic !== void 0) {
728
854
  diagnostics.push(result.diagnostic);
729
855
  }
730
856
  }
731
857
  {
732
- const diagnosticsPolicy = {
733
- ...scenarioAssertions.diagnostics,
734
- noRuntimeDiagnostics: scenarioAssertions.diagnostics?.noRuntimeDiagnostics ?? true
735
- };
858
+ const diagnosticsPolicy = resolveDiagnosticsPolicy(scenarioAssertions.diagnostics);
736
859
  const policyDiagnostics = evaluateDiagnosticsPolicy(input.report, diagnosticsPolicy);
737
860
  diagnostics.push(...policyDiagnostics);
738
- if (scenarioAssertions.diagnostics !== void 0 || policyDiagnostics.length > 0) {
739
- assertions.push({
740
- details: {
741
- consoleErrors: consoleErrors(input.report.observations?.console ?? []).length,
742
- networkErrors: input.report.observations?.network.length ?? 0,
743
- runtimeDiagnostics: runtimeDiagnostics(input.report.observations?.runtimeDiagnostics).length
744
- },
745
- id: "diagnostics",
746
- pass: policyDiagnostics.length === 0
747
- });
748
- }
861
+ assertions.push({
862
+ details: {
863
+ consoleErrors: consoleErrors(input.report.observations?.console ?? []).length,
864
+ networkErrors: input.report.observations?.network.length ?? 0,
865
+ policy: diagnosticsPolicy,
866
+ runtimeDiagnostics: runtimeDiagnostics(input.report.observations?.runtimeDiagnostics).length
867
+ },
868
+ id: "diagnostics",
869
+ pass: policyDiagnostics.length === 0
870
+ });
749
871
  }
750
872
  if (scenarioAssertions.movement?.minVelocity !== void 0) {
751
873
  const velocity = input.report.frames <= 0 ? 0 : input.report.distance / input.report.frames;
@@ -763,7 +885,7 @@ function evaluateRichPlaytestAssertions(input) {
763
885
  if (scenarioAssertions.movement?.minDistance !== void 0) {
764
886
  const pass = input.report.distance >= scenarioAssertions.movement.minDistance;
765
887
  assertions.push({
766
- details: { distance: input.report.distance, minimum: scenarioAssertions.movement.minDistance },
888
+ details: { distance: input.report.distance, entity: input.report.entity, minimum: scenarioAssertions.movement.minDistance },
767
889
  id: "movement.distance",
768
890
  pass
769
891
  });
@@ -991,36 +1113,48 @@ function evaluateRichPlaytestAssertions(input) {
991
1113
  diagnostics.push(result.diagnostic);
992
1114
  }
993
1115
  }
994
- for (const assertion of scenarioAssertions.contacts ?? []) {
995
- const entity = assertion.entity ?? input.scenario.subject ?? input.report.entity;
1116
+ for (const [contactIndex, assertion] of (scenarioAssertions.contacts ?? []).entries()) {
1117
+ const entity = assertion.entity ?? input.scenario.subject;
1118
+ const anonymous = entity === void 0;
996
1119
  if (assertion.requiredOn !== void 0 && !assertion.requiredOn.includes(input.scenario.target)) {
997
1120
  assertions.push({
998
- details: { entity, requiredOn: assertion.requiredOn, skipped: true, target: input.scenario.target },
999
- id: `contact.${entity}`,
1121
+ details: { entity: entity || "anonymous", requiredOn: assertion.requiredOn, skipped: true, target: input.scenario.target },
1122
+ id: assertion.entity === void 0 ? `contact.${contactIndex}` : `contact.${entity}`,
1000
1123
  pass: true
1001
1124
  });
1002
1125
  continue;
1003
1126
  }
1004
1127
  const tokens = [entity, assertion.with, assertion.kind].filter((item) => item !== void 0);
1005
1128
  const selectedSample = assertion.atStep === void 0 ? void 0 : input.report.observations?.physicsDebugSeries?.find((sample) => sample.label === assertion.atStep);
1006
- const stepAvailable = assertion.atStep === void 0 || selectedSample !== void 0;
1129
+ const runtimeStepAvailable = assertion.atStep === void 0 || runtimeGameplayAtStep(input.report.observations?.runtimeObservations, assertion.atStep) !== void 0;
1130
+ const stepAvailable = assertion.atStep === void 0 || selectedSample !== void 0 || runtimeStepAvailable;
1007
1131
  const effectEvidence = assertion.atStep === void 0 ? mergeEffectLogs(input.report.effectLog, input.report.observations?.effectLogSeries) : [];
1008
1132
  const effectCount = countMatchingEntries(effectEvidence, tokens);
1009
1133
  const runtimeCount = assertion.atStep === void 0 ? countRuntimeContacts(input.report.observations?.runtimeObservations, entity, assertion.with, assertion.kind) : 0;
1010
- const physicsDebugCount = assertion.kind === void 0 || assertion.kind === "contact" ? countPhysicsDebugContacts(input.report.observations, entity, assertion.with, selectedSample?.snapshot) : 0;
1011
- const count = effectCount + physicsDebugCount + runtimeCount;
1134
+ const physicsEvidence = assertion.kind === void 0 || assertion.kind === "contact" ? physicsDebugContactEvidence(input.report.observations, entity, assertion.with, selectedSample?.snapshot) : { candidates: [], count: 0 };
1135
+ const runtimeEvidence = runtimeContactEvidence(
1136
+ input.report.observations?.runtimeObservations,
1137
+ entity,
1138
+ assertion.with,
1139
+ assertion.kind,
1140
+ assertion.atStep
1141
+ );
1142
+ const candidates = [.../* @__PURE__ */ new Set([...physicsEvidence.candidates, ...runtimeEvidence.candidates])];
1143
+ const count = effectCount + physicsEvidence.count + (assertion.atStep === void 0 ? runtimeCount : runtimeEvidence.count);
1012
1144
  const minCount = assertion.minCount ?? (assertion.maxCount === void 0 ? 1 : 0);
1013
- const pass = stepAvailable && count >= minCount && (assertion.maxCount === void 0 || count <= assertion.maxCount);
1014
- assertions.push({ details: { atStep: assertion.atStep, count, entity, kind: assertion.kind, maxCount: assertion.maxCount, minCount, with: assertion.with }, id: `contact.${entity}`, pass });
1145
+ const candidatesAvailable = !anonymous || candidates.length > 0;
1146
+ const pass = stepAvailable && candidatesAvailable && count >= minCount && (assertion.maxCount === void 0 || count <= assertion.maxCount);
1147
+ const resultEntity = entity || "anonymous";
1148
+ assertions.push({ details: { atStep: assertion.atStep, candidates, count, entity: resultEntity, kind: assertion.kind, maxCount: assertion.maxCount, minCount, with: assertion.with }, id: assertion.entity === void 0 ? `contact.${contactIndex}` : `contact.${resultEntity}`, pass });
1015
1149
  if (!pass) {
1016
1150
  const partial = summarizeMatchingEntries(effectEvidence, [entity, assertion.with].filter((item) => item !== void 0));
1017
1151
  const hasPhysicsDebugEvidence = input.report.observations?.physicsDebug !== void 0 || (input.report.observations?.physicsDebugSeries?.length ?? 0) > 0;
1018
1152
  diagnostics.push({
1019
1153
  artifactPath: partial !== void 0 || !hasPhysicsDebugEvidence ? "effect-log.json" : "observations.json",
1020
- code: !stepAvailable ? "TN_PLAYTEST_CONTACT_STEP_NOT_OBSERVED" : assertion.maxCount !== void 0 && count > assertion.maxCount ? "TN_PLAYTEST_CONTACT_COUNT_EXCEEDED" : "TN_PLAYTEST_CONTACT_NOT_OBSERVED",
1021
- message: !stepAvailable ? `Contact assertion step '${assertion.atStep}' was not retained.` : assertion.maxCount !== void 0 && count > assertion.maxCount ? `Contact/trigger for '${entity}' was observed ${count} time(s), above allowed ${assertion.maxCount}.` : `Expected contact/trigger for '${entity}' was not observed ${minCount} time(s).`,
1022
- observedRuntimePath: `observations.json/physicsDebugSeries/artifact/primitives[category=contact,entity=${entity}] | effect-log.json/entries[kind=service|event,entity=${entity}]`,
1023
- path: `${input.scenario.sourcePath ?? "playtest"}/assert/contacts/${entity}`,
1154
+ code: !stepAvailable ? "TN_PLAYTEST_CONTACT_STEP_NOT_OBSERVED" : !candidatesAvailable ? "TN_PLAYTEST_CONTACT_CANDIDATES_UNAVAILABLE" : assertion.maxCount !== void 0 && count > assertion.maxCount ? "TN_PLAYTEST_CONTACT_COUNT_EXCEEDED" : "TN_PLAYTEST_CONTACT_NOT_OBSERVED",
1155
+ message: !stepAvailable ? `Contact assertion step '${assertion.atStep}' was not retained.` : !candidatesAvailable ? "No observed contact candidate was retained for the anonymous contact assertion." : assertion.maxCount !== void 0 && count > assertion.maxCount ? `Contact/trigger for '${resultEntity}' was observed ${count} time(s), above allowed ${assertion.maxCount}.` : `Expected contact/trigger for '${resultEntity}' was not observed ${minCount} time(s).`,
1156
+ observedRuntimePath: `observations.json/physicsDebugSeries/artifact/primitives[category=contact,entity=${resultEntity}] | effect-log.json/entries[kind=service|event,entity=${resultEntity}]`,
1157
+ path: `${input.scenario.sourcePath ?? "playtest"}/assert/contacts/${resultEntity}`,
1024
1158
  severity: "error",
1025
1159
  ...input.scenario.sourcePath === void 0 ? {} : { sourcePath: input.scenario.sourcePath },
1026
1160
  ...partial?.systemId === void 0 ? {} : { systemId: partial.systemId, sourcePath: partial.sourcePath },
@@ -1028,34 +1162,39 @@ function evaluateRichPlaytestAssertions(input) {
1028
1162
  });
1029
1163
  }
1030
1164
  }
1031
- for (const assertion of scenarioAssertions.settled ?? []) {
1165
+ for (const [settledIndex, assertion] of (scenarioAssertions.settled ?? []).entries()) {
1032
1166
  if (assertion.requiredOn !== void 0 && !assertion.requiredOn.includes(input.scenario.target)) {
1033
1167
  assertions.push({
1034
- details: { entity: assertion.entity, requiredOn: assertion.requiredOn, skipped: true, target: input.scenario.target },
1035
- id: `settled.${assertion.entity}`,
1168
+ details: { entity: assertion.entity ?? "anonymous", requiredOn: assertion.requiredOn, skipped: true, target: input.scenario.target },
1169
+ id: `settled.${assertion.entity ?? "anonymous"}`,
1036
1170
  pass: true
1037
1171
  });
1038
1172
  continue;
1039
1173
  }
1040
1174
  const snapshot = assertion.atStep === void 0 ? input.report.observations?.physicsDebugSeries?.at(-1)?.snapshot ?? input.report.observations?.physicsDebug : input.report.observations?.physicsDebugSeries?.find((sample) => sample.label === assertion.atStep)?.snapshot;
1041
- const bodies = physicsDebugSleepStates(snapshot, assertion.entity);
1042
1175
  const minimum = assertion.minBodies ?? 1;
1176
+ const candidate = settledCandidate(snapshot, assertion.entity);
1177
+ const bodies = candidate?.bodies ?? [];
1178
+ const omittedBodies = physicsDebugOmittedBodies(snapshot);
1043
1179
  const sleeping = bodies.filter((body) => body.sleeping).length;
1044
1180
  const comparisonSnapshot = assertion.compareToStep === void 0 ? void 0 : input.report.observations?.physicsDebugSeries?.find((sample) => sample.label === assertion.compareToStep)?.snapshot;
1045
- const poseDistance = assertion.compareToStep === void 0 ? void 0 : physicsDebugMeanPoseDistance(snapshot, comparisonSnapshot, assertion.entity);
1181
+ const selectedEntity = candidate?.selector ?? assertion.entity ?? "";
1182
+ const poseDistance = assertion.compareToStep === void 0 ? void 0 : physicsDebugMeanPoseDistance(snapshot, comparisonSnapshot, selectedEntity);
1046
1183
  const posePass = assertion.minMeanPoseDistance === void 0 || poseDistance !== void 0 && poseDistance.sharedBodies >= minimum && poseDistance.mean >= assertion.minMeanPoseDistance;
1047
- const pass = bodies.length >= minimum && sleeping === bodies.length && posePass;
1184
+ const complete = omittedBodies === 0;
1185
+ const pass = complete && candidate !== void 0 && bodies.length >= minimum && sleeping === bodies.length && posePass;
1186
+ const resultEntity = candidate?.selector ?? assertion.entity ?? "anonymous";
1048
1187
  assertions.push({
1049
- details: { atStep: assertion.atStep, bodies: bodies.length, compareToStep: assertion.compareToStep, entity: assertion.entity, minimum, poseDistance, sleeping },
1050
- id: `settled.${assertion.entity}`,
1188
+ details: { atStep: assertion.atStep, bodies: bodies.length, candidates: candidate?.candidates ?? [], compareToStep: assertion.compareToStep, entity: resultEntity, minimum, omittedBodies, poseDistance, sleeping },
1189
+ id: assertion.entity === void 0 ? `settled.${settledIndex}` : `settled.${assertion.entity}`,
1051
1190
  pass
1052
1191
  });
1053
1192
  if (!pass) diagnostics.push({
1054
1193
  artifactPath: "observations.json",
1055
- code: !posePass ? "TN_PLAYTEST_RAGDOLL_POSE_NOT_DISTINCT" : "TN_PLAYTEST_PHYSICS_NOT_SETTLED",
1056
- message: !posePass ? `Expected mean settled-pose distance for '${assertion.entity}' to reach ${assertion.minMeanPoseDistance}m from step '${assertion.compareToStep}'; observed ${poseDistance?.mean ?? "unavailable"}m across ${poseDistance?.sharedBodies ?? 0} bodies.` : `Expected at least ${minimum} physics bod${minimum === 1 ? "y" : "ies"} matching '${assertion.entity}' to be asleep; observed ${sleeping} of ${bodies.length}.`,
1194
+ code: !complete ? "TN_PLAYTEST_PHYSICS_EVIDENCE_TRUNCATED" : !posePass ? "TN_PLAYTEST_RAGDOLL_POSE_NOT_DISTINCT" : "TN_PLAYTEST_PHYSICS_NOT_SETTLED",
1195
+ message: !complete ? `Physics evidence omitted ${omittedBodies} bod${omittedBodies === 1 ? "y" : "ies"}; settled cannot pass on a partial snapshot.` : !posePass ? `Expected mean settled-pose distance for '${resultEntity}' to reach ${assertion.minMeanPoseDistance}m from step '${assertion.compareToStep}'; observed ${poseDistance?.mean ?? "unavailable"}m across ${poseDistance?.sharedBodies ?? 0} bodies.` : `Expected at least ${minimum} physics bod${minimum === 1 ? "y" : "ies"} matching '${resultEntity}' to be asleep; observed ${sleeping} of ${bodies.length}.`,
1057
1196
  observedRuntimePath: "observations.json/physicsDebugSeries/artifact/primitives[category=sleep]",
1058
- path: `${input.scenario.sourcePath ?? "playtest"}/assert/settled/${assertion.entity}`,
1197
+ path: `${input.scenario.sourcePath ?? "playtest"}/assert/settled/${resultEntity}`,
1059
1198
  severity: "error",
1060
1199
  ...input.scenario.sourcePath === void 0 ? {} : { sourcePath: input.scenario.sourcePath },
1061
1200
  suggestion: "Allow a longer settle window or fix damping, contacts, joints, and persistent forces that keep the bodies awake."
@@ -1115,7 +1254,7 @@ function evaluateRichPlaytestAssertions(input) {
1115
1254
  assertions.push({ details: { reason: "registered-without-evaluator" }, id, pass: false });
1116
1255
  diagnostics.push(assertionNotEvaluatedDiagnostic(id, "the registered assertion produced no evaluator result"));
1117
1256
  }
1118
- if (assertions.length === 0) {
1257
+ if (assertions.length === 0 || scenarioAssertions.diagnostics === void 0 && !assertions.some(({ id }) => id !== "diagnostics")) {
1119
1258
  const id = "scenario.assertions";
1120
1259
  assertions.push({ details: { reason: "no-evaluated-assertions" }, id, pass: false });
1121
1260
  diagnostics.push({
@@ -1143,28 +1282,57 @@ function movementEnvelopeHorizontalLimit(envelope, rise) {
1143
1282
  if (envelope.maxRise === 0) return rise === 0 ? envelope.forwardReach : void 0;
1144
1283
  return envelope.forwardReach * (1 + Math.sqrt(dropFromApex / envelope.maxRise));
1145
1284
  }
1146
- function countPhysicsDebugContacts(observations, entity, withEntity, selectedSnapshot) {
1285
+ function physicsDebugContactEvidence(observations, entity, withEntity, selectedSnapshot) {
1147
1286
  const snapshots = selectedSnapshot === void 0 ? [
1148
1287
  observations?.physicsDebug,
1149
1288
  ...(observations?.physicsDebugSeries ?? []).map((sample) => sample.snapshot)
1150
1289
  ] : [selectedSnapshot];
1151
- let count = 0;
1290
+ const candidates = [];
1152
1291
  for (const snapshot of snapshots) {
1153
1292
  if (!isRecord(snapshot) || !isRecord(snapshot.artifact) || !Array.isArray(snapshot.artifact.primitives)) continue;
1154
- count += snapshot.artifact.primitives.filter((primitive) => {
1155
- if (!isRecord(primitive) || primitive.category !== "contact" || typeof primitive.id !== "string") return false;
1156
- return primitive.id.includes(entity) && (withEntity === void 0 || primitive.id.includes(withEntity));
1157
- }).length;
1293
+ for (const primitive of snapshot.artifact.primitives) {
1294
+ if (!isRecord(primitive) || primitive.category !== "contact" || typeof primitive.id !== "string") continue;
1295
+ if (primitive.id.includes(entity ?? "") && (withEntity === void 0 || primitive.id.includes(withEntity))) {
1296
+ candidates.push(primitive.id);
1297
+ }
1298
+ }
1158
1299
  }
1159
- return count;
1300
+ return { candidates: [...new Set(candidates)], count: candidates.length };
1301
+ }
1302
+ function settledCandidate(snapshot, entity) {
1303
+ const bodies = physicsDebugSleepStates(snapshot, entity);
1304
+ if (entity !== void 0) {
1305
+ return bodies.length === 0 ? void 0 : { bodies, candidates: bodies.map(({ entity: body }) => body), selector: entity };
1306
+ }
1307
+ const groups = /* @__PURE__ */ new Map();
1308
+ for (const body of bodies) {
1309
+ const selector2 = bodySelector(body.entity);
1310
+ const group = groups.get(selector2) ?? [];
1311
+ group.push(body);
1312
+ groups.set(selector2, group);
1313
+ }
1314
+ const selected = [...groups.entries()].sort(([leftSelector, leftBodies], [rightSelector, rightBodies]) => rightBodies.length - leftBodies.length || leftSelector.localeCompare(rightSelector))[0];
1315
+ if (selected === void 0) return void 0;
1316
+ const [selector, selectedBodies] = selected;
1317
+ return { bodies: selectedBodies, candidates: selectedBodies.map(({ entity: body }) => body), selector };
1318
+ }
1319
+ function bodySelector(entity) {
1320
+ return /\d$/.test(entity) ? entity.replace(/\d+$/, "") : entity;
1160
1321
  }
1161
1322
  function physicsDebugSleepStates(snapshot, entity) {
1162
1323
  if (!isRecord(snapshot) || !isRecord(snapshot.artifact) || !Array.isArray(snapshot.artifact.primitives)) return [];
1163
1324
  return snapshot.artifact.primitives.flatMap((primitive) => {
1164
- if (!isRecord(primitive) || primitive.category !== "sleep" || typeof primitive.entity !== "string" || primitive.entity !== entity && !primitive.entity.startsWith(entity) || typeof primitive.value !== "number") return [];
1325
+ if (!isRecord(primitive) || primitive.category !== "sleep" || typeof primitive.entity !== "string" || entity !== void 0 && primitive.entity !== entity && !primitive.entity.startsWith(entity) || typeof primitive.value !== "number") return [];
1165
1326
  return [{ entity: primitive.entity, sleeping: primitive.value >= 1 }];
1166
1327
  });
1167
1328
  }
1329
+ function physicsDebugOmittedBodies(snapshot) {
1330
+ if (!isRecord(snapshot) || !isRecord(snapshot.artifact) || !isRecord(snapshot.artifact.overflow)) {
1331
+ return 0;
1332
+ }
1333
+ const omitted = snapshot.artifact.overflow.omittedBodies;
1334
+ return typeof omitted === "number" && Number.isInteger(omitted) && omitted >= 0 ? omitted : 1;
1335
+ }
1168
1336
  function physicsDebugMeanPoseDistance(snapshot, comparisonSnapshot, entity) {
1169
1337
  const positions = physicsDebugBodyPositions(snapshot, entity);
1170
1338
  const comparison = physicsDebugBodyPositions(comparisonSnapshot, entity);
@@ -1221,22 +1389,85 @@ function evaluateTagCountAssertion(assertion, observations) {
1221
1389
  }
1222
1390
  };
1223
1391
  }
1224
- function evaluateStateAssertion(assertion, observations) {
1225
- const gameplay = gameplayObservations(observations);
1392
+ function evaluateStateAssertion(assertion, observations, scenario, index) {
1393
+ const gameplay = gameplayObservations(runtimeObservationValue(observations));
1226
1394
  const states = isRecord(gameplay?.states) ? gameplay.states : void 0;
1227
- const observed = typeof states?.[assertion.entity] === "string" ? states[assertion.entity] : void 0;
1228
- const pass = observed === assertion.equals;
1229
- const result = { details: { entity: assertion.entity, expected: assertion.equals, observed: observed ?? null }, id: `states.${assertion.entity}`, pass };
1395
+ const candidates = Object.entries(states ?? {}).filter((entry) => typeof entry[1] === "string");
1396
+ const matching = assertion.entity === void 0 ? candidates.filter(([, state]) => state === assertion.equals) : candidates.filter(([entity]) => entity === assertion.entity);
1397
+ const terminalStep = assertion.entity === void 0 ? terminalContactStep(scenario, assertion.equals) : void 0;
1398
+ const terminal = terminalStep === void 0 ? { contactObserved: true, historyComplete: true, preExisting: false, preExistingEntities: [], step: null } : terminalStateEvidence(terminalStep, observations, scenario, matching.map(([entity]) => entity));
1399
+ const selected = matching.find(([entity]) => !terminal.preExistingEntities.includes(entity)) ?? matching[0];
1400
+ const selectedEntity = selected?.[0] ?? assertion.entity;
1401
+ const observed = selected?.[1];
1402
+ const selectedPreExisting = selected === void 0 ? terminal.preExisting : terminal.preExistingEntities.includes(selected[0]);
1403
+ const pass = observed === assertion.equals && terminal.contactObserved && terminal.historyComplete && !selectedPreExisting;
1404
+ const result = {
1405
+ details: {
1406
+ candidates: candidates.map(([entity, state]) => ({ entity, state })),
1407
+ entity: selectedEntity ?? "anonymous",
1408
+ expected: assertion.equals,
1409
+ observed: observed ?? null,
1410
+ terminal: { contactObserved: terminal.contactObserved, historyComplete: terminal.historyComplete, preExisting: selectedPreExisting, step: terminal.step }
1411
+ },
1412
+ id: assertion.entity === void 0 ? `states.${index}` : `states.${assertion.entity}`,
1413
+ pass
1414
+ };
1230
1415
  return pass ? { assertion: result } : {
1231
1416
  assertion: result,
1232
1417
  diagnostic: {
1233
- code: "TN_PLAYTEST_STATE_ASSERTION_FAILED",
1234
- message: `Entity '${assertion.entity}' state ${observed === void 0 ? "was unavailable" : `'${observed}'`} did not equal '${assertion.equals}'.`,
1418
+ code: observed === assertion.equals && (!terminal.contactObserved || !terminal.historyComplete || selectedPreExisting) ? "TN_PLAYTEST_STATE_ORDERING_FAILED" : "TN_PLAYTEST_STATE_ASSERTION_FAILED",
1419
+ message: observed === assertion.equals && (!terminal.contactObserved || !terminal.historyComplete || selectedPreExisting) ? `Terminal state '${assertion.equals}' was not observed after retained contact evidence at '${terminal.step ?? "an unavailable step"}'.` : `Entity '${selectedEntity ?? "anonymous"}' state ${observed === void 0 ? "was unavailable" : `'${observed}'`} did not equal '${assertion.equals}'.`,
1235
1420
  severity: "error",
1236
1421
  suggestion: "Ensure the entity has a StateMachine component and inspect runtimeObservations.gameplay.states in the playtest artifact."
1237
1422
  }
1238
1423
  };
1239
1424
  }
1425
+ function terminalContactStep(scenario, expectedState) {
1426
+ if (expectedState !== "won") return void 0;
1427
+ return [...scenario.assert?.contacts ?? []].reverse().find((assertion) => {
1428
+ const minimum = assertion.minCount ?? (assertion.maxCount === void 0 ? 1 : 0);
1429
+ return assertion.atStep !== void 0 && minimum > 0 && (assertion.requiredOn === void 0 || assertion.requiredOn.includes(scenario.target));
1430
+ })?.atStep;
1431
+ }
1432
+ function terminalStateEvidence(contactStep, observations, scenario, candidateEntities) {
1433
+ const contactAssertion = [...scenario.assert?.contacts ?? []].reverse().find((assertion) => assertion.atStep === contactStep);
1434
+ const contactObserved = contactAssertion === void 0 ? false : contactAssertionSatisfiedAtStep(contactAssertion, observations, scenario);
1435
+ const labeledSteps = scenario.steps.flatMap(({ label }) => label === void 0 ? [] : [label]);
1436
+ const contactIndex = labeledSteps.indexOf(contactStep);
1437
+ const samples = runtimeGameplaySeries(observations);
1438
+ const samplesByLabel = new Map(samples.map((sample) => [sample.label, sample.states]));
1439
+ const historyComplete = contactIndex >= 0 && labeledSteps.slice(0, contactIndex + 1).every((label) => samplesByLabel.has(label));
1440
+ const preExistingEntities = candidateEntities.filter((entity) => {
1441
+ if (contactIndex < 0) return false;
1442
+ return labeledSteps.slice(0, contactIndex).some((label) => samplesByLabel.get(label)?.[entity] === "won");
1443
+ });
1444
+ return {
1445
+ contactObserved,
1446
+ historyComplete,
1447
+ preExisting: preExistingEntities.length > 0,
1448
+ preExistingEntities,
1449
+ step: contactStep
1450
+ };
1451
+ }
1452
+ function contactAssertionSatisfiedAtStep(assertion, observations, scenario) {
1453
+ const selectedSample = physicsDebugSeries(observations).find((sample) => sample.label === assertion.atStep);
1454
+ const runtimeSamples = runtimeGameplaySeries(observations);
1455
+ const runtimeStepAvailable = runtimeSamples.some(({ label }) => label === assertion.atStep);
1456
+ const stepAvailable = selectedSample !== void 0 || runtimeStepAvailable;
1457
+ const entity = assertion.entity ?? scenario.subject;
1458
+ const anonymous = assertion.entity === void 0 && scenario.subject === void 0;
1459
+ const physicsEvidence = assertion.kind === void 0 || assertion.kind === "contact" ? physicsDebugContactEvidence(
1460
+ observationsForPhysics(observations),
1461
+ entity,
1462
+ assertion.with,
1463
+ selectedSample?.snapshot
1464
+ ) : { candidates: [], count: 0 };
1465
+ const runtimeEvidence = runtimeContactEvidence(observations, entity, assertion.with, assertion.kind, assertion.atStep);
1466
+ const candidates = [.../* @__PURE__ */ new Set([...physicsEvidence.candidates, ...runtimeEvidence.candidates])];
1467
+ const count = physicsEvidence.count + runtimeEvidence.count;
1468
+ const minimum = assertion.minCount ?? (assertion.maxCount === void 0 ? 1 : 0);
1469
+ return stepAvailable && (!anonymous || candidates.length > 0) && count >= minimum && (assertion.maxCount === void 0 || count <= assertion.maxCount);
1470
+ }
1240
1471
  function evaluateWorldAssertion(assertion, observations) {
1241
1472
  const gameplay = gameplayObservations(observations);
1242
1473
  const world = isRecord(gameplay?.world) ? gameplay.world : void 0;
@@ -1274,12 +1505,57 @@ function gameplayObservations(value) {
1274
1505
  const gameplay = value.gameplay;
1275
1506
  return isRecord(gameplay) ? gameplay : void 0;
1276
1507
  }
1508
+ function runtimeObservationValue(value) {
1509
+ if (!isRecord(value) || !Object.hasOwn(value, "runtimeObservations")) return value;
1510
+ return value.runtimeObservations;
1511
+ }
1512
+ function runtimeGameplaySamples(value) {
1513
+ const runtime = runtimeObservationValue(value);
1514
+ if (!isRecord(runtime) || !Array.isArray(runtime.gameplaySeries)) return [];
1515
+ return runtime.gameplaySeries.flatMap((entry) => {
1516
+ if (!isRecord(entry) || typeof entry.label !== "string") return [];
1517
+ const direct = isRecord(entry.gameplay) ? entry.gameplay : void 0;
1518
+ const nested = isRecord(entry.snapshot) && isRecord(entry.snapshot.gameplay) ? entry.snapshot.gameplay : void 0;
1519
+ return direct === void 0 && nested === void 0 ? [] : [{ gameplay: direct ?? nested, label: entry.label }];
1520
+ });
1521
+ }
1522
+ function runtimeGameplaySeries(value) {
1523
+ return runtimeGameplaySamples(value).map(({ gameplay, label }) => ({
1524
+ label,
1525
+ states: isRecord(gameplay.states) ? Object.fromEntries(Object.entries(gameplay.states).filter((entry) => typeof entry[1] === "string")) : {}
1526
+ }));
1527
+ }
1528
+ function runtimeGameplayAtStep(value, atStep) {
1529
+ const runtime = runtimeObservationValue(value);
1530
+ if (atStep === void 0) return gameplayObservations(runtime);
1531
+ return runtimeGameplaySamples(runtime).find(({ label }) => label === atStep)?.gameplay;
1532
+ }
1533
+ function physicsDebugSeries(value) {
1534
+ if (!isRecord(value) || !Array.isArray(value.physicsDebugSeries)) return [];
1535
+ return value.physicsDebugSeries.flatMap((sample) => {
1536
+ if (!isRecord(sample) || typeof sample.label !== "string") return [];
1537
+ return [{ label: sample.label, snapshot: sample.snapshot }];
1538
+ });
1539
+ }
1540
+ function observationsForPhysics(value) {
1541
+ return isRecord(value) ? value : void 0;
1542
+ }
1543
+ function runtimeContactEvidence(observations, entity, withEntity, kind, atStep) {
1544
+ const gameplay = runtimeGameplayAtStep(observations, atStep);
1545
+ if (!Array.isArray(gameplay?.contacts)) return { candidates: [], count: 0 };
1546
+ const candidates = [];
1547
+ for (const contact of gameplay.contacts) {
1548
+ if (!isRecord(contact) || typeof contact.entity !== "string" || typeof contact.with !== "string" || typeof contact.kind !== "string" || entity !== void 0 && contact.entity !== entity || withEntity !== void 0 && contact.with !== withEntity || kind !== void 0 && contact.kind !== kind) continue;
1549
+ candidates.push(`${contact.entity}:${contact.with}:${contact.kind}`);
1550
+ }
1551
+ return { candidates: [...new Set(candidates)], count: candidates.length };
1552
+ }
1277
1553
  function countRuntimeContacts(observations, entity, withEntity, kind) {
1278
1554
  const gameplay = gameplayObservations(observations);
1279
1555
  if (!Array.isArray(gameplay?.contacts)) return 0;
1280
1556
  return gameplay.contacts.filter((contact) => {
1281
1557
  if (!isRecord(contact)) return false;
1282
- return contact.entity === entity && (withEntity === void 0 || contact.with === withEntity) && (kind === void 0 || contact.kind === kind);
1558
+ return (entity === void 0 || contact.entity === entity) && (withEntity === void 0 || contact.with === withEntity) && (kind === void 0 || contact.kind === kind);
1283
1559
  }).length;
1284
1560
  }
1285
1561
  function runtimeAnimationObservations(value) {
@@ -1541,7 +1817,7 @@ function evaluateDiagnosticsPolicy(report, policy) {
1541
1817
  });
1542
1818
  }
1543
1819
  const capturedConsoleErrors = consoleErrors(report.observations?.console ?? []);
1544
- if (policy?.noConsoleErrors === true && capturedConsoleErrors.length > 0) {
1820
+ if (policy.noConsoleErrors && capturedConsoleErrors.length > 0) {
1545
1821
  diagnostics.push({
1546
1822
  code: "TN_PLAYTEST_CONSOLE_ERROR",
1547
1823
  message: `${capturedConsoleErrors.length} browser console error(s) were captured during playtest.`,
@@ -1549,7 +1825,7 @@ function evaluateDiagnosticsPolicy(report, policy) {
1549
1825
  suggestion: "Open console.json in the playtest artifact directory and fix the first runtime error."
1550
1826
  });
1551
1827
  }
1552
- if (policy?.noNetworkErrors === true && (report.observations?.network.length ?? 0) > 0) {
1828
+ if (policy.noNetworkErrors && (report.observations?.network.length ?? 0) > 0) {
1553
1829
  diagnostics.push({
1554
1830
  code: "TN_PLAYTEST_NETWORK_ERROR",
1555
1831
  message: `${report.observations?.network.length ?? 0} failed network request(s) were captured during playtest.`,
@@ -1558,7 +1834,7 @@ function evaluateDiagnosticsPolicy(report, policy) {
1558
1834
  });
1559
1835
  }
1560
1836
  const runtimeErrors = runtimeDiagnostics(report.observations?.runtimeDiagnostics);
1561
- if (policy?.noRuntimeDiagnostics === true && runtimeErrors.length > 0) {
1837
+ if (policy.noRuntimeDiagnostics && runtimeErrors.length > 0) {
1562
1838
  diagnostics.push({
1563
1839
  code: "TN_PLAYTEST_RUNTIME_DIAGNOSTIC",
1564
1840
  message: `${runtimeErrors.length} runtime diagnostic error(s) were captured during playtest.`,
@@ -1640,6 +1916,86 @@ function countMatchingEntries(effectLog, tokens) {
1640
1916
  return tokens.every((token) => text.includes(token));
1641
1917
  }).length;
1642
1918
  }
1919
+ function evaluatePerformanceAssertion(assertion, series, sourcePath) {
1920
+ const samples = series ?? [];
1921
+ const validSamples = samples.length > 0 && samples.every(isRuntimeDiagnosticsSample);
1922
+ const observed = validSamples ? samples : [];
1923
+ const frameTimes = observed.map(({ frameMs }) => frameMs);
1924
+ const drawCalls = observed.flatMap(({ drawCalls: value }) => value === void 0 ? [] : [value]);
1925
+ const triangles = observed.flatMap(({ triangles: value }) => value === void 0 ? [] : [value]);
1926
+ const frameMsP95 = nearestRank(frameTimes, 0.95);
1927
+ const maxObservedDrawCalls = drawCalls.length === 0 ? void 0 : Math.max(...drawCalls);
1928
+ const maxObservedTriangles = triangles.length === 0 ? void 0 : Math.max(...triangles);
1929
+ const results = [];
1930
+ const diagnostics = [];
1931
+ const path = `${sourcePath ?? "playtest"}/observations.json/performanceSeries`;
1932
+ const samplesPass = validSamples;
1933
+ results.push({
1934
+ details: { sampleCount: samples.length, valid: validSamples },
1935
+ id: "performance.samples",
1936
+ pass: samplesPass
1937
+ });
1938
+ if (!samplesPass) {
1939
+ diagnostics.push({
1940
+ code: "TN_PLAYTEST_PERFORMANCE_SAMPLES_MISSING",
1941
+ message: samples.length === 0 ? "Performance assertion received no render samples." : "Performance assertion received an invalid render sample series.",
1942
+ observedRuntimePath: path,
1943
+ severity: "error",
1944
+ sourcePath,
1945
+ suggestion: "Run the scenario against the real render loop and keep the performance bridge provider installed."
1946
+ });
1947
+ }
1948
+ const addBound = (id, expected, actual, unit, pass) => {
1949
+ results.push({ details: { actual: actual ?? null, expected, sampleCount: samples.length, unit }, id, pass });
1950
+ if (!pass) diagnostics.push({
1951
+ code: "TN_PLAYTEST_PERFORMANCE_ASSERTION_FAILED",
1952
+ message: `${id} expected at most ${expected} ${unit}, observed ${actual ?? "unavailable"}.`,
1953
+ observedRuntimePath: path,
1954
+ severity: "error",
1955
+ sourcePath,
1956
+ suggestion: "Inspect the recorded frame-cost series and reduce the authored scene cost that owns the regression."
1957
+ });
1958
+ };
1959
+ if (assertion.maxFrameMsP95 !== void 0) {
1960
+ addBound(
1961
+ "performance.maxFrameMsP95",
1962
+ assertion.maxFrameMsP95,
1963
+ frameMsP95,
1964
+ "ms",
1965
+ samplesPass && frameMsP95 !== void 0 && frameMsP95 <= assertion.maxFrameMsP95
1966
+ );
1967
+ }
1968
+ if (assertion.maxDrawCalls !== void 0) {
1969
+ addBound(
1970
+ "performance.maxDrawCalls",
1971
+ assertion.maxDrawCalls,
1972
+ maxObservedDrawCalls,
1973
+ "draw calls",
1974
+ samplesPass && drawCalls.length === samples.length && maxObservedDrawCalls !== void 0 && maxObservedDrawCalls <= assertion.maxDrawCalls
1975
+ );
1976
+ }
1977
+ if (assertion.maxTriangles !== void 0) {
1978
+ addBound(
1979
+ "performance.maxTriangles",
1980
+ assertion.maxTriangles,
1981
+ maxObservedTriangles,
1982
+ "triangles",
1983
+ samplesPass && triangles.length === samples.length && maxObservedTriangles !== void 0 && maxObservedTriangles <= assertion.maxTriangles
1984
+ );
1985
+ }
1986
+ return { assertions: results, diagnostics };
1987
+ }
1988
+ function isRuntimeDiagnosticsSample(value) {
1989
+ if (!isRecord(value) || typeof value.frameMs !== "number" || !Number.isFinite(value.frameMs) || value.frameMs <= 0) {
1990
+ return false;
1991
+ }
1992
+ return (value.drawCalls === void 0 || typeof value.drawCalls === "number" && Number.isFinite(value.drawCalls) && value.drawCalls >= 0) && (value.triangles === void 0 || typeof value.triangles === "number" && Number.isFinite(value.triangles) && value.triangles >= 0);
1993
+ }
1994
+ function nearestRank(values, percentile) {
1995
+ if (values.length === 0) return void 0;
1996
+ const sorted = [...values].sort((left, right) => left - right);
1997
+ return sorted[Math.max(0, Math.ceil(values.length * percentile) - 1)];
1998
+ }
1643
1999
  function mergeEffectLogs(effectLog, series) {
1644
2000
  return {
1645
2001
  entries: [effectLog, ...(series ?? []).map((sample) => sample.snapshot)].flatMap((log) => isRecord(log) && Array.isArray(log.entries) ? log.entries : [])
@@ -1931,8 +2287,6 @@ function playtestDiagnostic(code, message, instruction, details = {}) {
1931
2287
  var PLAYTEST_BRIDGE_GLOBAL = "__THREENATIVE_PLAYTEST_BRIDGE__";
1932
2288
  var PLAYTEST_PROTOCOL_VERSION = 1;
1933
2289
  var PLAYTEST_PROTOCOL_LIMITS = {
1934
- maxEntitiesPerSample: 100,
1935
- maxEventsPerDrain: 1e3,
1936
2290
  maxPayloadBytes: 1e6,
1937
2291
  operationTimeoutMs: 5e3
1938
2292
  };
@@ -2174,6 +2528,7 @@ function validateStep(value, scenarioPath, index) {
2174
2528
  "label",
2175
2529
  "overlayMessage",
2176
2530
  "pointerPosition",
2531
+ "pointers",
2177
2532
  "press",
2178
2533
  "release",
2179
2534
  "screenshot",
@@ -2193,19 +2548,23 @@ function validateStep(value, scenarioPath, index) {
2193
2548
  x: value.pointerPosition.x,
2194
2549
  y: value.pointerPosition.y
2195
2550
  } : void 0;
2551
+ const pointers = Array.isArray(value.pointers) ? value.pointers.map((pointer, pointerIndex) => validatePointer(pointer, scenarioPath, index, pointerIndex)) : void 0;
2196
2552
  if (isRecord2(value.overlayMessage)) {
2197
2553
  rejectUnknownKeys(value.overlayMessage, ["overlayId", "payload", "type"], scenarioPath, `steps[${index}].overlayMessage`);
2198
2554
  }
2199
2555
  if (isRecord2(value.pointerPosition)) {
2200
2556
  rejectUnknownKeys(value.pointerPosition, ["buttons", "x", "y"], scenarioPath, `steps[${index}].pointerPosition`);
2201
2557
  }
2558
+ if (pointers !== void 0 && new Set(pointers.map(({ id }) => id)).size !== pointers.length) {
2559
+ throw invalidStep(scenarioPath, `Scenario step ${index} pointers must use unique ids.`);
2560
+ }
2202
2561
  const holdFrames = positiveInteger(value.holdFrames);
2203
2562
  const holdTicks = positiveInteger(value.holdTicks);
2204
2563
  const waitFrames2 = positiveInteger(value.waitFrames);
2205
2564
  const waitTicks = positiveInteger(value.waitTicks);
2206
2565
  const kind = value.kind === "wait" ? "wait" : value.kind === "input" ? "input" : void 0;
2207
2566
  const screenshot = typeof value.screenshot === "string" && /^[A-Za-z0-9._-]+$/.test(value.screenshot) ? value.screenshot : void 0;
2208
- const window = isRecord2(value.window) && (value.window.operation === "minimize" || value.window.operation === "resize" || value.window.operation === "restore") && (value.window.operation !== "resize" || typeof value.window.width === "number" && Number.isFinite(value.window.width) && value.window.width >= 1 && typeof value.window.height === "number" && Number.isFinite(value.window.height) && value.window.height >= 1) ? {
2567
+ const window2 = isRecord2(value.window) && (value.window.operation === "minimize" || value.window.operation === "resize" || value.window.operation === "restore") && (value.window.operation !== "resize" || typeof value.window.width === "number" && Number.isFinite(value.window.width) && value.window.width >= 1 && typeof value.window.height === "number" && Number.isFinite(value.window.height) && value.window.height >= 1) ? {
2209
2568
  operation: value.window.operation,
2210
2569
  ...typeof value.window.width === "number" ? { width: value.window.width } : {},
2211
2570
  ...typeof value.window.height === "number" ? { height: value.window.height } : {}
@@ -2226,17 +2585,20 @@ function validateStep(value, scenarioPath, index) {
2226
2585
  if (value.pointerPosition !== void 0 && pointerPosition === void 0) {
2227
2586
  throw invalidStep(scenarioPath, `Scenario step ${index} pointerPosition must define normalized x and y values from 0 through 1.`);
2228
2587
  }
2588
+ if (value.pointers !== void 0 && pointers === void 0) {
2589
+ throw invalidStep(scenarioPath, `Scenario step ${index} pointers must be an array.`);
2590
+ }
2229
2591
  if (value.screenshot !== void 0 && screenshot === void 0) {
2230
2592
  throw invalidStep(scenarioPath, `Scenario step ${index} screenshot must be a stable file-safe name.`);
2231
2593
  }
2232
2594
  if (value.label !== void 0 && (typeof value.label !== "string" || value.label.trim() === "")) {
2233
2595
  throw invalidStep(scenarioPath, `Scenario step ${index} label must be a non-empty string.`);
2234
2596
  }
2235
- if (value.window !== void 0 && window === void 0) {
2597
+ if (value.window !== void 0 && window2 === void 0) {
2236
2598
  throw invalidStep(scenarioPath, `Scenario step ${index} window must define minimize, restore, or resize with positive width and height.`);
2237
2599
  }
2238
- if (press === void 0 && overlayMessage === void 0 && pointerPosition === void 0 && window === void 0 && waitFrames2 === void 0 && waitTicks === void 0) {
2239
- throw invalidStep(scenarioPath, `Scenario step ${index} must define press, overlayMessage, pointerPosition, window, or waitFrames/waitTicks.`);
2600
+ if (press === void 0 && overlayMessage === void 0 && pointerPosition === void 0 && pointers === void 0 && window2 === void 0 && waitFrames2 === void 0 && waitTicks === void 0) {
2601
+ throw invalidStep(scenarioPath, `Scenario step ${index} must define press, overlayMessage, pointerPosition, pointers, window, or waitFrames/waitTicks.`);
2240
2602
  }
2241
2603
  if (value.holdFrames !== void 0 && holdFrames === void 0) {
2242
2604
  throw invalidStep(scenarioPath, `Scenario step ${index} holdFrames must be a positive integer.`);
@@ -2266,12 +2628,33 @@ function validateStep(value, scenarioPath, index) {
2266
2628
  ...typeof value.label === "string" ? { label: value.label } : {},
2267
2629
  ...overlayMessage === void 0 ? {} : { overlayMessage },
2268
2630
  ...pointerPosition === void 0 ? {} : { pointerPosition },
2631
+ ...pointers === void 0 ? {} : { pointers },
2269
2632
  ...press === void 0 ? {} : { press },
2270
2633
  release: typeof value.release === "boolean" ? value.release : true,
2271
2634
  ...screenshot === void 0 ? {} : { screenshot },
2272
2635
  ...waitFrames2 === void 0 ? {} : { waitFrames: waitFrames2 },
2273
2636
  ...waitTicks === void 0 ? {} : { waitTicks },
2274
- ...window === void 0 ? {} : { window }
2637
+ ...window2 === void 0 ? {} : { window: window2 }
2638
+ };
2639
+ }
2640
+ function validatePointer(value, scenarioPath, stepIndex, pointerIndex) {
2641
+ const path = `steps[${stepIndex}].pointers[${pointerIndex}]`;
2642
+ if (!isRecord2(value)) throw invalidStep(scenarioPath, `${path} must be an object.`);
2643
+ rejectUnknownKeys(value, ["buttons", "id", "x", "y"], scenarioPath, path);
2644
+ if (!Number.isInteger(value.id) || value.id < 1) {
2645
+ throw invalidStep(scenarioPath, `${path}.id must be a positive integer.`);
2646
+ }
2647
+ if (typeof value.x !== "number" || !Number.isFinite(value.x) || value.x < 0 || value.x > 1 || typeof value.y !== "number" || !Number.isFinite(value.y) || value.y < 0 || value.y > 1) {
2648
+ throw invalidStep(scenarioPath, `${path} must define normalized x and y values from 0 through 1.`);
2649
+ }
2650
+ if (value.buttons !== void 0 && (!Number.isInteger(value.buttons) || value.buttons < 1)) {
2651
+ throw invalidStep(scenarioPath, `${path}.buttons must be a positive integer when present.`);
2652
+ }
2653
+ return {
2654
+ ...typeof value.buttons === "number" ? { buttons: value.buttons } : {},
2655
+ id: value.id,
2656
+ x: value.x,
2657
+ y: value.y
2275
2658
  };
2276
2659
  }
2277
2660
  function validateStepLabels(steps, assertions, scenarioPath) {
@@ -2313,6 +2696,18 @@ function validateStepLabels(steps, assertions, scenarioPath) {
2313
2696
  requireLabel(assertion.compareToStep, `assert.settled[${index}].compareToStep`);
2314
2697
  }
2315
2698
  requireLabel(assertions.movement?.reachesPositionWithin?.atStep, "assert.movement.reachesPositionWithin.atStep");
2699
+ requireLabel(assertions.framebufferCoverage?.window.startStep, "assert.framebufferCoverage.window.startStep");
2700
+ requireLabel(assertions.framebufferCoverage?.window.endStep, "assert.framebufferCoverage.window.endStep");
2701
+ if (assertions.framebufferCoverage !== void 0) {
2702
+ const startIndex = steps.findIndex(({ label }) => label === assertions.framebufferCoverage?.window.startStep);
2703
+ const endIndex = steps.findIndex(({ label }) => label === assertions.framebufferCoverage?.window.endStep);
2704
+ if (endIndex < startIndex) {
2705
+ throw invalidScenario(
2706
+ scenarioPath,
2707
+ "Assertion 'assert.framebufferCoverage.window.endStep' must not precede startStep."
2708
+ );
2709
+ }
2710
+ }
2316
2711
  }
2317
2712
  function playtestStepHoldTicks(step, fallback = 1) {
2318
2713
  if (step.press === void 0 || step.holdFrames !== void 0 || step.waitFrames !== void 0) return 0;
@@ -2331,12 +2726,25 @@ function validateAssertions(value, scenarioPath) {
2331
2726
  const movement = isRecord2(value.movement) ? value.movement : void 0;
2332
2727
  const camera = isRecord2(value.camera) ? value.camera : void 0;
2333
2728
  const diagnostics = isRecord2(value.diagnostics) ? value.diagnostics : void 0;
2729
+ const performance = isRecord2(value.performance) ? validatePerformanceAssertion(value.performance, scenarioPath, "assert.performance") : void 0;
2730
+ const framebufferCoverage = isRecord2(value.framebufferCoverage) ? validateFramebufferCoverageAssertion(
2731
+ value.framebufferCoverage,
2732
+ scenarioPath,
2733
+ "assert.framebufferCoverage"
2734
+ ) : void 0;
2334
2735
  const world = isRecord2(value.world) ? value.world : void 0;
2335
- if (diagnostics?.noRuntimeDiagnostics === false && (typeof diagnostics.runtimeDiagnosticsOptOutReason !== "string" || diagnostics.runtimeDiagnosticsOptOutReason.trim() === "")) {
2336
- throw invalidScenario(
2337
- scenarioPath,
2338
- "Assertion 'assert.diagnostics.noRuntimeDiagnostics' may be false only when 'runtimeDiagnosticsOptOutReason' explains the bounded exception."
2339
- );
2736
+ const optOuts = [
2737
+ ["noConsoleErrors", "consoleErrorsOptOutReason"],
2738
+ ["noNetworkErrors", "networkErrorsOptOutReason"],
2739
+ ["noRuntimeDiagnostics", "runtimeDiagnosticsOptOutReason"]
2740
+ ];
2741
+ for (const [policyKey, reasonKey] of optOuts) {
2742
+ if (diagnostics?.[policyKey] === false && (typeof diagnostics[reasonKey] !== "string" || diagnostics[reasonKey].trim() === "")) {
2743
+ throw invalidScenario(
2744
+ scenarioPath,
2745
+ `Assertion 'assert.diagnostics.${policyKey}' may be false only when '${reasonKey}' explains the bounded exception.`
2746
+ );
2747
+ }
2340
2748
  }
2341
2749
  return {
2342
2750
  ...Array.isArray(value.aerodynamics) ? { aerodynamics: value.aerodynamics.map(validateAerodynamicsAssertion).filter((item) => item !== void 0) } : {},
@@ -2360,11 +2768,15 @@ function validateAssertions(value, scenarioPath) {
2360
2768
  ...typeof diagnostics.noConsoleErrors === "boolean" ? { noConsoleErrors: diagnostics.noConsoleErrors } : {},
2361
2769
  ...typeof diagnostics.noNetworkErrors === "boolean" ? { noNetworkErrors: diagnostics.noNetworkErrors } : {},
2362
2770
  ...typeof diagnostics.noRuntimeDiagnostics === "boolean" ? { noRuntimeDiagnostics: diagnostics.noRuntimeDiagnostics } : {},
2771
+ ...typeof diagnostics.consoleErrorsOptOutReason === "string" ? { consoleErrorsOptOutReason: diagnostics.consoleErrorsOptOutReason } : {},
2772
+ ...typeof diagnostics.networkErrorsOptOutReason === "string" ? { networkErrorsOptOutReason: diagnostics.networkErrorsOptOutReason } : {},
2363
2773
  ...typeof diagnostics.runtimeDiagnosticsOptOutReason === "string" ? { runtimeDiagnosticsOptOutReason: diagnostics.runtimeDiagnosticsOptOutReason } : {},
2364
2774
  ...typeof diagnostics.runtimeReady === "boolean" ? { runtimeReady: diagnostics.runtimeReady } : {}
2365
2775
  }
2366
2776
  },
2367
2777
  ...Array.isArray(value.hud) ? { hud: value.hud.map(validatePathAssertion).filter((item) => item !== void 0) } : {},
2778
+ ...performance === void 0 ? {} : { performance },
2779
+ ...framebufferCoverage === void 0 ? {} : { framebufferCoverage },
2368
2780
  ...movement === void 0 ? {} : {
2369
2781
  movement: {
2370
2782
  ...typeof movement.axis === "string" ? { axis: movement.axis } : {},
@@ -2467,7 +2879,7 @@ function validateSettledAssertion(value, scenarioPath, objectPath) {
2467
2879
  return {
2468
2880
  ...present("atStep", optionalString(record2, "atStep", scenarioPath, objectPath)),
2469
2881
  ...present("compareToStep", optionalString(record2, "compareToStep", scenarioPath, objectPath)),
2470
- entity: requireString(record2, "entity", scenarioPath, objectPath),
2882
+ ...present("entity", optionalString(record2, "entity", scenarioPath, objectPath)),
2471
2883
  ...present("minBodies", optionalPositiveInteger(record2, "minBodies", scenarioPath, objectPath)),
2472
2884
  ...present("minMeanPoseDistance", optionalPositiveNumber(record2, "minMeanPoseDistance", scenarioPath, objectPath)),
2473
2885
  ...present("requiredOn", optionalTargetArray(record2, "requiredOn", scenarioPath, objectPath))
@@ -2637,6 +3049,14 @@ function optionalNumber(value, key, scenarioPath, objectPath) {
2637
3049
  }
2638
3050
  return raw;
2639
3051
  }
3052
+ function optionalNonNegativeNumber(value, key, scenarioPath, objectPath) {
3053
+ const raw = value[key];
3054
+ if (raw === void 0) return void 0;
3055
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) {
3056
+ throw invalidScenario(scenarioPath, `'${objectPath}.${key}' must be a finite non-negative number, received ${describeValue(raw)}.`);
3057
+ }
3058
+ return raw;
3059
+ }
2640
3060
  function optionalNonNegativeInteger(value, key, scenarioPath, objectPath) {
2641
3061
  const raw = value[key];
2642
3062
  if (raw === void 0) return void 0;
@@ -2677,11 +3097,61 @@ function optionalTargetArray(value, key, scenarioPath, objectPath) {
2677
3097
  function present(key, value) {
2678
3098
  return value === void 0 ? {} : { [key]: value };
2679
3099
  }
3100
+ function validatePerformanceAssertion(value, scenarioPath, objectPath) {
3101
+ const record2 = requireRecord(value, scenarioPath, objectPath);
3102
+ rejectUnknownKeys(record2, ["maxDrawCalls", "maxFrameMsP95", "maxTriangles"], scenarioPath, objectPath);
3103
+ return {
3104
+ ...present("maxDrawCalls", optionalNonNegativeNumber(record2, "maxDrawCalls", scenarioPath, objectPath)),
3105
+ ...present("maxFrameMsP95", optionalNonNegativeNumber(record2, "maxFrameMsP95", scenarioPath, objectPath)),
3106
+ ...present("maxTriangles", optionalNonNegativeNumber(record2, "maxTriangles", scenarioPath, objectPath))
3107
+ };
3108
+ }
3109
+ function validateFramebufferCoverageAssertion(value, scenarioPath, objectPath) {
3110
+ const record2 = requireRecord(value, scenarioPath, objectPath);
3111
+ rejectUnknownKeys(record2, ["backdrop", "grid", "tolerance", "window"], scenarioPath, objectPath);
3112
+ const backdrop = requireArray(record2, "backdrop", scenarioPath, objectPath);
3113
+ if (backdrop.length !== 3 || backdrop.some((channel) => typeof channel !== "number" || !Number.isInteger(channel) || channel < 0 || channel > 255)) {
3114
+ throw invalidScenario(
3115
+ scenarioPath,
3116
+ `'${objectPath}.backdrop' must be three integer RGB channels from 0 to 255.`
3117
+ );
3118
+ }
3119
+ const tolerance = optionalNonNegativeInteger(record2, "tolerance", scenarioPath, objectPath);
3120
+ if (tolerance === void 0 || tolerance > 255) {
3121
+ throw invalidScenario(scenarioPath, `'${objectPath}.tolerance' must be an integer from 0 to 255.`);
3122
+ }
3123
+ const window2 = requireRecord(record2.window, scenarioPath, `${objectPath}.window`);
3124
+ rejectUnknownKeys(window2, ["endStep", "startStep"], scenarioPath, `${objectPath}.window`);
3125
+ const gridValue = record2.grid;
3126
+ let grid;
3127
+ if (gridValue !== void 0) {
3128
+ const gridRecord = requireRecord(gridValue, scenarioPath, `${objectPath}.grid`);
3129
+ rejectUnknownKeys(gridRecord, ["columns", "rows"], scenarioPath, `${objectPath}.grid`);
3130
+ const columns = optionalPositiveInteger(gridRecord, "columns", scenarioPath, `${objectPath}.grid`);
3131
+ const rows = optionalPositiveInteger(gridRecord, "rows", scenarioPath, `${objectPath}.grid`);
3132
+ if (columns === void 0 || rows === void 0 || columns > 256 || rows > 256) {
3133
+ throw invalidScenario(
3134
+ scenarioPath,
3135
+ `'${objectPath}.grid' columns and rows must be positive integers no greater than 256.`
3136
+ );
3137
+ }
3138
+ grid = { columns, rows };
3139
+ }
3140
+ return {
3141
+ backdrop,
3142
+ ...grid === void 0 ? {} : { grid },
3143
+ tolerance,
3144
+ window: {
3145
+ endStep: requireString(window2, "endStep", scenarioPath, `${objectPath}.window`),
3146
+ startStep: requireString(window2, "startStep", scenarioPath, `${objectPath}.window`)
3147
+ }
3148
+ };
3149
+ }
2680
3150
  function validateStateAssertion(value, scenarioPath, objectPath) {
2681
3151
  const record2 = requireRecord(value, scenarioPath, objectPath);
2682
3152
  rejectUnknownKeys(record2, ["entity", "equals"], scenarioPath, objectPath);
2683
3153
  return {
2684
- entity: requireString(record2, "entity", scenarioPath, objectPath),
3154
+ ...present("entity", optionalString(record2, "entity", scenarioPath, objectPath)),
2685
3155
  equals: requireString(record2, "equals", scenarioPath, objectPath)
2686
3156
  };
2687
3157
  }
@@ -2981,8 +3451,11 @@ var STANDALONE_PLAYTEST_OBSERVATION_FIELDS = [
2981
3451
  "components",
2982
3452
  "componentSeries",
2983
3453
  "console",
3454
+ "framebufferCoverage",
2984
3455
  "hud",
2985
3456
  "network",
3457
+ "physicsDebugSeries",
3458
+ "performanceSeries",
2986
3459
  "resources",
2987
3460
  "resourceSeries",
2988
3461
  "runtimeDiagnostics",
@@ -3002,6 +3475,7 @@ var BROWSER_CAPABILITIES = [
3002
3475
  "browser.network",
3003
3476
  "browser.screenshot",
3004
3477
  "browser.trace",
3478
+ "runtime.diagnostics",
3005
3479
  "runtime.ui"
3006
3480
  ];
3007
3481
  var PlaytestBridgeError = class extends Error {
@@ -3012,13 +3486,15 @@ var PlaytestBridgeError = class extends Error {
3012
3486
  diagnostic;
3013
3487
  };
3014
3488
  var PlaywrightTransport = class {
3015
- constructor(page) {
3489
+ constructor(page, operationTimeoutMs = PLAYTEST_PROTOCOL_LIMITS.operationTimeoutMs) {
3016
3490
  this.page = page;
3491
+ this.operationTimeoutMs = operationTimeoutMs;
3017
3492
  }
3018
3493
  page;
3494
+ operationTimeoutMs;
3019
3495
  capabilities = BROWSER_CAPABILITIES;
3020
3496
  async call(method, argument) {
3021
- return bridgeCall(this.page, method, argument);
3497
+ return bridgeCall(this.page, method, argument, this.operationTimeoutMs);
3022
3498
  }
3023
3499
  async close() {
3024
3500
  }
@@ -3029,16 +3505,14 @@ var PlaywrightTransport = class {
3029
3505
  }
3030
3506
  };
3031
3507
  async function connectPlaytestBridge(page, scenario, timeoutMs = PLAYTEST_PROTOCOL_LIMITS.operationTimeoutMs) {
3032
- return connectPlaytestBridgeTransport(new PlaywrightTransport(page), scenario, timeoutMs);
3508
+ return connectPlaytestBridgeTransport(new PlaywrightTransport(page, timeoutMs), scenario, timeoutMs);
3033
3509
  }
3034
3510
  async function connectPlaytestBridgeTransport(transport, scenario, timeoutMs = PLAYTEST_PROTOCOL_LIMITS.operationTimeoutMs) {
3035
3511
  const required = requiredPlaytestCapabilities(scenario);
3036
- const semanticRequired = required.filter(
3037
- (capability2) => !capability2.startsWith("browser.") && capability2 !== "runtime.ui" && (capability2 !== "runtime.diagnostics" || scenario.assert?.diagnostics?.noRuntimeDiagnostics === true)
3038
- );
3512
+ const bridgeRequired = missingPlaytestCapabilities(required, transport.capabilities);
3039
3513
  const exists = await transport.waitForBridge(timeoutMs);
3040
3514
  if (!exists) {
3041
- if (semanticRequired.length === 0) {
3515
+ if (bridgeRequired.length === 0) {
3042
3516
  return void 0;
3043
3517
  }
3044
3518
  throw new PlaytestBridgeError(playtestDiagnostic(
@@ -3170,7 +3644,7 @@ function assertBoundedPayload(value) {
3170
3644
  ));
3171
3645
  }
3172
3646
  }
3173
- async function bridgeCall(page, method, argument) {
3647
+ async function bridgeCall(page, method, argument, timeoutMs = PLAYTEST_PROTOCOL_LIMITS.operationTimeoutMs) {
3174
3648
  let timeout;
3175
3649
  try {
3176
3650
  return await Promise.race([
@@ -3188,9 +3662,9 @@ async function bridgeCall(page, method, argument) {
3188
3662
  new Promise((_resolve, reject) => {
3189
3663
  timeout = setTimeout(() => reject(new PlaytestBridgeError(playtestDiagnostic(
3190
3664
  "TN_PLAYTEST_OPERATION_TIMEOUT",
3191
- `Bridge operation '${method}' exceeded ${PLAYTEST_PROTOCOL_LIMITS.operationTimeoutMs}ms.`,
3665
+ `Bridge operation '${method}' exceeded ${timeoutMs}ms.`,
3192
3666
  "Bound the provider work or return a smaller observation payload."
3193
- ))), PLAYTEST_PROTOCOL_LIMITS.operationTimeoutMs);
3667
+ ))), timeoutMs);
3194
3668
  })
3195
3669
  ]);
3196
3670
  } finally {
@@ -3198,13 +3672,19 @@ async function bridgeCall(page, method, argument) {
3198
3672
  }
3199
3673
  }
3200
3674
  var execFileAsync = promisify(execFile);
3201
- var AdbAndroidDriver = class {
3675
+ var AdbAndroidDriver = class _AdbAndroidDriver {
3202
3676
  constructor(options) {
3203
3677
  this.options = options;
3204
3678
  this.adbPath = options.adbPath ?? discoverAdb();
3205
3679
  }
3206
3680
  options;
3681
+ static COVERAGE_VIDEO_PATH = "/sdcard/tn-playtest-framebuffer-coverage.mp4";
3207
3682
  adbPath;
3683
+ screenrecord;
3684
+ screenrecordError;
3685
+ touchSlots = /* @__PURE__ */ new Map();
3686
+ nextTrackingId = 100;
3687
+ rotation;
3208
3688
  async prepare(endpoint, mailboxRoot) {
3209
3689
  const url = new URL(endpoint);
3210
3690
  const port = url.port;
@@ -3226,10 +3706,7 @@ var AdbAndroidDriver = class {
3226
3706
  }
3227
3707
  async captureConsole() {
3228
3708
  const output = await this.adb(["logcat", "-d", "-v", "brief"]);
3229
- return output.split(/\r?\n/u).filter((line) => /Mystral|THREENATIVE|chromium/u.test(line)).map((text) => ({
3230
- text,
3231
- type: /^(?:E|F)\//u.test(text) || /\b(?:Error|FATAL|FAILED)\b/u.test(text) ? "error" : "log"
3232
- }));
3709
+ return parseAndroidConsole(output);
3233
3710
  }
3234
3711
  async screenshot(path) {
3235
3712
  const { stdout } = await execFileAsync(this.adbPath, [
@@ -3240,9 +3717,116 @@ var AdbAndroidDriver = class {
3240
3717
  ], { encoding: "buffer", maxBuffer: 32 * 1024 * 1024 });
3241
3718
  await writeFile(path, stdout);
3242
3719
  }
3720
+ async startScreenRecording() {
3721
+ if (this.screenrecord !== void 0) {
3722
+ throw new Error("TN_PLAYTEST_FRAMEBUFFER_COVERAGE_RECORDING_ACTIVE");
3723
+ }
3724
+ if ((await this.adb(["shell", "pidof", "screenrecord"]).catch(() => "")).trim().length > 0) {
3725
+ throw new Error("TN_PLAYTEST_FRAMEBUFFER_COVERAGE_OTHER_RECORDING_ACTIVE");
3726
+ }
3727
+ try {
3728
+ await this.adb(["shell", "rm", "-f", _AdbAndroidDriver.COVERAGE_VIDEO_PATH]);
3729
+ this.screenrecordError = void 0;
3730
+ this.screenrecord = spawn(this.adbPath, [
3731
+ ...this.serialArgs(),
3732
+ "shell",
3733
+ "screenrecord",
3734
+ "--time-limit",
3735
+ "180",
3736
+ "--bit-rate",
3737
+ "20000000",
3738
+ _AdbAndroidDriver.COVERAGE_VIDEO_PATH
3739
+ ], { stdio: "ignore" });
3740
+ this.screenrecord.once("error", (error) => {
3741
+ this.screenrecordError = error;
3742
+ });
3743
+ await this.waitForScreenRecorder();
3744
+ } catch (error) {
3745
+ await this.abortScreenRecording();
3746
+ throw error;
3747
+ }
3748
+ }
3749
+ async stopScreenRecording(path) {
3750
+ const recorder = this.screenrecord;
3751
+ if (recorder === void 0) {
3752
+ throw new Error("TN_PLAYTEST_FRAMEBUFFER_COVERAGE_RECORDING_NOT_ACTIVE");
3753
+ }
3754
+ this.screenrecord = void 0;
3755
+ this.screenrecordError = void 0;
3756
+ try {
3757
+ const pids = (await this.adb(["shell", "pidof", "screenrecord"]).catch(() => "")).trim().split(/\s+/u).filter((pid) => /^\d+$/u.test(pid));
3758
+ for (const pid of pids) await this.adb(["shell", "kill", "-2", pid]);
3759
+ await waitForProcessExit(recorder, 5e3);
3760
+ await this.adb(["pull", _AdbAndroidDriver.COVERAGE_VIDEO_PATH, path]);
3761
+ if ((await stat(path)).size === 0) {
3762
+ throw new Error("TN_PLAYTEST_FRAMEBUFFER_COVERAGE_RECORDING_EMPTY");
3763
+ }
3764
+ } finally {
3765
+ recorder.kill();
3766
+ await this.adb(["shell", "rm", "-f", _AdbAndroidDriver.COVERAGE_VIDEO_PATH]).catch(() => void 0);
3767
+ }
3768
+ }
3243
3769
  async isAlive() {
3244
3770
  return (await this.adb(["shell", "pidof", this.options.packageName])).trim().length > 0;
3245
3771
  }
3772
+ async setPointers(pointers) {
3773
+ const serial = (await this.adb(["get-serialno"])).trim();
3774
+ if (!serial.startsWith("emulator-")) {
3775
+ throw new Error("TN_PLAYTEST_ANDROID_MULTITOUCH_EMULATOR_REQUIRED: multi-pointer injection uses rootless adb emu event send.");
3776
+ }
3777
+ if (new Set(pointers.map(({ id }) => id)).size !== pointers.length) {
3778
+ throw new Error("Android complete held-pointer sets require unique pointer ids.");
3779
+ }
3780
+ if (pointers.some(({ buttons }) => buttons !== void 0 && buttons !== 1)) {
3781
+ throw new Error("Android touch injection supports buttons=1 only.");
3782
+ }
3783
+ this.rotation ??= await this.readRotation();
3784
+ const next = new Map(pointers.map((pointer) => [pointer.id, pointer]));
3785
+ const identity = [];
3786
+ const positions = [];
3787
+ const append = (batch, type, code, value) => {
3788
+ batch.push(`${type}:${code}:${value}`);
3789
+ };
3790
+ for (const [id, held] of [...this.touchSlots]) {
3791
+ if (next.has(id)) continue;
3792
+ append(identity, "EV_ABS", "ABS_MT_SLOT", held.slot);
3793
+ append(identity, "EV_ABS", "ABS_MT_TRACKING_ID", -1);
3794
+ this.touchSlots.delete(id);
3795
+ }
3796
+ for (const pointer of pointers) {
3797
+ const [x, y] = rotatedTouchPosition(pointer.x, pointer.y, this.rotation);
3798
+ let held = this.touchSlots.get(pointer.id);
3799
+ if (held === void 0) {
3800
+ const usedSlots = new Set([...this.touchSlots.values()].map(({ slot: slot2 }) => slot2));
3801
+ let slot = 0;
3802
+ while (usedSlots.has(slot)) slot += 1;
3803
+ held = { slot, trackingId: this.nextTrackingId++, x, y };
3804
+ this.touchSlots.set(pointer.id, held);
3805
+ append(identity, "EV_ABS", "ABS_MT_SLOT", slot);
3806
+ append(identity, "EV_ABS", "ABS_MT_TRACKING_ID", held.trackingId);
3807
+ append(positions, "EV_ABS", "ABS_MT_SLOT", slot);
3808
+ append(positions, "EV_ABS", "ABS_MT_POSITION_X", x);
3809
+ append(positions, "EV_ABS", "ABS_MT_POSITION_Y", y);
3810
+ append(positions, "EV_ABS", "ABS_MT_TOUCH_MAJOR", 1);
3811
+ append(positions, "EV_ABS", "ABS_MT_PRESSURE", 512);
3812
+ } else if (held.x !== x || held.y !== y) {
3813
+ append(positions, "EV_ABS", "ABS_MT_SLOT", held.slot);
3814
+ append(positions, "EV_ABS", "ABS_MT_POSITION_X", x);
3815
+ append(positions, "EV_ABS", "ABS_MT_POSITION_Y", y);
3816
+ held.x = x;
3817
+ held.y = y;
3818
+ }
3819
+ }
3820
+ for (const batch of androidTouchBatches(identity, positions)) {
3821
+ await this.adb(["emu", "event", "send", ...batch]);
3822
+ }
3823
+ return {
3824
+ activeIds: [...this.touchSlots.keys()],
3825
+ injection: "adb-emu-event-protocol-b",
3826
+ rotation: this.rotation,
3827
+ trackingIds: [...this.touchSlots.values()].map(({ trackingId }) => trackingId)
3828
+ };
3829
+ }
3246
3830
  async readFile(path) {
3247
3831
  try {
3248
3832
  const contents = await this.adb(["exec-out", "cat", path]);
@@ -3256,9 +3840,19 @@ var AdbAndroidDriver = class {
3256
3840
  await this.adb(["shell", "rm", "-f", path]);
3257
3841
  }
3258
3842
  async stop() {
3843
+ await this.abortScreenRecording();
3844
+ await this.setPointers([]).catch(() => void 0);
3259
3845
  await this.adb(["shell", "am", "force-stop", this.options.packageName]).catch(() => void 0);
3260
3846
  await this.adb(["reverse", "--remove-all"]).catch(() => void 0);
3261
3847
  }
3848
+ async readRotation() {
3849
+ const input = await this.adb(["shell", "dumpsys", "input"]);
3850
+ const surface = /SurfaceOrientation:\s*([0-3])/u.exec(input)?.[1];
3851
+ if (surface !== void 0) return Number(surface);
3852
+ const setting = (await this.adb(["shell", "settings", "get", "system", "user_rotation"])).trim();
3853
+ if (/^[0-3]$/u.test(setting)) return Number(setting);
3854
+ throw new Error("TN_PLAYTEST_ANDROID_ROTATION_UNKNOWN: dumpsys input and user_rotation did not report 0 through 3.");
3855
+ }
3262
3856
  async writeFile(path, contents) {
3263
3857
  const directory = await mkdtemp(join(tmpdir(), "threenative-adb-mailbox-"));
3264
3858
  const localPath = join(directory, "payload.json");
@@ -3279,6 +3873,9 @@ var AdbAndroidDriver = class {
3279
3873
  [...this.serialArgs(), ...args],
3280
3874
  { encoding: "utf8", maxBuffer: 8 * 1024 * 1024 }
3281
3875
  );
3876
+ if (/^KO:/mu.test(stdout)) {
3877
+ throw new Error(`adb ${args.join(" ")} failed: ${stdout.trim()}`);
3878
+ }
3282
3879
  return stdout;
3283
3880
  } catch (error) {
3284
3881
  const detail = error;
@@ -3287,10 +3884,79 @@ var AdbAndroidDriver = class {
3287
3884
  );
3288
3885
  }
3289
3886
  }
3887
+ async waitForScreenRecorder() {
3888
+ for (let attempt = 0; attempt < 100; attempt += 1) {
3889
+ if (this.screenrecordError !== void 0) {
3890
+ throw new Error(`TN_PLAYTEST_FRAMEBUFFER_COVERAGE_RECORDING_FAILED:${this.screenrecordError.message}`);
3891
+ }
3892
+ if (this.screenrecord?.exitCode !== null) {
3893
+ throw new Error("TN_PLAYTEST_FRAMEBUFFER_COVERAGE_RECORDING_EXITED");
3894
+ }
3895
+ const pid = await this.adb(["shell", "pidof", "screenrecord"]).catch(() => "");
3896
+ if (pid.trim().length > 0) return;
3897
+ await new Promise((resolve5) => setTimeout(resolve5, 20));
3898
+ }
3899
+ throw new Error("TN_PLAYTEST_FRAMEBUFFER_COVERAGE_RECORDING_NOT_READY");
3900
+ }
3901
+ async abortScreenRecording() {
3902
+ const recorder = this.screenrecord;
3903
+ this.screenrecord = void 0;
3904
+ this.screenrecordError = void 0;
3905
+ if (recorder !== void 0) {
3906
+ const pids = (await this.adb(["shell", "pidof", "screenrecord"]).catch(() => "")).trim().split(/\s+/u).filter((pid) => /^\d+$/u.test(pid));
3907
+ for (const pid of pids) await this.adb(["shell", "kill", "-2", pid]).catch(() => void 0);
3908
+ await waitForProcessExit(recorder, 5e3).catch(() => recorder.kill());
3909
+ await this.adb(["shell", "rm", "-f", _AdbAndroidDriver.COVERAGE_VIDEO_PATH]).catch(() => void 0);
3910
+ }
3911
+ }
3290
3912
  serialArgs() {
3291
3913
  return this.options.serial === void 0 ? [] : ["-s", this.options.serial];
3292
3914
  }
3293
3915
  };
3916
+ async function waitForProcessExit(child, timeoutMs) {
3917
+ if (child.exitCode !== null) return;
3918
+ await new Promise((resolve5, reject) => {
3919
+ const timeout = setTimeout(() => {
3920
+ cleanup();
3921
+ reject(new Error("TN_PLAYTEST_FRAMEBUFFER_COVERAGE_RECORDING_STOP_TIMEOUT"));
3922
+ }, timeoutMs);
3923
+ const onExit = () => {
3924
+ cleanup();
3925
+ resolve5();
3926
+ };
3927
+ const cleanup = () => {
3928
+ clearTimeout(timeout);
3929
+ child.off("exit", onExit);
3930
+ };
3931
+ child.once("exit", onExit);
3932
+ if (child.exitCode !== null) onExit();
3933
+ });
3934
+ }
3935
+ function parseAndroidConsole(output) {
3936
+ return output.split(/\r?\n/u).filter((line) => !/^[VDIWEF]\/SurfaceSyncGroup\(/u.test(line)).filter((line) => /Mystral|THREENATIVE|chromium/u.test(line)).map((text) => ({
3937
+ text,
3938
+ type: /^(?:E|F)\//u.test(text) || /\b(?:Error|FATAL|FAILED)\b/u.test(text) ? "error" : "log"
3939
+ }));
3940
+ }
3941
+ var TOUCH_AXIS_MAX = 32767;
3942
+ function androidTouchBatches(identity, positions) {
3943
+ const batches = [];
3944
+ for (const batch of [identity, positions]) {
3945
+ if (batch.length === 0) continue;
3946
+ if (batch.some((event) => event.includes("ABS_MT_TRACKING_ID")) && batch.some((event) => event.includes("ABS_MT_POSITION_"))) {
3947
+ throw new Error(
3948
+ "TN_PLAYTEST_ANDROID_TOUCH_BATCH_MIXED: a tracking id and a coordinate cannot share one emulator event batch; the emulator silently drops the coordinate."
3949
+ );
3950
+ }
3951
+ batches.push([...batch, "EV_SYN:0:0"]);
3952
+ }
3953
+ return batches;
3954
+ }
3955
+ function rotatedTouchPosition(x, y, rotation) {
3956
+ const normalized = rotation === 0 ? [x, y] : rotation === 1 ? [y, 1 - x] : rotation === 2 ? [1 - x, 1 - y] : rotation === 3 ? [1 - y, x] : void 0;
3957
+ if (normalized === void 0) throw new Error(`Android display rotation ${rotation} is invalid.`);
3958
+ return normalized.map((value) => Math.round(value * TOUCH_AXIS_MAX));
3959
+ }
3294
3960
  function isMissingRemoteFile(error) {
3295
3961
  const detail = error;
3296
3962
  return isMissingRemoteFileOutput(`${detail.stderr ?? ""}
@@ -3318,7 +3984,8 @@ function discoverAdb(environment = process.env) {
3318
3984
  var ANDROID_TRANSPORT_CAPABILITIES = [
3319
3985
  "browser.console",
3320
3986
  "browser.input",
3321
- "browser.screenshot"
3987
+ "browser.screenshot",
3988
+ "runtime.diagnostics"
3322
3989
  ];
3323
3990
  var DeviceBridgeTransport = class {
3324
3991
  capabilities = ANDROID_TRANSPORT_CAPABILITIES;
@@ -3561,63 +4228,399 @@ async function delayUntil(deadline) {
3561
4228
  const remaining = deadline - Date.now();
3562
4229
  if (remaining > 0) await new Promise((resolve5) => setTimeout(resolve5, Math.min(40, remaining)));
3563
4230
  }
3564
- var ManagedServerError = class extends Error {
3565
- constructor(diagnostic) {
3566
- super(diagnostic.message);
3567
- this.diagnostic = diagnostic;
3568
- }
3569
- diagnostic;
4231
+ var CAPTURE_GUARD_LIMITS = {
4232
+ brightLuminance: 0.05,
4233
+ minBrightPixelRatio: 0.05,
4234
+ minDistinctColors: 8,
4235
+ minLuminanceStdDev: 0.01
3570
4236
  };
3571
- async function runStandalonePlaytest(config) {
3572
- const scenario = await loadPlaytestScenario(config.projectPath, config.scenarioPath);
3573
- await mkdir(config.artifactDirectory, { recursive: true });
3574
- let server;
3575
- let browser;
3576
- let page;
3577
- let teardownPromise;
3578
- const teardown = async () => {
3579
- if (teardownPromise !== void 0) return teardownPromise;
3580
- teardownPromise = (async () => {
3581
- stopManagedServer(server);
3582
- await page?.context().close().catch(() => void 0);
3583
- await browser?.close().catch(() => void 0);
3584
- })();
3585
- return teardownPromise;
3586
- };
3587
- const handleSignal = () => {
3588
- void teardown().catch(() => void 0).finally(() => {
3589
- process.exitCode = 2;
3590
- process.exit(2);
3591
- });
4237
+ var CaptureGuardError = class extends Error {
4238
+ constructor(label, reason, stats) {
4239
+ super(`TN_CAPTURE_BLANK: ${label}: ${reason}`);
4240
+ this.label = label;
4241
+ this.reason = reason;
4242
+ this.stats = stats;
4243
+ this.name = "CaptureGuardError";
4244
+ }
4245
+ label;
4246
+ reason;
4247
+ stats;
4248
+ code = "TN_CAPTURE_BLANK";
4249
+ };
4250
+ function inspectFrame(png) {
4251
+ const image = PNG.sync.read(png);
4252
+ const colors = /* @__PURE__ */ new Set();
4253
+ let luminanceTotal = 0;
4254
+ let luminanceSquaredTotal = 0;
4255
+ let brightPixels = 0;
4256
+ let visiblePixels = 0;
4257
+ for (let offset = 0; offset < image.data.length; offset += 4) {
4258
+ const red = image.data[offset] ?? 0;
4259
+ const green = image.data[offset + 1] ?? 0;
4260
+ const blue = image.data[offset + 2] ?? 0;
4261
+ const alpha = image.data[offset + 3] ?? 0;
4262
+ colors.add((red << 24 | green << 16 | blue << 8 | alpha) >>> 0);
4263
+ if (alpha === 0) continue;
4264
+ const luminance = (0.2126 * red + 0.7152 * green + 0.0722 * blue) / 255;
4265
+ visiblePixels += 1;
4266
+ if (luminance > CAPTURE_GUARD_LIMITS.brightLuminance) brightPixels += 1;
4267
+ luminanceTotal += luminance;
4268
+ luminanceSquaredTotal += luminance * luminance;
4269
+ }
4270
+ const mean = visiblePixels === 0 ? 0 : luminanceTotal / visiblePixels;
4271
+ const variance = visiblePixels === 0 ? 0 : luminanceSquaredTotal / visiblePixels - mean * mean;
4272
+ return {
4273
+ distinctColors: colors.size,
4274
+ brightPixelRatio: image.data.length === 0 ? 0 : brightPixels / (image.data.length / 4),
4275
+ height: image.height,
4276
+ luminanceStdDev: Math.sqrt(Math.max(0, variance)),
4277
+ width: image.width
3592
4278
  };
3593
- process.once("SIGINT", handleSignal);
3594
- process.once("SIGTERM", handleSignal);
3595
- const preflight = preflightDisplay(config, scenario);
3596
- if (preflight !== void 0) {
3597
- process.stderr.write(`${JSON.stringify({ diagnostics: [preflight] })}
3598
- `);
4279
+ }
4280
+ function assertCaptureNotBlank(png, label) {
4281
+ const stats = inspectFrame(png);
4282
+ if (stats.distinctColors < CAPTURE_GUARD_LIMITS.minDistinctColors) {
4283
+ throw new CaptureGuardError(
4284
+ label,
4285
+ `only ${stats.distinctColors} distinct color(s); capture is likely uniform or blank`,
4286
+ stats
4287
+ );
3599
4288
  }
3600
- try {
3601
- server = config.server === void 0 ? void 0 : startManagedServer(config);
3602
- browser = await chromium.launch({
3603
- ...config.browserArgs === void 0 ? {} : { args: [...config.browserArgs] },
3604
- headless: config.headless
3605
- });
3606
- if (server !== void 0) {
3607
- await waitForUrl(config.url, config.server?.timeoutMs ?? config.timeoutMs, server);
3608
- }
3609
- const context = await browser.newContext({ viewport: scenario.viewport });
4289
+ if (stats.luminanceStdDev < CAPTURE_GUARD_LIMITS.minLuminanceStdDev) {
4290
+ throw new CaptureGuardError(
4291
+ label,
4292
+ `luminance standard deviation ${stats.luminanceStdDev.toFixed(5)} is below ${CAPTURE_GUARD_LIMITS.minLuminanceStdDev}`,
4293
+ stats
4294
+ );
4295
+ }
4296
+ if (stats.brightPixelRatio < CAPTURE_GUARD_LIMITS.minBrightPixelRatio) {
4297
+ throw new CaptureGuardError(
4298
+ label,
4299
+ `bright pixel ratio ${stats.brightPixelRatio.toFixed(5)} is below ${CAPTURE_GUARD_LIMITS.minBrightPixelRatio}`,
4300
+ stats
4301
+ );
4302
+ }
4303
+ return stats;
4304
+ }
4305
+
4306
+ // src/runner/browser.ts
4307
+ var WEBGPU_BROWSER_ARGS = [
4308
+ "--ozone-platform=x11",
4309
+ "--enable-unsafe-webgpu",
4310
+ "--disable-gpu-sandbox",
4311
+ "--ignore-gpu-blocklist",
4312
+ // Without this Chromium never reaches the Vulkan driver on Linux and silently serves WebGPU
4313
+ // from SwiftShader, its CPU rasteriser. Nothing errors: the adapter answers, the run
4314
+ // proceeds, and the results are a software renderer's. Measured on an RTX 2080 under Xvfb,
4315
+ // `adapter.info` reads `swiftshader / google` without the flag and `turing / nvidia` with it,
4316
+ // which is the difference between blank captures and a rendered frame.
4317
+ "--enable-features=Vulkan"
4318
+ ];
4319
+ function resolveBrowserArguments(browserArgs) {
4320
+ return [...browserArgs ?? []];
4321
+ }
4322
+ var SOFTWARE_ADAPTER = /swiftshader|llvmpipe|lavapipe|softwarerasterizer|software adapter|basic render/i;
4323
+ function softwareAdapterName(adapter) {
4324
+ if (adapter === void 0) return void 0;
4325
+ for (const value of Object.values(adapter)) {
4326
+ if (typeof value === "string" && SOFTWARE_ADAPTER.test(value)) return value;
4327
+ }
4328
+ return void 0;
4329
+ }
4330
+ function reconcileBrowserPointers(previous, next) {
4331
+ const normalized = new Map(next.map((pointer) => [pointer.id, {
4332
+ buttons: pointer.buttons ?? 1,
4333
+ id: pointer.id,
4334
+ x: pointer.x,
4335
+ y: pointer.y
4336
+ }]));
4337
+ const previousPrimary = previous.keys().next().value;
4338
+ const nextPrimary = normalized.keys().next().value;
4339
+ const changes = [];
4340
+ for (const pointer of previous.values()) {
4341
+ if (!normalized.has(pointer.id)) {
4342
+ changes.push({ isPrimary: pointer.id === previousPrimary, pointer: { ...pointer, buttons: 0 }, type: "pointerup" });
4343
+ }
4344
+ }
4345
+ for (const pointer of normalized.values()) {
4346
+ const old = previous.get(pointer.id);
4347
+ if (old === void 0) {
4348
+ changes.push({ isPrimary: pointer.id === nextPrimary, pointer, type: "pointerdown" });
4349
+ } else if (old.x !== pointer.x || old.y !== pointer.y || old.buttons !== pointer.buttons) {
4350
+ changes.push({ isPrimary: pointer.id === nextPrimary, pointer, type: "pointermove" });
4351
+ }
4352
+ }
4353
+ return changes;
4354
+ }
4355
+ var DEFAULT_COLUMNS = 32;
4356
+ var DEFAULT_ROWS = 18;
4357
+ var PROBE_KEY = "__THREENATIVE_FRAMEBUFFER_COVERAGE_PROBE__";
4358
+ async function startFramebufferCoverageProbe(page, assertion) {
4359
+ const columns = assertion.grid?.columns ?? DEFAULT_COLUMNS;
4360
+ const rows = assertion.grid?.rows ?? DEFAULT_ROWS;
4361
+ await page.evaluate(
4362
+ ({ backdrop, columns: gridColumns, key, rows: gridRows, tolerance }) => {
4363
+ const host = globalThis;
4364
+ if (host[key] !== void 0) throw new Error("A framebuffer coverage probe is already active.");
4365
+ const canvases = [...document.querySelectorAll("canvas")];
4366
+ const source = canvases.sort(
4367
+ (left, right) => right.width * right.height - left.width * left.height
4368
+ )[0];
4369
+ const state = { active: true, frameCount: 0 };
4370
+ host[key] = state;
4371
+ if (source === void 0) {
4372
+ state.unreadableReason = "the page has no canvas framebuffer";
4373
+ return;
4374
+ }
4375
+ if (source.width <= 0 || source.height <= 0) {
4376
+ state.unreadableReason = `the canvas drawing buffer is ${source.width}x${source.height}`;
4377
+ return;
4378
+ }
4379
+ const sampleCanvas = document.createElement("canvas");
4380
+ sampleCanvas.width = gridColumns;
4381
+ sampleCanvas.height = gridRows;
4382
+ const sampleContext = sampleCanvas.getContext("2d", { willReadFrequently: true });
4383
+ if (sampleContext === null) {
4384
+ state.unreadableReason = "a 2D readback context could not be created";
4385
+ return;
4386
+ }
4387
+ const capture = () => {
4388
+ if (!state.active) return;
4389
+ try {
4390
+ sampleContext.clearRect(0, 0, gridColumns, gridRows);
4391
+ sampleContext.drawImage(source, 0, 0, gridColumns, gridRows);
4392
+ const image = sampleContext.getImageData(0, 0, gridColumns, gridRows);
4393
+ if (image.data.length !== gridColumns * gridRows * 4) {
4394
+ throw new Error(`readback returned ${image.data.length} bytes`);
4395
+ }
4396
+ const samples = [];
4397
+ let hasReadableAlpha = false;
4398
+ let violates = false;
4399
+ for (let offset = 0; offset < image.data.length; offset += 4) {
4400
+ const sample = [
4401
+ image.data[offset],
4402
+ image.data[offset + 1],
4403
+ image.data[offset + 2]
4404
+ ];
4405
+ samples.push(sample);
4406
+ if (image.data[offset + 3] > 0) hasReadableAlpha = true;
4407
+ if (sample.some((channel, index) => Math.abs(channel - backdrop[index]) > tolerance)) {
4408
+ violates = true;
4409
+ }
4410
+ }
4411
+ if (!hasReadableAlpha) throw new Error("readback returned only transparent pixels");
4412
+ const frameIndex = state.frameCount;
4413
+ state.frameCount += 1;
4414
+ if (violates && state.firstViolation === void 0) {
4415
+ const fullCanvas = document.createElement("canvas");
4416
+ fullCanvas.width = source.width;
4417
+ fullCanvas.height = source.height;
4418
+ const fullContext = fullCanvas.getContext("2d");
4419
+ if (fullContext === null) throw new Error("a full-frame evidence context could not be created");
4420
+ fullContext.drawImage(source, 0, 0);
4421
+ state.firstViolation = {
4422
+ frameIndex,
4423
+ fullPngDataUrl: fullCanvas.toDataURL("image/png"),
4424
+ grid: { columns: gridColumns, rows: gridRows, samples }
4425
+ };
4426
+ }
4427
+ } catch (error) {
4428
+ state.unreadableReason = error instanceof Error ? error.message : String(error);
4429
+ state.active = false;
4430
+ return;
4431
+ }
4432
+ state.requestId = requestAnimationFrame(capture);
4433
+ };
4434
+ state.requestId = requestAnimationFrame(capture);
4435
+ },
4436
+ { backdrop: assertion.backdrop, columns, key: PROBE_KEY, rows, tolerance: assertion.tolerance }
4437
+ );
4438
+ }
4439
+ async function finishFramebufferCoverageProbe(page, artifactDirectory) {
4440
+ const result = await page.evaluate((key) => {
4441
+ const host = globalThis;
4442
+ const state = host[key];
4443
+ if (state === void 0) return void 0;
4444
+ state.active = false;
4445
+ if (state.requestId !== void 0) cancelAnimationFrame(state.requestId);
4446
+ delete host[key];
4447
+ return {
4448
+ ...state.firstViolation === void 0 ? {} : { firstViolation: state.firstViolation },
4449
+ frameCount: state.frameCount,
4450
+ ...state.unreadableReason === void 0 ? {} : { unreadableReason: state.unreadableReason }
4451
+ };
4452
+ }, PROBE_KEY);
4453
+ if (result === void 0) {
4454
+ return {
4455
+ boundarySource: "scenario-steps",
4456
+ frameCount: 0,
4457
+ unreadableReason: "the declared coverage window never installed its framebuffer probe",
4458
+ windowCompleted: false,
4459
+ windowStarted: false
4460
+ };
4461
+ }
4462
+ let firstViolation;
4463
+ let unreadableReason = result.unreadableReason;
4464
+ if (result.firstViolation !== void 0) {
4465
+ const screenshotPath = join(
4466
+ artifactDirectory,
4467
+ `framebuffer-coverage-frame-${result.firstViolation.frameIndex}.png`
4468
+ );
4469
+ const encoded = result.firstViolation.fullPngDataUrl;
4470
+ if (encoded?.startsWith("data:image/png;base64,") === true) {
4471
+ await writeFile(screenshotPath, Buffer.from(encoded.slice("data:image/png;base64,".length), "base64"));
4472
+ } else {
4473
+ unreadableReason ??= "the violating frame could not be encoded as PNG evidence";
4474
+ }
4475
+ firstViolation = {
4476
+ frameIndex: result.firstViolation.frameIndex,
4477
+ grid: result.firstViolation.grid,
4478
+ screenshotPath: encoded?.startsWith("data:image/png;base64,") === true ? screenshotPath : ""
4479
+ };
4480
+ }
4481
+ return {
4482
+ boundarySource: "scenario-steps",
4483
+ ...firstViolation === void 0 ? {} : { firstViolation },
4484
+ frameCount: result.frameCount,
4485
+ ...unreadableReason === void 0 ? {} : { unreadableReason },
4486
+ windowCompleted: true,
4487
+ windowStarted: true
4488
+ };
4489
+ }
4490
+
4491
+ // src/runner/runner.ts
4492
+ var ManagedServerError = class extends Error {
4493
+ constructor(diagnostic) {
4494
+ super(diagnostic.message);
4495
+ this.diagnostic = diagnostic;
4496
+ }
4497
+ diagnostic;
4498
+ };
4499
+ function failedDiagnosticsAssertion(policy) {
4500
+ return {
4501
+ details: {
4502
+ consoleErrors: 0,
4503
+ networkErrors: 0,
4504
+ policy,
4505
+ reason: "not-evaluated",
4506
+ runtimeDiagnostics: 0
4507
+ },
4508
+ id: "diagnostics",
4509
+ pass: false
4510
+ };
4511
+ }
4512
+ async function writeCaptureProvenance(artifactDirectory, provenance) {
4513
+ await writeFile(join(artifactDirectory, "capture.json"), `${JSON.stringify(provenance, null, 2)}
4514
+ `);
4515
+ }
4516
+ async function writeObservationArtifacts(artifactDirectory, requested, observations) {
4517
+ const runtimeErrors = observations.runtimeTrace?.recentRuntimeErrors ?? [];
4518
+ const files = [
4519
+ ["console.json", observations.console, observations.console.length > 0 || requested?.console === true],
4520
+ ["network.json", observations.network, observations.network.length > 0 || requested?.network === true],
4521
+ ["runtime-trace.json", observations.runtimeTrace, runtimeErrors.length > 0 || requested?.runtimeTrace === true]
4522
+ ];
4523
+ const written = [];
4524
+ for (const [name, content, wanted] of files) {
4525
+ if (!wanted || content === void 0) continue;
4526
+ await writeFile(join(artifactDirectory, name), `${JSON.stringify(content, null, 2)}
4527
+ `);
4528
+ written.push(name);
4529
+ }
4530
+ return written;
4531
+ }
4532
+ var UNHANDLED_REJECTION_PREFIX = "__THREENATIVE_PLAYTEST_UNHANDLED_REJECTION__:";
4533
+ async function runStandalonePlaytest(config) {
4534
+ const scenario = await loadPlaytestScenario(config.projectPath, config.scenarioPath);
4535
+ await mkdir(config.artifactDirectory, { recursive: true });
4536
+ let server;
4537
+ let browser;
4538
+ let page;
4539
+ let teardownPromise;
4540
+ const pageLifecycle = {
4541
+ closed: false,
4542
+ crashed: false,
4543
+ frameNavigations: [],
4544
+ navigations: [],
4545
+ settled: false,
4546
+ tail: []
4547
+ };
4548
+ const teardown = async () => {
4549
+ if (teardownPromise !== void 0) return teardownPromise;
4550
+ teardownPromise = (async () => {
4551
+ await boundedTeardownStep(page?.context().close(), 5e3);
4552
+ await boundedTeardownStep(browser?.close(), 1e4);
4553
+ await stopManagedServer(server);
4554
+ })();
4555
+ return teardownPromise;
4556
+ };
4557
+ const handleSignal = () => {
4558
+ void teardown().catch(() => void 0).finally(() => {
4559
+ process.exitCode = 2;
4560
+ process.exit(2);
4561
+ });
4562
+ };
4563
+ process.once("SIGINT", handleSignal);
4564
+ process.once("SIGTERM", handleSignal);
4565
+ const preflight = preflightDisplay(config, scenario);
4566
+ if (preflight !== void 0) {
4567
+ process.stderr.write(`${JSON.stringify({ diagnostics: [preflight] })}
4568
+ `);
4569
+ }
4570
+ try {
4571
+ if (config.server !== void 0) {
4572
+ await assertManagedUrlAvailable(config.url);
4573
+ server = startManagedServer(config);
4574
+ }
4575
+ browser = await chromium.launch({
4576
+ ...config.browserArgs === void 0 ? {} : { args: resolveBrowserArguments(config.browserArgs) },
4577
+ headless: config.headless
4578
+ });
4579
+ if (server !== void 0) {
4580
+ await waitForUrl(config.url, config.server?.timeoutMs ?? config.timeoutMs, server);
4581
+ }
4582
+ const context = await browser.newContext({ viewport: scenario.viewport });
3610
4583
  if (config.trace) {
3611
4584
  await context.tracing.start({ screenshots: true, snapshots: true });
3612
4585
  }
3613
4586
  page = await context.newPage();
4587
+ await page.addInitScript(() => {
4588
+ globalThis.__THREENATIVE_PLAYTEST_RUNNER_EXPECTED__ = true;
4589
+ window.addEventListener("unhandledrejection", (event) => {
4590
+ const reason = event.reason instanceof Error ? event.reason.stack || event.reason.message : String(event.reason);
4591
+ console.error(`__THREENATIVE_PLAYTEST_UNHANDLED_REJECTION__:${reason}`);
4592
+ });
4593
+ });
3614
4594
  const consoleEntries = [];
3615
4595
  const networkEntries = [];
3616
- page.on("console", (entry) => consoleEntries.push({ text: entry.text(), type: entry.type() }));
3617
- page.on("pageerror", (error) => consoleEntries.push({ text: error.stack || error.message, type: "pageerror" }));
4596
+ page.on("console", (entry) => {
4597
+ const text = entry.text();
4598
+ const unhandledRejection = text.startsWith(UNHANDLED_REJECTION_PREFIX);
4599
+ consoleEntries.push({
4600
+ source: unhandledRejection ? "unhandled-rejection" : "browser-console",
4601
+ text: unhandledRejection ? text.slice(UNHANDLED_REJECTION_PREFIX.length) : text,
4602
+ type: entry.type()
4603
+ });
4604
+ pageLifecycle.tail.push(`${entry.type()}: ${text}`);
4605
+ if (pageLifecycle.tail.length > 8) pageLifecycle.tail.shift();
4606
+ });
4607
+ page.on("pageerror", (error) => consoleEntries.push({ source: "page-error", text: error.stack || error.message, type: "pageerror" }));
3618
4608
  page.on("requestfailed", (request) => networkEntries.push({ method: request.method(), url: request.url() }));
3619
- await page.goto(config.url, { timeout: config.timeoutMs, waitUntil: "domcontentloaded" });
3620
- const bridge = await connectPlaytestBridge(page, scenario);
4609
+ const observedPage = page;
4610
+ page.on("crash", () => {
4611
+ pageLifecycle.crashed = true;
4612
+ });
4613
+ page.on("framenavigated", (frame) => {
4614
+ if (frame !== observedPage.mainFrame()) return;
4615
+ pageLifecycle.frameNavigations.push(frame.url());
4616
+ if (pageLifecycle.settled) pageLifecycle.navigations.push(frame.url());
4617
+ });
4618
+ page.on("close", () => {
4619
+ pageLifecycle.closed = true;
4620
+ });
4621
+ const activePage = page;
4622
+ const bridge = await openPageAndConnectBridge(page, config, scenario);
4623
+ pageLifecycle.settled = true;
3621
4624
  if (bridge !== void 0 && scenario.setup !== void 0) {
3622
4625
  await bridge.applySetup(setupRequest(scenario));
3623
4626
  }
@@ -3627,18 +4630,90 @@ async function runStandalonePlaytest(config) {
3627
4630
  ).catch(() => false);
3628
4631
  const entityIds = observedEntityIds(scenario);
3629
4632
  const resourceIds = observedResourceIds(scenario);
3630
- const sampleRequest = { entities: entityIds, include: ["components", "diagnostics", "entities", "resources"], resources: resourceIds };
4633
+ const sampleRequest = {
4634
+ ...entityIds === void 0 ? {} : { entities: entityIds },
4635
+ include: [
4636
+ "components",
4637
+ "diagnostics",
4638
+ "entities",
4639
+ "resources",
4640
+ ...scenario.assert?.aerodynamics === void 0 && scenario.assert?.contacts === void 0 && scenario.assert?.settled === void 0 ? [] : ["physicsDebugSeries"],
4641
+ ...scenario.assert?.performance === void 0 ? [] : ["runtimeDiagnosticsSeries"]
4642
+ ],
4643
+ resources: resourceIds
4644
+ };
3631
4645
  const labeledSamples = [];
4646
+ const capturesAnonymousMovement = isAnonymousMovementScenario(scenario);
4647
+ const movementSamples = [];
3632
4648
  const wantsVisual = (scenario.assert?.visual?.length ?? 0) > 0;
4649
+ const needsCapture = scenario.artifacts?.screenshots !== false || scenario.steps.some((step) => step.screenshot !== void 0) || wantsVisual;
4650
+ const captureProvenance = needsCapture ? await readCaptureProvenance(page, config, scenario) : void 0;
4651
+ if (captureProvenance !== void 0) {
4652
+ await writeCaptureProvenance(config.artifactDirectory, captureProvenance);
4653
+ }
4654
+ let captureFailure;
4655
+ const capturePage = async (label, options) => {
4656
+ let png;
4657
+ try {
4658
+ png = await activePage.screenshot(options);
4659
+ } catch (error) {
4660
+ try {
4661
+ const fallback = await captureVisualSurface(
4662
+ activePage,
4663
+ typeof options?.path === "string" ? options.path : void 0
4664
+ );
4665
+ if (fallback === void 0) throw error;
4666
+ png = fallback;
4667
+ } catch {
4668
+ throw error;
4669
+ }
4670
+ }
4671
+ try {
4672
+ assertCaptureNotBlank(png, label);
4673
+ return png;
4674
+ } catch (error) {
4675
+ if (!(error instanceof CaptureGuardError)) throw error;
4676
+ captureFailure ??= { code: error.code, label: error.label, reason: error.reason };
4677
+ return void 0;
4678
+ }
4679
+ };
4680
+ const captureVisualPage = async (label, artifactPath) => {
4681
+ try {
4682
+ const png = await captureVisualSurface(activePage, artifactPath);
4683
+ if (png === void 0) {
4684
+ captureFailure ??= {
4685
+ code: "TN_CAPTURE_BLANK",
4686
+ label,
4687
+ reason: "no canvas was available for the visual capture"
4688
+ };
4689
+ return void 0;
4690
+ }
4691
+ assertCaptureNotBlank(png, label);
4692
+ return png;
4693
+ } catch (error) {
4694
+ if (!(error instanceof CaptureGuardError)) throw error;
4695
+ captureFailure ??= { code: error.code, label: error.label, reason: error.reason };
4696
+ return void 0;
4697
+ }
4698
+ };
3633
4699
  const beforeSnapshot = await bridge?.sample(sampleRequest);
4700
+ let movementCursor = beforeSnapshot;
3634
4701
  const pathEntity = scenario.assert?.movement?.pathLength === void 0 ? void 0 : scenario.assert.movement.entity ?? scenario.subject;
3635
4702
  const pathPositions = beforeSnapshot === void 0 || pathEntity === void 0 ? [] : [entityPosition(beforeSnapshot, pathEntity)].filter((position) => position !== void 0);
3636
- const inputState = { heldKeys: /* @__PURE__ */ new Set(), pointerButtons: 0 };
4703
+ const inputState = { heldKeys: /* @__PURE__ */ new Set(), pointerButtons: 0, pointers: /* @__PURE__ */ new Map() };
3637
4704
  const hudAssertions = scenario.assert?.hud ?? [];
3638
4705
  const beforeHud = await sampleHud(page, hudAssertions);
3639
- const beforeScreenshot = scenario.artifacts?.screenshots === "before-after" || wantsVisual ? await page.screenshot(scenario.artifacts?.screenshots === "before-after" ? { path: join(config.artifactDirectory, "before.png") } : void 0) : void 0;
4706
+ const beforeScreenshot = scenario.artifacts?.screenshots === "before-after" || wantsVisual ? wantsVisual ? await captureVisualPage(
4707
+ "before.png",
4708
+ scenario.artifacts?.screenshots === "before-after" ? join(config.artifactDirectory, "before.png") : void 0
4709
+ ) : await capturePage("before.png", scenario.artifacts?.screenshots === "before-after" ? { path: join(config.artifactDirectory, "before.png") } : {}) : void 0;
4710
+ let framebufferCoverage;
3640
4711
  for (const [index, step] of scenario.steps.entries()) {
3641
- await runStep(
4712
+ const framebufferAssertion = scenario.assert?.framebufferCoverage;
4713
+ if (framebufferAssertion !== void 0 && step.label === framebufferAssertion.window.startStep) {
4714
+ await startFramebufferCoverageProbe(page, framebufferAssertion);
4715
+ }
4716
+ const stepSamples = await runStep(
3642
4717
  page,
3643
4718
  bridge,
3644
4719
  step,
@@ -3646,15 +4721,32 @@ async function runStandalonePlaytest(config) {
3646
4721
  pathEntity,
3647
4722
  pathPositions,
3648
4723
  inputState,
4724
+ capturesAnonymousMovement ? sampleRequest : void 0,
3649
4725
  index === scenario.steps.length - 1
3650
4726
  );
4727
+ if (capturesAnonymousMovement && movementCursor !== void 0 && stepSamples.afterInput !== void 0) {
4728
+ movementSamples.push({
4729
+ after: stepSamples.afterInput,
4730
+ before: movementCursor,
4731
+ inputDriven: stepSamples.inputDriven
4732
+ });
4733
+ }
4734
+ if (capturesAnonymousMovement && stepSamples.afterInput !== void 0 && stepSamples.afterStep !== void 0 && stepSamples.afterStep !== stepSamples.afterInput) {
4735
+ movementSamples.push({ after: stepSamples.afterStep, before: stepSamples.afterInput, inputDriven: false });
4736
+ }
4737
+ if (capturesAnonymousMovement && stepSamples.afterStep !== void 0) {
4738
+ movementCursor = stepSamples.afterStep;
4739
+ }
4740
+ if (step.label === scenario.assert?.framebufferCoverage?.window.endStep) {
4741
+ framebufferCoverage = await finishFramebufferCoverageProbe(page, config.artifactDirectory);
4742
+ }
3651
4743
  if (step.label !== void 0 && bridge !== void 0) {
3652
- const snapshot = await bridge.sample(sampleRequest);
4744
+ const snapshot = await bridge.sample({ ...sampleRequest, label: step.label });
3653
4745
  const signals = bridge.description.capabilities.includes("runtime.events") ? await bridge.drainEvents() : [];
3654
4746
  labeledSamples.push({ label: step.label, signals, snapshot });
3655
4747
  }
3656
4748
  if (step.screenshot !== void 0) {
3657
- await page.screenshot({ path: join(config.artifactDirectory, `${safePart(step.screenshot)}.png`) });
4749
+ await capturePage(`${safePart(step.screenshot)}.png`, { path: join(config.artifactDirectory, `${safePart(step.screenshot)}.png`) });
3658
4750
  }
3659
4751
  }
3660
4752
  const afterSnapshot = await bridge?.sample(sampleRequest);
@@ -3663,8 +4755,11 @@ async function runStandalonePlaytest(config) {
3663
4755
  if (position !== void 0) pathPositions.push(position);
3664
4756
  }
3665
4757
  const afterHud = await sampleHud(page, hudAssertions);
3666
- const afterScreenshot = scenario.artifacts?.screenshots !== false || wantsVisual ? await page.screenshot(scenario.artifacts?.screenshots === false ? void 0 : { path: join(config.artifactDirectory, "after.png") }) : void 0;
3667
- const visual = screenshotObservations(beforeScreenshot, afterScreenshot, scenario);
4758
+ const afterScreenshot = scenario.artifacts?.screenshots !== false || wantsVisual ? wantsVisual ? await captureVisualPage(
4759
+ "after.png",
4760
+ scenario.artifacts?.screenshots === false ? void 0 : join(config.artifactDirectory, "after.png")
4761
+ ) : await capturePage("after.png", scenario.artifacts?.screenshots === false ? {} : { path: join(config.artifactDirectory, "after.png") }) : void 0;
4762
+ const visual = screenshotObservations(beforeScreenshot, afterScreenshot, scenario, captureFailure);
3668
4763
  if (config.trace) {
3669
4764
  await context.tracing.stop({ path: join(config.artifactDirectory, "trace.zip") });
3670
4765
  }
@@ -3679,14 +4774,27 @@ async function runStandalonePlaytest(config) {
3679
4774
  pairObservations(beforeHud, afterHud),
3680
4775
  runtimeReady,
3681
4776
  visual,
3682
- labeledSamples
4777
+ labeledSamples,
4778
+ framebufferCoverage,
4779
+ captureProvenance,
4780
+ captureFailure,
4781
+ movementSamples
3683
4782
  );
4783
+ await writeObservationArtifacts(config.artifactDirectory, scenario.artifacts, {
4784
+ console: consoleEntries,
4785
+ network: networkEntries,
4786
+ runtimeTrace: normalizedRuntimeDiagnostics(afterSnapshot, scenario, consoleEntries)
4787
+ });
3684
4788
  await context.close();
3685
4789
  return addPreflightDiagnostic(report, preflight);
3686
4790
  } catch (error) {
3687
4791
  if (error instanceof PlaytestBridgeError || error instanceof ManagedServerError) {
3688
4792
  return addPreflightDiagnostic(failureReport(config, scenario, error.diagnostic), preflight);
3689
4793
  }
4794
+ const lifecycleDiagnostic = pageLifecycleDiagnostic(error, pageLifecycle, config.url);
4795
+ if (lifecycleDiagnostic !== void 0) {
4796
+ return addPreflightDiagnostic(failureReport(config, scenario, lifecycleDiagnostic), preflight);
4797
+ }
3690
4798
  throw error;
3691
4799
  } finally {
3692
4800
  process.off("SIGINT", handleSignal);
@@ -3697,28 +4805,33 @@ async function runStandalonePlaytest(config) {
3697
4805
  function preflightDisplay(config, scenario, environment = process.env, platform = process.platform) {
3698
4806
  const takesScreenshot = scenario.artifacts?.screenshots !== false || scenario.steps.some(({ screenshot }) => screenshot !== void 0);
3699
4807
  const evaluatesVisual = (scenario.assert?.visual?.length ?? 0) > 0;
3700
- if (platform !== "linux" || config.headless !== true || environment.DISPLAY || environment.WAYLAND_DISPLAY || !takesScreenshot && !evaluatesVisual) {
4808
+ const evaluatesFramebuffer = scenario.assert?.framebufferCoverage !== void 0;
4809
+ if (platform !== "linux" || config.headless !== true || environment.DISPLAY || environment.WAYLAND_DISPLAY || !takesScreenshot && !evaluatesVisual && !evaluatesFramebuffer) {
3701
4810
  return void 0;
3702
4811
  }
3703
4812
  return {
3704
- code: "TN_PLAYTEST_HEADLESS_WEBGPU",
3705
- message: "Headless Linux visual runs may render WebGPU blank without a display; use xvfb-run -a -s '-screen 0 1600x900x24'.",
3706
- severity: "warning",
4813
+ code: evaluatesFramebuffer ? "TN_PLAYTEST_FRAMEBUFFER_PIXELS_UNREADABLE" : "TN_PLAYTEST_HEADLESS_WEBGPU",
4814
+ message: evaluatesFramebuffer ? "Headless Linux cannot provide trusted per-frame WebGPU pixels without a display; use xvfb-run -a -s '-screen 0 1600x900x24'." : "Headless Linux visual runs may render WebGPU blank without a display; use xvfb-run -a -s '-screen 0 1600x900x24'.",
4815
+ severity: evaluatesFramebuffer ? "error" : "warning",
3707
4816
  suggestion: "Prefix the command with xvfb-run -a -s '-screen 0 1600x900x24'."
3708
4817
  };
3709
4818
  }
3710
4819
  function addPreflightDiagnostic(report, diagnostic) {
3711
4820
  return diagnostic === void 0 ? report : { ...report, diagnostics: [diagnostic, ...report.diagnostics] };
3712
4821
  }
3713
- function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEntries, networkEntries, pathLength = void 0, hud = {}, runtimeReady = true, visual = void 0, labeledSamples = []) {
3714
- const entity = scenario.assert?.movement?.entity ?? scenario.subject ?? "";
3715
- const beforePosition = entityPosition(beforeSnapshot, entity);
3716
- const afterPosition = entityPosition(afterSnapshot, entity);
3717
- const beforeRotation = entityRotation(beforeSnapshot, entity);
3718
- const afterRotation = entityRotation(afterSnapshot, entity);
4822
+ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEntries, networkEntries, pathLength = void 0, hud = {}, runtimeReady = true, visual = void 0, labeledSamples = [], framebufferCoverage = void 0, capture = void 0, captureFailure = void 0, movementSamples = []) {
4823
+ const movementSample = isAnonymousMovementScenario(scenario) ? observedMovementSample(movementSamples) : void 0;
4824
+ const entity = scenario.assert?.movement?.entity ?? scenario.subject ?? movementSample?.entity ?? "";
4825
+ const movementBeforeSnapshot = movementSample?.before ?? (isAnonymousMovementScenario(scenario) ? void 0 : beforeSnapshot);
4826
+ const movementAfterSnapshot = movementSample?.after ?? (isAnonymousMovementScenario(scenario) ? void 0 : afterSnapshot);
4827
+ const beforePosition = entityPosition(movementBeforeSnapshot, entity);
4828
+ const afterPosition = entityPosition(movementAfterSnapshot, entity);
4829
+ const beforeRotation = entityRotation(movementBeforeSnapshot, entity);
4830
+ const afterRotation = entityRotation(movementAfterSnapshot, entity);
3719
4831
  const components = componentObservations(beforeSnapshot, afterSnapshot);
3720
4832
  const movementDelta = beforePosition === void 0 || afterPosition === void 0 ? void 0 : subtract(afterPosition, beforePosition);
3721
4833
  const distance = movementDelta === void 0 ? 0 : length(movementDelta);
4834
+ const performanceSeries = scenario.assert?.performance === void 0 ? void 0 : afterSnapshot?.runtimeDiagnosticsSeries ?? beforeSnapshot?.runtimeDiagnosticsSeries;
3722
4835
  const diagnostics = [];
3723
4836
  if (runtimeReady === false && scenario.assert?.diagnostics?.runtimeReady === true) {
3724
4837
  diagnostics.push({
@@ -3732,6 +4845,7 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
3732
4845
  ...afterPosition === void 0 ? {} : { after: { frame: scenario.steps.length, position: afterPosition, ...afterRotation === void 0 ? {} : { rotation: afterRotation }, tick: afterSnapshot?.clock.tick ?? 0 } },
3733
4846
  ...beforePosition === void 0 ? {} : { before: { frame: 0, position: beforePosition, ...beforeRotation === void 0 ? {} : { rotation: beforeRotation }, tick: beforeSnapshot?.clock.tick ?? 0 } },
3734
4847
  diagnostics,
4848
+ diagnosticsPolicy: resolveDiagnosticsPolicy(scenario.assert?.diagnostics),
3735
4849
  distance,
3736
4850
  entity,
3737
4851
  expectMoved: scenario.assert?.movement?.minDistance !== void 0,
@@ -3748,10 +4862,20 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
3748
4862
  signals: labeledSamples.flatMap(({ signals }) => signals)
3749
4863
  },
3750
4864
  hud,
4865
+ ...framebufferCoverage === void 0 ? {} : { framebufferCoverage },
3751
4866
  network: networkEntries,
4867
+ ...performanceSeries === void 0 ? {} : { performanceSeries },
3752
4868
  resources: resourceObservations(beforeSnapshot, afterSnapshot),
3753
- ...afterSnapshot?.gameplay === void 0 ? {} : { runtimeObservations: { gameplay: afterSnapshot.gameplay } },
3754
- runtimeDiagnostics: normalizedRuntimeDiagnostics(afterSnapshot, scenario),
4869
+ ...afterSnapshot?.gameplay === void 0 && labeledSamples.every(({ snapshot }) => snapshot.gameplay === void 0) ? {} : {
4870
+ runtimeObservations: {
4871
+ ...afterSnapshot?.gameplay === void 0 ? {} : { gameplay: afterSnapshot.gameplay },
4872
+ ...labeledSamples.every(({ snapshot }) => snapshot.gameplay === void 0) ? {} : {
4873
+ gameplaySeries: labeledSamples.flatMap(({ label, snapshot }) => snapshot.gameplay === void 0 ? [] : [{ gameplay: snapshot.gameplay, label, tick: snapshot.clock.tick ?? 0 }])
4874
+ }
4875
+ }
4876
+ },
4877
+ ...afterSnapshot?.physicsDebugSeries === void 0 ? {} : { physicsDebugSeries: afterSnapshot.physicsDebugSeries },
4878
+ runtimeDiagnostics: normalizedRuntimeDiagnostics(afterSnapshot, scenario, consoleEntries),
3755
4879
  ...visual === void 0 ? {} : { visual }
3756
4880
  })
3757
4881
  };
@@ -3762,6 +4886,23 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
3762
4886
  const cameraResult = evaluateCamera(scenario, afterSnapshot);
3763
4887
  const assertionResults = [...evaluated.assertions, ...cameraResult === void 0 ? [] : [cameraResult]];
3764
4888
  const allDiagnostics = [...diagnostics, ...evaluated.diagnostics];
4889
+ const softwareAdapter = capture?.rendererKind === "webgpu" ? softwareAdapterName(capture.adapter) : void 0;
4890
+ if (softwareAdapter !== void 0 && config.allowSoftwareAdapter !== true) {
4891
+ allDiagnostics.push({
4892
+ code: "TN_PLAYTEST_SOFTWARE_ADAPTER",
4893
+ message: `WebGPU was served by a software adapter: '${softwareAdapter}'. Nothing errored, so every result in this run is a CPU rasteriser's.`,
4894
+ severity: "error",
4895
+ suggestion: "Run with --headed under a display and --browser-recipe webgpu so Chromium reaches the GPU driver, or pass --allow-software to accept the fallback deliberately."
4896
+ });
4897
+ }
4898
+ if (captureFailure !== void 0) {
4899
+ allDiagnostics.push({
4900
+ code: captureFailure.code,
4901
+ message: `Visual capture '${captureFailure.label}' was blank: ${captureFailure.reason}.`,
4902
+ severity: "error",
4903
+ suggestion: "Inspect the browser display and GPU adapter before treating this run as render evidence."
4904
+ });
4905
+ }
3765
4906
  if (cameraResult?.pass === false) {
3766
4907
  allDiagnostics.push({
3767
4908
  code: "TN_PLAYTEST_CAMERA_ASSERTION_FAILED",
@@ -3773,6 +4914,7 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
3773
4914
  return {
3774
4915
  ...base,
3775
4916
  artifactDirectory: config.artifactDirectory,
4917
+ ...capture === void 0 ? {} : { capture },
3776
4918
  assertionResults,
3777
4919
  diagnostics: allDiagnostics,
3778
4920
  pass: assertionResults.every(({ pass }) => pass) && allDiagnostics.every(({ severity }) => severity !== "error"),
@@ -3782,6 +4924,25 @@ function buildReport(config, scenario, beforeSnapshot, afterSnapshot, consoleEnt
3782
4924
  url: config.url
3783
4925
  };
3784
4926
  }
4927
+ async function captureVisualSurface(page, artifactPath) {
4928
+ const canvases = page.locator("canvas");
4929
+ const sourceIndex = await canvases.evaluateAll((elements) => {
4930
+ let largestArea = 0;
4931
+ let largestIndex = -1;
4932
+ for (const [index, canvas] of elements.entries()) {
4933
+ const area = canvas.width * canvas.height;
4934
+ if (area > largestArea) {
4935
+ largestArea = area;
4936
+ largestIndex = index;
4937
+ }
4938
+ }
4939
+ return largestIndex;
4940
+ });
4941
+ if (sourceIndex < 0) return void 0;
4942
+ const content = await canvases.nth(sourceIndex).screenshot();
4943
+ if (artifactPath !== void 0) await writeFile(artifactPath, content);
4944
+ return content;
4945
+ }
3785
4946
  function buildObservations(candidate) {
3786
4947
  const observations = {};
3787
4948
  for (const field of STANDALONE_PLAYTEST_OBSERVATION_FIELDS) {
@@ -3803,8 +4964,8 @@ function componentObservations(before, after) {
3803
4964
  }]))];
3804
4965
  }));
3805
4966
  }
3806
- function screenshotObservations(before, after, scenario) {
3807
- if (after === void 0) return void 0;
4967
+ function screenshotObservations(before, after, scenario, captureFailure = void 0) {
4968
+ if (after === void 0) return captureFailure === void 0 ? void 0 : { captureFailure };
3808
4969
  const afterPng = PNG.sync.read(after);
3809
4970
  const beforePng = before === void 0 ? void 0 : PNG.sync.read(before);
3810
4971
  const sameSize = beforePng !== void 0 && beforePng.width === afterPng.width && beforePng.height === afterPng.height;
@@ -3826,7 +4987,8 @@ function screenshotObservations(before, after, scenario) {
3826
4987
  return {
3827
4988
  ...changedPixelRatio === void 0 ? {} : { changedPixelRatio },
3828
4989
  ...sameSize ? { comparisonSource: "before-after" } : {},
3829
- ...regions.length === 0 ? {} : { nonblankRegions: regions }
4990
+ ...regions.length === 0 ? {} : { nonblankRegions: regions },
4991
+ ...captureFailure === void 0 ? {} : { captureFailure }
3830
4992
  };
3831
4993
  }
3832
4994
  function regionMetrics(png, region) {
@@ -3850,10 +5012,13 @@ function regionMetrics(png, region) {
3850
5012
  return { darkPixelRatio: dark / pixels, nonblankPixelRatio: nonblank / pixels };
3851
5013
  }
3852
5014
  function failureReport(config, scenario, diagnostic) {
5015
+ const diagnosticsPolicy = resolveDiagnosticsPolicy(scenario.assert?.diagnostics);
3853
5016
  return {
3854
5017
  artifactDirectory: config.artifactDirectory,
5018
+ assertionResults: [failedDiagnosticsAssertion(diagnosticsPolicy)],
3855
5019
  debugColliders: false,
3856
5020
  diagnostics: [{ ...diagnostic, suggestion: diagnostic.fix.instruction }],
5021
+ diagnosticsPolicy,
3857
5022
  distance: 0,
3858
5023
  entity: scenario.subject ?? "",
3859
5024
  expectMoved: false,
@@ -3888,7 +5053,7 @@ function setupRequest(scenario) {
3888
5053
  }
3889
5054
  };
3890
5055
  }
3891
- async function runStep(page, bridge, step, viewport, pathEntity, pathPositions, inputState, finalStep) {
5056
+ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions, inputState, movementSampleRequest, finalStep) {
3892
5057
  if (step.pointerPosition !== void 0) {
3893
5058
  await page.mouse.move(
3894
5059
  step.pointerPosition.x * viewport.width,
@@ -3898,6 +5063,9 @@ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions,
3898
5063
  await setPointerButtons(page, inputState, step.pointerPosition.buttons);
3899
5064
  }
3900
5065
  }
5066
+ if (step.pointers !== void 0) {
5067
+ await setBrowserPointers(page, inputState, step.pointers, viewport);
5068
+ }
3901
5069
  const press = step.press;
3902
5070
  if (typeof press === "string") {
3903
5071
  await page.keyboard.down(press);
@@ -3916,28 +5084,97 @@ async function runStep(page, bridge, step, viewport, pathEntity, pathPositions,
3916
5084
  }
3917
5085
  }
3918
5086
  }
5087
+ const inputDriven = playtestStepDrivesMovement(step, inputActive(inputState));
3919
5088
  const ticks = playtestStepHoldTicks(step, 0) + playtestStepWaitTicks(step);
3920
5089
  const frames = (step.holdFrames ?? 0) + (step.waitFrames ?? 0);
3921
5090
  if (ticks > 0 && bridge?.description.capabilities.includes("runtime.fixedStep") === true) {
3922
- for (let index = 0; index < ticks; index += 1) {
3923
- await bridge.advance(1);
5091
+ const sampleTicks = 10;
5092
+ for (let index = 0; index < ticks; index += sampleTicks) {
5093
+ await bridge.advance(Math.min(sampleTicks, ticks - index));
3924
5094
  await samplePathPosition(bridge, pathEntity, pathPositions);
3925
5095
  }
3926
5096
  } else {
3927
5097
  await waitFrames(page, Math.max(frames, ticks, 1));
3928
5098
  await samplePathPosition(bridge, pathEntity, pathPositions);
3929
5099
  }
5100
+ const afterInput = bridge === void 0 || movementSampleRequest === void 0 ? void 0 : await bridge.sample(movementSampleRequest);
5101
+ let afterStep = afterInput;
3930
5102
  if (press !== void 0 && step.release) {
3931
5103
  const released = typeof press === "string" ? [press] : [...inputState.heldKeys];
3932
5104
  for (const key of released) {
3933
5105
  await page.keyboard.up(key);
3934
5106
  inputState.heldKeys.delete(key);
3935
5107
  }
3936
- if (!finalStep) await waitFrames(page, 1);
5108
+ if (!finalStep) {
5109
+ if (bridge?.description.capabilities.includes("runtime.fixedStep") === true) {
5110
+ await bridge.advance(1);
5111
+ } else {
5112
+ await waitFrames(page, 1);
5113
+ }
5114
+ if (bridge !== void 0 && movementSampleRequest !== void 0) {
5115
+ afterStep = await bridge.sample(movementSampleRequest);
5116
+ }
5117
+ }
3937
5118
  }
3938
5119
  if (step.pointerPosition?.buttons !== void 0 && step.release) {
3939
5120
  await setPointerButtons(page, inputState, 0);
3940
5121
  }
5122
+ if (step.pointers !== void 0 && step.release) {
5123
+ await setBrowserPointers(page, inputState, [], viewport);
5124
+ if (bridge?.description.capabilities.includes("runtime.fixedStep") === true) {
5125
+ await bridge.advance(1);
5126
+ } else {
5127
+ await waitFrames(page, 1);
5128
+ }
5129
+ if (bridge !== void 0 && movementSampleRequest !== void 0) {
5130
+ afterStep = await bridge.sample(movementSampleRequest);
5131
+ }
5132
+ }
5133
+ return { afterInput, afterStep, inputDriven };
5134
+ }
5135
+ function playtestStepDrivesMovement(step, hasHeldInput) {
5136
+ const hasNewInput = typeof step.press === "string" ? step.press.length > 0 : (step.press?.length ?? 0) > 0 || step.pointerPosition !== void 0 || (step.pointers?.length ?? 0) > 0;
5137
+ return hasNewInput || step.press === void 0 && step.pointers === void 0 && step.pointerPosition === void 0 && hasHeldInput;
5138
+ }
5139
+ function inputActive(inputState) {
5140
+ return inputState.heldKeys.size > 0 || inputState.pointerButtons !== 0 || inputState.pointers.size > 0;
5141
+ }
5142
+ async function setBrowserPointers(page, inputState, next, viewport) {
5143
+ const changes = reconcileBrowserPointers(inputState.pointers, next);
5144
+ if (next.some(({ buttons }) => buttons !== void 0 && buttons !== 1)) {
5145
+ throw new Error("Browser touch injection supports buttons=1 only.");
5146
+ }
5147
+ inputState.touchSession ??= await page.context().newCDPSession(page);
5148
+ const session = inputState.touchSession;
5149
+ const points = (pointers) => pointers.map((pointer) => ({
5150
+ force: 1,
5151
+ id: pointer.id,
5152
+ radiusX: 1,
5153
+ radiusY: 1,
5154
+ x: pointer.x * viewport.width,
5155
+ y: pointer.y * viewport.height
5156
+ }));
5157
+ const removed = changes.filter(({ type }) => type === "pointerup").map(({ pointer }) => pointer);
5158
+ const added = changes.filter(({ type }) => type === "pointerdown").map(({ pointer }) => pointer);
5159
+ const moved = changes.filter(({ type }) => type === "pointermove").map(({ pointer }) => pointer);
5160
+ if (removed.length > 0) {
5161
+ await session.send("Input.dispatchTouchEvent", {
5162
+ touchPoints: points(removed),
5163
+ type: "touchEnd"
5164
+ });
5165
+ }
5166
+ if (added.length > 0) {
5167
+ await session.send("Input.dispatchTouchEvent", { touchPoints: points(added), type: "touchStart" });
5168
+ }
5169
+ if (moved.length > 0) {
5170
+ await session.send("Input.dispatchTouchEvent", { touchPoints: points(moved), type: "touchMove" });
5171
+ }
5172
+ inputState.pointers = new Map(next.map((pointer) => [pointer.id, {
5173
+ buttons: pointer.buttons ?? 1,
5174
+ id: pointer.id,
5175
+ x: pointer.x,
5176
+ y: pointer.y
5177
+ }]));
3941
5178
  }
3942
5179
  var POINTER_BUTTONS = [
3943
5180
  { button: "left", mask: 1 },
@@ -3988,13 +5225,15 @@ async function waitFrames(page, frames) {
3988
5225
  }), frames);
3989
5226
  }
3990
5227
  function observedEntityIds(scenario) {
3991
- return [...new Set([
5228
+ if (isAnonymousMovementScenario(scenario)) return void 0;
5229
+ const ids = [...new Set([
3992
5230
  scenario.subject,
3993
5231
  scenario.assert?.movement?.entity,
3994
5232
  scenario.assert?.camera?.entity,
3995
5233
  scenario.assert?.camera?.follows,
3996
5234
  ...(scenario.assert?.visibility ?? []).map(({ entity }) => entity)
3997
5235
  ].filter((value) => value !== void 0))];
5236
+ return ids.length > 0 ? ids : scenario.assert?.movement === void 0 ? [] : void 0;
3998
5237
  }
3999
5238
  function observedResourceIds(scenario) {
4000
5239
  return [.../* @__PURE__ */ new Set([
@@ -4030,6 +5269,48 @@ function pairObservations(before, after) {
4030
5269
  function entityPosition(snapshot, id) {
4031
5270
  return snapshot?.entities?.find((entity) => entity.id === id)?.transform?.position;
4032
5271
  }
5272
+ function isAnonymousMovementScenario(scenario) {
5273
+ return scenario.assert?.movement !== void 0 && scenario.assert.movement.entity === void 0 && scenario.subject === void 0;
5274
+ }
5275
+ function observedMovementSample(samples) {
5276
+ const inputOff = samples.filter(({ inputDriven }) => !inputDriven);
5277
+ if (inputOff.length === 0) return void 0;
5278
+ return samples.filter(({ inputDriven }) => inputDriven).flatMap((sample) => observedMovementEntities(sample.before, sample.after).flatMap(({ id, distance }) => {
5279
+ const inputOffBaseline = inputOff.every((offSample) => {
5280
+ const offEntity = observedMovementEntities(offSample.before, offSample.after).find(({ id: offId }) => offId === id);
5281
+ return offEntity !== void 0 && offEntity.distance === 0 && movementRate(offSample, id) !== void 0;
5282
+ });
5283
+ const inputOnRate = movementRate(sample, id);
5284
+ return !inputOffBaseline || inputOnRate === void 0 || inputOnRate <= 0 ? [] : [{ ...sample, distance, entity: id, contrast: inputOnRate }];
5285
+ })).sort((left, right) => right.distance - left.distance || right.contrast - left.contrast || left.entity.localeCompare(right.entity))[0];
5286
+ }
5287
+ function observedMovementEntities(before, after) {
5288
+ const beforeEntities = new Map(
5289
+ (before.entities ?? []).filter(({ transform }) => transform?.position !== void 0).map(({ id, transform }) => [id, transform.position])
5290
+ );
5291
+ return (after.entities ?? []).flatMap((entity) => {
5292
+ const beforePosition = beforeEntities.get(entity.id);
5293
+ const afterPosition = entity.transform?.position;
5294
+ return beforePosition === void 0 || afterPosition === void 0 || entity.visible === false ? [] : [{ distance: length(subtract(afterPosition, beforePosition)), id: entity.id }];
5295
+ });
5296
+ }
5297
+ function movementRate(sample, entity) {
5298
+ const beforePosition = entityPosition(sample.before, entity);
5299
+ const afterPosition = entityPosition(sample.after, entity);
5300
+ if (beforePosition === void 0 || afterPosition === void 0) return void 0;
5301
+ const duration = movementDuration(sample);
5302
+ return duration === void 0 ? void 0 : length(subtract(afterPosition, beforePosition)) / duration;
5303
+ }
5304
+ function movementDuration(sample) {
5305
+ if (sample.before.clock.mode !== sample.after.clock.mode) return void 0;
5306
+ const duration = sample.before.clock.mode === "fixed-step" ? positiveFiniteDelta(sample.before.clock.tick, sample.after.clock.tick) : positiveFiniteDelta(sample.before.clock.timeMs, sample.after.clock.timeMs);
5307
+ return duration;
5308
+ }
5309
+ function positiveFiniteDelta(before, after) {
5310
+ if (typeof before !== "number" || typeof after !== "number" || !Number.isFinite(before) || !Number.isFinite(after)) return void 0;
5311
+ const delta = after - before;
5312
+ return Number.isFinite(delta) && delta > 0 ? delta : void 0;
5313
+ }
4033
5314
  function entityRotation(snapshot, id) {
4034
5315
  return snapshot?.entities?.find((entity) => entity.id === id)?.transform?.rotation;
4035
5316
  }
@@ -4037,9 +5318,22 @@ function resourceObservations(before, after) {
4037
5318
  const ids = /* @__PURE__ */ new Set([...Object.keys(before?.resources ?? {}), ...Object.keys(after?.resources ?? {})]);
4038
5319
  return Object.fromEntries([...ids].map((id) => [id, { before: before?.resources?.[id], after: after?.resources?.[id] }]));
4039
5320
  }
4040
- function normalizedRuntimeDiagnostics(snapshot, scenario) {
5321
+ function isRuntimeReadout(entry) {
5322
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return false;
5323
+ const record2 = entry;
5324
+ if (record2.severity === "error" || record2.error !== void 0) return false;
5325
+ if (typeof record2.type === "string" && ["assert", "error", "pageerror"].includes(record2.type)) return false;
5326
+ const value = record2.value;
5327
+ return typeof record2.label === "string" && (typeof value === "string" || typeof value === "number" || typeof value === "boolean");
5328
+ }
5329
+ function normalizedRuntimeDiagnostics(snapshot, scenario, consoleEntries) {
5330
+ const published = snapshot?.diagnostics ?? [];
4041
5331
  return {
4042
- recentRuntimeErrors: snapshot?.diagnostics ?? [],
5332
+ recentRuntimeErrors: [
5333
+ ...published.filter((entry) => !isRuntimeReadout(entry)),
5334
+ ...consoleEntries.filter(({ source, type }) => source !== "browser-console" && ["assert", "error", "pageerror"].includes(type))
5335
+ ],
5336
+ runtimeReadouts: published.filter(isRuntimeReadout),
4043
5337
  scene: {
4044
5338
  renderedEntities: (snapshot?.entities ?? []).map((entity) => ({
4045
5339
  id: entity.id,
@@ -4049,6 +5343,88 @@ function normalizedRuntimeDiagnostics(snapshot, scenario) {
4049
5343
  }
4050
5344
  };
4051
5345
  }
5346
+ async function readCaptureProvenance(page, config, scenario) {
5347
+ const observed = await page.evaluate(async () => {
5348
+ const gpu = globalThis.navigator.gpu;
5349
+ const adapter = gpu === void 0 ? null : await gpu.requestAdapter().catch(() => null);
5350
+ const infoCandidate = adapter?.info;
5351
+ const legacyInfo = await adapter?.requestAdapterInfo?.().catch(() => void 0);
5352
+ const info = infoCandidate === void 0 || Object.keys(infoCandidate).length === 0 ? legacyInfo ?? infoCandidate : infoCandidate;
5353
+ const adapterIdentityKeys = ["architecture", "description", "device", "vendor"];
5354
+ const adapterIdentityEntries = info === void 0 ? [] : adapterIdentityKeys.flatMap((key) => {
5355
+ const value = info[key];
5356
+ const text = String(value ?? "");
5357
+ return text.length === 0 ? [] : [[key, text]];
5358
+ });
5359
+ const webgpuAdapterEntries = [...adapterIdentityEntries];
5360
+ if (adapterIdentityEntries.length > 0 && adapter?.features !== void 0) {
5361
+ const features = [...adapter.features].map(String).sort();
5362
+ if (features.length > 0) webgpuAdapterEntries.push(["features", features.join(",")]);
5363
+ }
5364
+ if (adapterIdentityEntries.length > 0) {
5365
+ for (const key of ["maxBindGroups", "maxTextureDimension2D", "maxStorageBufferBindingSize"]) {
5366
+ const value = adapter?.limits?.[key];
5367
+ if (typeof value === "number" && Number.isFinite(value)) webgpuAdapterEntries.push([`limit.${key}`, String(value)]);
5368
+ }
5369
+ }
5370
+ const webgpuAdapterInfo = adapterIdentityEntries.length === 0 ? void 0 : Object.fromEntries(webgpuAdapterEntries);
5371
+ const canvas = document.querySelector("canvas");
5372
+ const engine = canvas?.getAttribute("data-engine")?.toLowerCase() ?? "";
5373
+ let rendererKind;
5374
+ if (engine.includes("webgpu")) rendererKind = "webgpu";
5375
+ else if (engine.includes("webgl")) rendererKind = "webgl";
5376
+ else if (adapter !== null && canvas !== null) {
5377
+ try {
5378
+ if (canvas.getContext("webgpu") !== null) rendererKind = "webgpu";
5379
+ } catch {
5380
+ }
5381
+ }
5382
+ let webglAdapterInfo;
5383
+ if (rendererKind === void 0 || rendererKind === "webgl") {
5384
+ try {
5385
+ const context = canvas?.getContext("webgl2") ?? canvas?.getContext("webgl");
5386
+ if (context !== null && context !== void 0) {
5387
+ rendererKind = "webgl";
5388
+ const debugInfo = context.getExtension("WEBGL_debug_renderer_info");
5389
+ const vendor = String(context.getParameter(debugInfo?.UNMASKED_VENDOR_WEBGL ?? context.VENDOR) ?? "");
5390
+ const renderer = String(context.getParameter(debugInfo?.UNMASKED_RENDERER_WEBGL ?? context.RENDERER) ?? "");
5391
+ const webglEntries = [
5392
+ ["renderer", renderer],
5393
+ ["vendor", vendor]
5394
+ ];
5395
+ webglAdapterInfo = Object.fromEntries(webglEntries.filter(([, value]) => value.length > 0));
5396
+ }
5397
+ } catch {
5398
+ }
5399
+ }
5400
+ return {
5401
+ adapter: rendererKind === "webgl" ? webglAdapterInfo : webgpuAdapterInfo,
5402
+ rendererKind
5403
+ };
5404
+ });
5405
+ if (observed.adapter === void 0 || Object.keys(observed.adapter).length === 0) {
5406
+ throw new PlaytestBridgeError(playtestDiagnostic(
5407
+ "TN_PLAYTEST_CAPTURE_PROVENANCE_MISSING",
5408
+ `Visual capture could not read a renderer adapter description (kind=${observed.rendererKind ?? "unknown"}).`,
5409
+ "Run the visual playtest with a working GPU/WebGPU adapter or WebGL renderer; the runner will not write unknown adapter provenance."
5410
+ ));
5411
+ }
5412
+ if (observed.rendererKind === void 0) {
5413
+ throw new PlaytestBridgeError(playtestDiagnostic(
5414
+ "TN_PLAYTEST_CAPTURE_PROVENANCE_MISSING",
5415
+ "Visual capture could not identify the page renderer kind.",
5416
+ "Expose a WebGPU/WebGL canvas before capturing the visual artifact, then rerun the playtest."
5417
+ ));
5418
+ }
5419
+ return {
5420
+ adapter: observed.adapter,
5421
+ browserArgs: resolveBrowserArguments(config.browserArgs),
5422
+ captureMethod: "page.screenshot",
5423
+ rendererKind: observed.rendererKind,
5424
+ target: scenario.target,
5425
+ viewport: { ...scenario.viewport }
5426
+ };
5427
+ }
4052
5428
  function pixelBoundsToNdc(bounds, viewport) {
4053
5429
  return {
4054
5430
  max: [2 * (bounds.x + bounds.width) / viewport.width - 1, 1 - 2 * bounds.y / viewport.height],
@@ -4103,6 +5479,74 @@ function startManagedServer(config) {
4103
5479
  });
4104
5480
  return server;
4105
5481
  }
5482
+ var PAGE_NAVIGATED_PATTERN = /Execution context was destroyed|frame (?:was )?detached|Target (?:page|closed)/iu;
5483
+ var TEARDOWN_TIMED_OUT = /* @__PURE__ */ Symbol("teardown-timed-out");
5484
+ async function boundedTeardownStep(step, timeoutMs) {
5485
+ if (step === void 0) return true;
5486
+ let timer;
5487
+ const timeout = new Promise((resolveTimeout) => {
5488
+ timer = setTimeout(() => resolveTimeout(TEARDOWN_TIMED_OUT), timeoutMs);
5489
+ });
5490
+ try {
5491
+ return await Promise.race([step.catch(() => void 0), timeout]) !== TEARDOWN_TIMED_OUT;
5492
+ } finally {
5493
+ if (timer !== void 0) clearTimeout(timer);
5494
+ }
5495
+ }
5496
+ function isPageNavigatedRace(error) {
5497
+ return error instanceof Error && PAGE_NAVIGATED_PATTERN.test(error.message);
5498
+ }
5499
+ function pageLifecycleDiagnostic(error, lifecycle, url) {
5500
+ if (!lifecycle.crashed && !isPageNavigatedRace(error)) return void 0;
5501
+ const detail = error instanceof Error ? error.message : String(error);
5502
+ if (lifecycle.crashed) {
5503
+ return playtestDiagnostic(
5504
+ "TN_PLAYTEST_PAGE_CRASHED",
5505
+ `The browser page crashed while the scenario was running at '${url}'; runner error: ${detail}.`,
5506
+ "The renderer process died mid-run, so no assertion after that point was observed. Re-run with a smaller scene or a hardware GPU; under a virtual display the software WebGPU path is the usual cause."
5507
+ );
5508
+ }
5509
+ const where = lifecycle.navigations.length === 0 ? "an unrecorded location" : `'${lifecycle.navigations.join("', '")}'`;
5510
+ const observed = [
5511
+ `page closed: ${lifecycle.closed}`,
5512
+ `main-frame navigations: ${lifecycle.frameNavigations.length}`,
5513
+ ...lifecycle.tail.length === 0 ? [] : [`last console: ${lifecycle.tail.join(" | ")}`]
5514
+ ].join("; ");
5515
+ return playtestDiagnostic(
5516
+ "TN_PLAYTEST_PAGE_NAVIGATED",
5517
+ `The page navigated to ${where} while the scenario was running at '${url}'; runner error: ${detail}. Observed: ${observed}.`,
5518
+ "Something moved the document after the run started, so the observations after that point are from a different page. Remove the navigation from the game, or point --url at a server that does not reload itself mid-run."
5519
+ );
5520
+ }
5521
+ async function openPageAndConnectBridge(page, config, scenario) {
5522
+ const attempts = 3;
5523
+ let lastError;
5524
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
5525
+ try {
5526
+ await page.goto(config.url, { timeout: config.timeoutMs, waitUntil: "domcontentloaded" });
5527
+ await page.waitForLoadState("load", { timeout: config.timeoutMs }).catch(() => void 0);
5528
+ return await connectPlaytestBridge(page, scenario);
5529
+ } catch (error) {
5530
+ if (error instanceof PlaytestBridgeError || !isPageNavigatedRace(error)) throw error;
5531
+ lastError = error instanceof Error ? error : new Error(String(error));
5532
+ }
5533
+ }
5534
+ throw new PlaytestBridgeError(playtestDiagnostic(
5535
+ "TN_PLAYTEST_PAGE_NAVIGATED",
5536
+ `The page navigated during the bridge handshake on all ${attempts} attempts at '${config.url}'; last runner error: ${lastError?.message ?? "unknown"}.`,
5537
+ "The served page is reloading itself while the run starts. With a Vite dev server this is usually dependency pre-bundling: run the project's build or dev command once before the scenario so the dependency cache is warm, or point --url at a preview server instead.",
5538
+ { nextCommand: config.server?.command }
5539
+ ));
5540
+ }
5541
+ async function assertManagedUrlAvailable(url) {
5542
+ try {
5543
+ const response = await fetch(url, { method: "HEAD", signal: AbortSignal.timeout(500) });
5544
+ await response.body?.cancel();
5545
+ } catch {
5546
+ return;
5547
+ }
5548
+ throw managedServerError("Managed server URL is already in use before startup.", url, 0, []);
5549
+ }
4106
5550
  async function waitForUrl(url, timeoutMs, server) {
4107
5551
  const started = Date.now();
4108
5552
  const output = [];
@@ -4126,8 +5570,9 @@ async function waitForUrl(url, timeoutMs, server) {
4126
5570
  }
4127
5571
  throw managedServerError(`Managed server did not become ready within ${timeoutMs}ms.`, url, timeoutMs, output);
4128
5572
  }
4129
- function stopManagedServer(server) {
4130
- if (server?.pid === void 0 || server.exitCode !== null) return;
5573
+ async function stopManagedServer(server) {
5574
+ if (server?.pid === void 0 || server.exitCode !== null || server.signalCode !== null) return;
5575
+ const stopped = waitForProcessExit2(server, 2e3);
4131
5576
  if (process.platform === "win32") server.kill();
4132
5577
  else {
4133
5578
  try {
@@ -4135,6 +5580,29 @@ function stopManagedServer(server) {
4135
5580
  } catch {
4136
5581
  }
4137
5582
  }
5583
+ if (await stopped) return;
5584
+ if (process.platform === "win32") server.kill("SIGKILL");
5585
+ else {
5586
+ try {
5587
+ process.kill(-server.pid, "SIGKILL");
5588
+ } catch {
5589
+ }
5590
+ }
5591
+ await waitForProcessExit2(server, 1e3);
5592
+ }
5593
+ function waitForProcessExit2(server, timeoutMs) {
5594
+ if (server.exitCode !== null || server.signalCode !== null) return Promise.resolve(true);
5595
+ return new Promise((resolveExit) => {
5596
+ const timeout = setTimeout(() => {
5597
+ server.off("exit", onExit);
5598
+ resolveExit(false);
5599
+ }, timeoutMs);
5600
+ const onExit = () => {
5601
+ clearTimeout(timeout);
5602
+ resolveExit(true);
5603
+ };
5604
+ server.once("exit", onExit);
5605
+ });
4138
5606
  }
4139
5607
  function managedServerError(message, url, timeoutMs, output) {
4140
5608
  return new ManagedServerError(playtestDiagnostic(
@@ -4143,6 +5611,219 @@ function managedServerError(message, url, timeoutMs, output) {
4143
5611
  "Run the server command directly, fix its first error, then rerun the same playtest command."
4144
5612
  ));
4145
5613
  }
5614
+ var execFileAsync2 = promisify(execFile);
5615
+ var DEFAULT_GRID = { columns: 32, rows: 18 };
5616
+ async function analyzeFramebufferCoverageRecording(videoPath, artifactDirectory, assertion, boundarySource = "video-backdrop-dominance") {
5617
+ await mkdir(artifactDirectory, { recursive: true });
5618
+ const frameDirectory = await mkdtemp(join(artifactDirectory, ".framebuffer-coverage-frames-"));
5619
+ try {
5620
+ const pattern = join(frameDirectory, "frame-%06d.png");
5621
+ await execFileAsync2(
5622
+ "ffmpeg",
5623
+ ["-loglevel", "error", "-i", videoPath, "-vsync", "0", pattern],
5624
+ { maxBuffer: 32 * 1024 * 1024 }
5625
+ );
5626
+ const framePaths = (await readdir(frameDirectory)).filter((name) => /^frame-\d+\.png$/u.test(name)).sort().map((name) => join(frameDirectory, name));
5627
+ if (framePaths.length === 0) {
5628
+ return {
5629
+ boundarySource,
5630
+ frameCount: 0,
5631
+ unreadableReason: "TN_PLAYTEST_FRAMEBUFFER_COVERAGE_VIDEO_NO_FRAMES",
5632
+ windowCompleted: false,
5633
+ windowStarted: false
5634
+ };
5635
+ }
5636
+ const box = await findVideoContentBoxFromFiles(framePaths);
5637
+ if (box === void 0) {
5638
+ return {
5639
+ boundarySource,
5640
+ frameCount: 0,
5641
+ unreadableReason: "TN_PLAYTEST_FRAMEBUFFER_COVERAGE_VIDEO_ALL_BLACK",
5642
+ windowCompleted: false,
5643
+ windowStarted: false
5644
+ };
5645
+ }
5646
+ const gridSize = assertion.grid ?? DEFAULT_GRID;
5647
+ const grids = [];
5648
+ for (const path of framePaths) {
5649
+ grids.push(sampleFramebufferCoverageVideoFrame(PNG.sync.read(await readFile(path)), box, gridSize));
5650
+ }
5651
+ const observation = boundarySource === "scenario-steps" ? analyzeScenarioBracketedCoverageFrames(grids, framePaths, assertion) : analyzeSampledCoverageFrames(grids, framePaths, assertion);
5652
+ if (observation.firstViolation === void 0) return observation;
5653
+ const screenshotPath = join(
5654
+ artifactDirectory,
5655
+ `framebuffer-coverage-failure-${observation.firstViolation.frameIndex}.png`
5656
+ );
5657
+ await copyFile(observation.firstViolation.screenshotPath, screenshotPath);
5658
+ return {
5659
+ ...observation,
5660
+ firstViolation: { ...observation.firstViolation, screenshotPath }
5661
+ };
5662
+ } catch (error) {
5663
+ return {
5664
+ boundarySource,
5665
+ frameCount: 0,
5666
+ unreadableReason: `TN_PLAYTEST_FRAMEBUFFER_COVERAGE_VIDEO_UNREADABLE:${errorMessage(error)}`,
5667
+ windowCompleted: false,
5668
+ windowStarted: false
5669
+ };
5670
+ } finally {
5671
+ await rm(frameDirectory, { force: true, recursive: true });
5672
+ }
5673
+ }
5674
+ function analyzeScenarioBracketedCoverageFrames(grids, framePaths, assertion) {
5675
+ const base = {
5676
+ boundarySource: "scenario-steps",
5677
+ windowCompleted: true,
5678
+ windowStarted: true
5679
+ };
5680
+ if (grids.length === 0) {
5681
+ return {
5682
+ ...base,
5683
+ frameCount: 0,
5684
+ unreadableReason: "TN_PLAYTEST_FRAMEBUFFER_COVERAGE_VIDEO_NO_FRAMES"
5685
+ };
5686
+ }
5687
+ if (framePaths.length !== grids.length) {
5688
+ return {
5689
+ ...base,
5690
+ frameCount: 0,
5691
+ unreadableReason: "TN_PLAYTEST_FRAMEBUFFER_COVERAGE_VIDEO_PATH_COUNT"
5692
+ };
5693
+ }
5694
+ const firstViolationOffset = grids.findIndex(
5695
+ (grid) => grid.samples.some((sample) => !sampleMatches(sample, assertion.backdrop, assertion.tolerance))
5696
+ );
5697
+ if (firstViolationOffset === -1) {
5698
+ return {
5699
+ ...base,
5700
+ frameCount: grids.length
5701
+ };
5702
+ }
5703
+ const violationGrid = grids[firstViolationOffset];
5704
+ const violationFramePath = framePaths[firstViolationOffset];
5705
+ if (violationGrid === void 0 || violationFramePath === void 0) {
5706
+ return {
5707
+ ...base,
5708
+ frameCount: 0,
5709
+ unreadableReason: "TN_PLAYTEST_FRAMEBUFFER_COVERAGE_VIDEO_PATH_COUNT"
5710
+ };
5711
+ }
5712
+ return {
5713
+ ...base,
5714
+ firstViolation: {
5715
+ frameIndex: firstViolationOffset,
5716
+ grid: violationGrid,
5717
+ screenshotPath: violationFramePath
5718
+ },
5719
+ frameCount: grids.length
5720
+ };
5721
+ }
5722
+ async function findVideoContentBoxFromFiles(framePaths) {
5723
+ const appPaths = framePaths.slice(Math.floor(framePaths.length / 2));
5724
+ const firstPath = appPaths[0];
5725
+ if (firstPath === void 0) return void 0;
5726
+ const accumulator = createContentBoxAccumulator(PNG.sync.read(await readFile(firstPath)));
5727
+ for (const path of appPaths) {
5728
+ if (!accumulateContentBox(accumulator, PNG.sync.read(await readFile(path)))) {
5729
+ throw new Error("TN_PLAYTEST_FRAMEBUFFER_COVERAGE_VIDEO_SIZE_CHANGED");
5730
+ }
5731
+ }
5732
+ return finishContentBox(accumulator);
5733
+ }
5734
+ function createContentBoxAccumulator(frame) {
5735
+ return {
5736
+ columnLit: new Uint8Array(frame.width),
5737
+ height: frame.height,
5738
+ rowLit: new Uint8Array(frame.height),
5739
+ width: frame.width
5740
+ };
5741
+ }
5742
+ function accumulateContentBox(accumulator, frame) {
5743
+ if (frame.width !== accumulator.width || frame.height !== accumulator.height) return false;
5744
+ for (let y = 0; y < frame.height; y += 1) {
5745
+ for (let x = 0; x < frame.width; x += 1) {
5746
+ const offset = (y * frame.width + x) * 4;
5747
+ if (frame.data[offset] > 12 || frame.data[offset + 1] > 12 || frame.data[offset + 2] > 12) {
5748
+ accumulator.rowLit[y] = 1;
5749
+ accumulator.columnLit[x] = 1;
5750
+ }
5751
+ }
5752
+ }
5753
+ return true;
5754
+ }
5755
+ function finishContentBox({ columnLit, height, rowLit, width }) {
5756
+ const firstRow = rowLit.indexOf(1);
5757
+ const firstColumn = columnLit.indexOf(1);
5758
+ if (firstRow === -1 || firstColumn === -1) return void 0;
5759
+ let lastRow = height - 1;
5760
+ while (lastRow > firstRow && rowLit[lastRow] === 0) lastRow -= 1;
5761
+ let lastColumn = width - 1;
5762
+ while (lastColumn > firstColumn && columnLit[lastColumn] === 0) lastColumn -= 1;
5763
+ return {
5764
+ height: lastRow - firstRow + 1,
5765
+ width: lastColumn - firstColumn + 1,
5766
+ x: firstColumn,
5767
+ y: firstRow
5768
+ };
5769
+ }
5770
+ function sampleFramebufferCoverageVideoFrame(frame, box, grid = DEFAULT_GRID) {
5771
+ const samples = [];
5772
+ for (let row = 0; row < grid.rows; row += 1) {
5773
+ const y = box.y + Math.min(box.height - 1, Math.floor((row + 0.5) / grid.rows * box.height));
5774
+ for (let column = 0; column < grid.columns; column += 1) {
5775
+ const x = box.x + Math.min(box.width - 1, Math.floor((column + 0.5) / grid.columns * box.width));
5776
+ const offset = (y * frame.width + x) * 4;
5777
+ samples.push([frame.data[offset], frame.data[offset + 1], frame.data[offset + 2]]);
5778
+ }
5779
+ }
5780
+ return { columns: grid.columns, rows: grid.rows, samples };
5781
+ }
5782
+ function analyzeSampledCoverageFrames(grids, framePaths, assertion) {
5783
+ const base = {
5784
+ boundarySource: "video-backdrop-dominance",
5785
+ frameCount: 0,
5786
+ windowCompleted: false,
5787
+ windowStarted: false
5788
+ };
5789
+ const matchingFractions = grids.map(
5790
+ (grid) => grid.samples.reduce(
5791
+ (count, sample) => count + (sampleMatches(sample, assertion.backdrop, assertion.tolerance) ? 1 : 0),
5792
+ 0
5793
+ ) / grid.samples.length
5794
+ );
5795
+ const dominantFrames = matchingFractions.map((fraction, index) => ({ fraction, index })).filter(({ fraction }) => fraction > 0.5).map(({ index }) => index);
5796
+ const firstVideoFrame = dominantFrames[0];
5797
+ const lastVideoFrame = dominantFrames.at(-1);
5798
+ if (firstVideoFrame === void 0 || lastVideoFrame === void 0) return base;
5799
+ const windowFrames = grids.slice(firstVideoFrame, lastVideoFrame + 1);
5800
+ const firstViolationOffset = windowFrames.findIndex(
5801
+ (grid) => grid.samples.some((sample) => !sampleMatches(sample, assertion.backdrop, assertion.tolerance))
5802
+ );
5803
+ return {
5804
+ ...base,
5805
+ frameCount: windowFrames.length,
5806
+ ...firstViolationOffset === -1 ? {} : {
5807
+ firstViolation: {
5808
+ frameIndex: firstViolationOffset,
5809
+ grid: windowFrames[firstViolationOffset],
5810
+ screenshotPath: framePaths[firstVideoFrame + firstViolationOffset]
5811
+ }
5812
+ },
5813
+ windowCompleted: lastVideoFrame < grids.length - 1,
5814
+ windowStarted: firstVideoFrame > 0
5815
+ };
5816
+ }
5817
+ function sampleMatches(sample, backdrop, tolerance) {
5818
+ return Math.max(
5819
+ Math.abs(sample[0] - backdrop[0]),
5820
+ Math.abs(sample[1] - backdrop[1]),
5821
+ Math.abs(sample[2] - backdrop[2])
5822
+ ) <= tolerance;
5823
+ }
5824
+ function errorMessage(error) {
5825
+ return error instanceof Error ? error.message : String(error);
5826
+ }
4146
5827
 
4147
5828
  // src/runner/androidRunner.ts
4148
5829
  async function runAndroidPlaytest(config, dependencies = {}) {
@@ -4157,7 +5838,7 @@ async function runAndroidPlaytest(config, dependencies = {}) {
4157
5838
  ...config.device === void 0 ? {} : { serial: config.device }
4158
5839
  });
4159
5840
  const mailboxRoot = config.mailboxRoot ?? `/sdcard/Android/data/${android.packageName}/files`;
4160
- return runDevicePlaytest(config, {
5841
+ return runDevicePlaytest({ ...config, mailboxRoot }, {
4161
5842
  driver,
4162
5843
  mailboxPaths: androidMailboxPaths(android.packageName, mailboxRoot),
4163
5844
  name: "android",
@@ -4170,9 +5851,26 @@ async function runDevicePlaytest(config, target) {
4170
5851
  await mkdir(config.artifactDirectory, { recursive: true });
4171
5852
  const unsupported = unsupportedAssertion(scenario, target.name);
4172
5853
  if (unsupported !== void 0) return failureReport2(config, scenario, unsupported, target.name);
5854
+ if (target.name === "android" && scenario.assert?.framebufferCoverage !== void 0 && (typeof target.driver.startScreenRecording !== "function" || typeof target.driver.stopScreenRecording !== "function")) {
5855
+ return failureReport2(config, scenario, unsupportedDiagnostic(
5856
+ "framebuffer coverage recording",
5857
+ "Use the adb-backed Android driver; framebuffer coverage requires screenrecord and offline ffmpeg analysis.",
5858
+ target.name
5859
+ ), target.name);
5860
+ }
5861
+ if (target.name === "android" && scenario.steps.some((step) => step.pointers !== void 0) && typeof target.driver.setPointers !== "function") {
5862
+ return failureReport2(config, scenario, unsupportedDiagnostic(
5863
+ "complete held-pointer input",
5864
+ "Use the emulator-backed Android driver; multi-pointer steps cannot fall back to one-pointer bridge input.",
5865
+ target.name
5866
+ ), target.name);
5867
+ }
4173
5868
  const endpoint = config.endpoint ?? "http://127.0.0.1:41777/playtest";
4174
5869
  const transport = target.transport ?? createDeviceTransport(target.driver, endpoint, target.mailboxPaths);
4175
5870
  let bridge;
5871
+ let coverageRecordingStarted = false;
5872
+ let framebufferCoverage;
5873
+ const coverageVideoPath = join(config.artifactDirectory, "framebuffer-coverage.mp4");
4176
5874
  try {
4177
5875
  await transport.start();
4178
5876
  await target.driver.prepare(endpoint, config.mailboxRoot);
@@ -4193,19 +5891,40 @@ async function runDevicePlaytest(config, target) {
4193
5891
  }
4194
5892
  if (scenario.setup !== void 0) await bridge.applySetup(setupRequest2(scenario));
4195
5893
  if (scenario.warmupFrames > 0) await bridge.advance(scenario.warmupFrames);
5894
+ const entityIds = observedEntityIds2(scenario);
4196
5895
  const sampleRequest = {
4197
- entities: observedEntityIds2(scenario),
4198
- include: ["components", "diagnostics", "entities", "resources"],
5896
+ ...entityIds === void 0 ? {} : { entities: entityIds },
5897
+ include: [
5898
+ "components",
5899
+ "diagnostics",
5900
+ "entities",
5901
+ "resources",
5902
+ ...scenario.assert?.aerodynamics === void 0 && scenario.assert?.contacts === void 0 && scenario.assert?.settled === void 0 ? [] : ["physicsDebugSeries"]
5903
+ ],
4199
5904
  resources: observedResourceIds2(scenario)
4200
5905
  };
4201
5906
  const before = await bridge.sample(sampleRequest);
4202
5907
  const pathEntity = scenario.assert?.movement?.pathLength === void 0 ? void 0 : scenario.assert.movement.entity ?? scenario.subject;
4203
5908
  const pathPositions = [];
4204
5909
  appendPosition(pathPositions, before, pathEntity);
5910
+ const capturesAnonymousMovement = scenario.assert?.movement !== void 0 && scenario.assert.movement.entity === void 0 && scenario.subject === void 0;
5911
+ const movementSamples = [];
5912
+ let movementCursor = before;
4205
5913
  const labeledSamples = [];
4206
5914
  const heldKeys = /* @__PURE__ */ new Set();
4207
5915
  let pointerButtons = 0;
4208
- for (const step of scenario.steps) {
5916
+ let pointerCount = 0;
5917
+ for (const [index, step] of scenario.steps.entries()) {
5918
+ const framebufferAssertion = scenario.assert?.framebufferCoverage;
5919
+ if (target.name === "android" && framebufferAssertion !== void 0 && step.label === framebufferAssertion.window.startStep) {
5920
+ try {
5921
+ await target.driver.startScreenRecording?.();
5922
+ coverageRecordingStarted = true;
5923
+ await delay(100);
5924
+ } catch (error) {
5925
+ framebufferCoverage = unreadableCoverageObservation(error);
5926
+ }
5927
+ }
4209
5928
  if (step.pointerPosition !== void 0) {
4210
5929
  pointerButtons = step.pointerPosition.buttons ?? pointerButtons;
4211
5930
  await transport.call("input.pointer", {
@@ -4215,42 +5934,100 @@ async function runDevicePlaytest(config, target) {
4215
5934
  y: step.pointerPosition.y * scenario.viewport.height
4216
5935
  });
4217
5936
  }
4218
- const pressed = typeof step.press === "string" ? [step.press] : step.press ?? [];
4219
- for (const key of [...heldKeys]) {
4220
- if (!pressed.includes(key)) {
4221
- await transport.call("input.keyUp", { key });
4222
- heldKeys.delete(key);
4223
- }
5937
+ if (step.pointers !== void 0) {
5938
+ await target.driver.setPointers?.(step.pointers);
5939
+ pointerCount = step.pointers.length;
4224
5940
  }
4225
- for (const key of pressed) {
4226
- if (!heldKeys.has(key)) {
4227
- await transport.call("input.keyDown", { key });
4228
- heldKeys.add(key);
5941
+ const pressed = step.press;
5942
+ if (typeof pressed === "string") {
5943
+ if (!heldKeys.has(pressed)) {
5944
+ await transport.call("input.keyDown", { key: pressed });
5945
+ heldKeys.add(pressed);
5946
+ }
5947
+ } else if (pressed !== void 0) {
5948
+ for (const key of [...heldKeys]) {
5949
+ if (!pressed.includes(key)) {
5950
+ await transport.call("input.keyUp", { key });
5951
+ heldKeys.delete(key);
5952
+ }
5953
+ }
5954
+ for (const key of pressed) {
5955
+ if (!heldKeys.has(key)) {
5956
+ await transport.call("input.keyDown", { key });
5957
+ heldKeys.add(key);
5958
+ }
4229
5959
  }
4230
5960
  }
5961
+ const inputDriven = playtestStepDrivesMovement(
5962
+ step,
5963
+ heldKeys.size > 0 || pointerButtons !== 0 || pointerCount > 0
5964
+ );
5965
+ const movementBefore = capturesAnonymousMovement ? movementCursor : void 0;
4231
5966
  const frames = Math.max(
4232
5967
  1,
4233
5968
  playtestStepHoldTicks(step, 0) + playtestStepWaitTicks(step),
4234
5969
  (step.holdFrames ?? 0) + (step.waitFrames ?? 0)
4235
5970
  );
4236
- await bridge.advance(frames);
4237
- appendPosition(pathPositions, await bridge.sample(sampleRequest), pathEntity);
5971
+ if (coverageRecordingStarted) {
5972
+ for (let frame = 0; frame < frames; frame += 1) {
5973
+ await bridge.advance(1);
5974
+ await delay(100);
5975
+ }
5976
+ } else {
5977
+ await bridge.advance(frames);
5978
+ }
5979
+ const afterInput = await bridge.sample(sampleRequest);
5980
+ appendPosition(pathPositions, afterInput, pathEntity);
5981
+ if (movementBefore !== void 0) {
5982
+ movementSamples.push({ after: afterInput, before: movementBefore, inputDriven });
5983
+ }
5984
+ let afterStep = afterInput;
4238
5985
  if (step.label !== void 0) {
4239
- const snapshot = await bridge.sample(sampleRequest);
5986
+ const snapshot = await bridge.sample({ ...sampleRequest, label: step.label });
4240
5987
  const signals = bridge.description.capabilities.includes("runtime.events") ? await bridge.drainEvents() : [];
4241
5988
  labeledSamples.push({ label: step.label, signals, snapshot });
4242
5989
  }
4243
5990
  if (step.screenshot !== void 0) {
4244
5991
  await target.driver.screenshot(join(config.artifactDirectory, `${safePart2(step.screenshot)}.png`));
4245
5992
  }
4246
- if (step.release) {
4247
- for (const key of pressed) {
5993
+ if (step.release && pressed !== void 0) {
5994
+ const released = typeof pressed === "string" ? [pressed] : [...pressed];
5995
+ for (const key of released) {
4248
5996
  await transport.call("input.keyUp", { key });
4249
5997
  heldKeys.delete(key);
4250
5998
  }
4251
- if (pointerButtons !== 0) {
4252
- pointerButtons = 0;
4253
- await transport.call("input.pointer", { buttons: 0, type: "up", x: 0, y: 0 });
5999
+ if (index !== scenario.steps.length - 1) {
6000
+ await bridge.advance(1);
6001
+ if (capturesAnonymousMovement) afterStep = await bridge.sample(sampleRequest);
6002
+ }
6003
+ }
6004
+ if (step.pointerPosition?.buttons !== void 0 && step.release) {
6005
+ pointerButtons = 0;
6006
+ await transport.call("input.pointer", { buttons: 0, type: "up", x: 0, y: 0 });
6007
+ }
6008
+ if (step.pointers !== void 0 && step.release) {
6009
+ await target.driver.setPointers?.([]);
6010
+ pointerCount = 0;
6011
+ await bridge.advance(1);
6012
+ if (capturesAnonymousMovement) afterStep = await bridge.sample(sampleRequest);
6013
+ }
6014
+ if (movementBefore !== void 0 && afterInput !== void 0 && afterStep !== afterInput) {
6015
+ movementSamples.push({ after: afterStep, before: afterInput, inputDriven: false });
6016
+ }
6017
+ if (capturesAnonymousMovement) movementCursor = afterStep;
6018
+ if (coverageRecordingStarted && target.name === "android" && framebufferAssertion !== void 0 && step.label === framebufferAssertion.window.endStep) {
6019
+ try {
6020
+ await target.driver.stopScreenRecording?.(coverageVideoPath);
6021
+ coverageRecordingStarted = false;
6022
+ framebufferCoverage = await analyzeFramebufferCoverageRecording(
6023
+ coverageVideoPath,
6024
+ config.artifactDirectory,
6025
+ framebufferAssertion,
6026
+ "scenario-steps"
6027
+ );
6028
+ } catch (error) {
6029
+ coverageRecordingStarted = false;
6030
+ framebufferCoverage = unreadableCoverageObservation(error);
4254
6031
  }
4255
6032
  }
4256
6033
  }
@@ -4267,13 +6044,6 @@ async function runDevicePlaytest(config, target) {
4267
6044
  ), target.name);
4268
6045
  }
4269
6046
  const consoleEntries = await target.driver.captureConsole();
4270
- if (consoleEntries.some(({ type }) => type === "error" || type === "pageerror")) {
4271
- return failureReport2(config, scenario, playtestDiagnostic(
4272
- "TN_PLAYTEST_DEVICE_FAILED",
4273
- `${targetLabel(target.name)} logs contained a runtime error before assertions were evaluated.`,
4274
- `Inspect ${target.name === "android" ? "logcat" : "unified logs"}, fix the first native or JavaScript error, then rerun the same scenario.`
4275
- ), target.name);
4276
- }
4277
6047
  const report = buildReport(
4278
6048
  config,
4279
6049
  scenario,
@@ -4285,8 +6055,17 @@ async function runDevicePlaytest(config, target) {
4285
6055
  {},
4286
6056
  true,
4287
6057
  void 0,
4288
- labeledSamples
6058
+ labeledSamples,
6059
+ framebufferCoverage,
6060
+ void 0,
6061
+ void 0,
6062
+ movementSamples
4289
6063
  );
6064
+ await writeObservationArtifacts(config.artifactDirectory, scenario.artifacts, {
6065
+ console: consoleEntries,
6066
+ network: [],
6067
+ runtimeTrace: void 0
6068
+ });
4290
6069
  return { ...report, runtime: "native", target: target.name, url: endpoint };
4291
6070
  } catch (error) {
4292
6071
  if (error instanceof PlaytestBridgeError) {
@@ -4294,6 +6073,9 @@ async function runDevicePlaytest(config, target) {
4294
6073
  }
4295
6074
  throw error;
4296
6075
  } finally {
6076
+ if (target.name === "android" && scenario.steps.some((step) => step.pointers !== void 0)) {
6077
+ await target.driver.setPointers?.([]).catch(() => void 0);
6078
+ }
4297
6079
  await target.driver.stop().catch(() => void 0);
4298
6080
  await bridge?.close().catch(() => void 0);
4299
6081
  await transport.close().catch(() => void 0);
@@ -4314,6 +6096,14 @@ function isMailboxDriver(driver) {
4314
6096
  return typeof driver.readFile === "function" && typeof driver.removeFile === "function" && typeof driver.writeFile === "function";
4315
6097
  }
4316
6098
  function unsupportedAssertion(scenario, target) {
6099
+ const hasMultiPointerInput = scenario.steps.some((step) => step.pointers !== void 0);
6100
+ if (hasMultiPointerInput && target === "ios") {
6101
+ return unsupportedDiagnostic(
6102
+ "complete held-pointer input",
6103
+ "Run this scenario on --target browser or --target android; iOS multi-pointer injection is not implemented.",
6104
+ target
6105
+ );
6106
+ }
4317
6107
  if (scenario.assert?.diagnostics?.noNetworkErrors === true) {
4318
6108
  return unsupportedDiagnostic(
4319
6109
  "network assertions",
@@ -4335,6 +6125,13 @@ function unsupportedAssertion(scenario, target) {
4335
6125
  target
4336
6126
  );
4337
6127
  }
6128
+ if (scenario.assert?.framebufferCoverage !== void 0 && target === "ios") {
6129
+ return unsupportedDiagnostic(
6130
+ "framebuffer coverage recording",
6131
+ "Run this assertion on --target browser or --target android; the iOS transport has no per-frame recorder observer.",
6132
+ target
6133
+ );
6134
+ }
4338
6135
  return void 0;
4339
6136
  }
4340
6137
  function unsupportedDiagnostic(subject, fix, target) {
@@ -4346,9 +6143,12 @@ function unsupportedDiagnostic(subject, fix, target) {
4346
6143
  }
4347
6144
  function failureReport2(config, scenario, diagnostic, target) {
4348
6145
  const item = { ...diagnostic, suggestion: diagnostic.fix.instruction };
6146
+ const diagnosticsPolicy = resolveDiagnosticsPolicy(scenario.assert?.diagnostics);
4349
6147
  return {
4350
6148
  artifactDirectory: config.artifactDirectory,
6149
+ assertionResults: [failedDiagnosticsAssertion(diagnosticsPolicy)],
4351
6150
  diagnostics: [item],
6151
+ diagnosticsPolicy,
4352
6152
  distance: 0,
4353
6153
  entity: scenario.subject ?? "",
4354
6154
  expectMoved: false,
@@ -4385,13 +6185,15 @@ function setupRequest2(scenario) {
4385
6185
  };
4386
6186
  }
4387
6187
  function observedEntityIds2(scenario) {
4388
- return [...new Set([
6188
+ if (scenario.assert?.movement !== void 0 && scenario.assert.movement.entity === void 0 && scenario.subject === void 0) return void 0;
6189
+ const ids = [...new Set([
4389
6190
  scenario.subject,
4390
6191
  scenario.assert?.movement?.entity,
4391
6192
  scenario.assert?.camera?.entity,
4392
6193
  scenario.assert?.camera?.follows,
4393
6194
  ...(scenario.assert?.visibility ?? []).map(({ entity }) => entity)
4394
6195
  ].filter((value) => value !== void 0))];
6196
+ return ids.length > 0 ? ids : scenario.assert?.movement === void 0 ? [] : void 0;
4395
6197
  }
4396
6198
  function observedResourceIds2(scenario) {
4397
6199
  return [.../* @__PURE__ */ new Set([
@@ -4417,18 +6219,21 @@ function accumulatedPathLength2(positions) {
4417
6219
  function safePart2(value) {
4418
6220
  return value.replace(/[^A-Za-z0-9._-]+/g, "-");
4419
6221
  }
4420
-
4421
- // src/runner/browser.ts
4422
- var WEBGPU_BROWSER_ARGS = [
4423
- "--ozone-platform=x11",
4424
- "--enable-unsafe-webgpu",
4425
- "--disable-gpu-sandbox",
4426
- "--ignore-gpu-blocklist"
4427
- ];
4428
-
4429
- // src/runner/config.ts
6222
+ function unreadableCoverageObservation(error) {
6223
+ return {
6224
+ boundarySource: "scenario-steps",
6225
+ frameCount: 0,
6226
+ unreadableReason: error instanceof Error ? error.message : String(error),
6227
+ windowCompleted: false,
6228
+ windowStarted: false
6229
+ };
6230
+ }
6231
+ function delay(milliseconds) {
6232
+ return new Promise((resolve5) => setTimeout(resolve5, milliseconds));
6233
+ }
4430
6234
  var PLAYTEST_FLAGS = {
4431
6235
  "--adb": { default: "auto-discover", summary: "absolute adb executable path", takesValue: true },
6236
+ "--allow-software": { default: "false", summary: "accept a software WebGPU adapter as evidence", takesValue: false },
4432
6237
  "--activity": { default: ".MystralActivity", summary: "Android launch activity", takesValue: true },
4433
6238
  "--app": { default: "required for iOS", summary: "built iOS .app bundle", takesValue: true },
4434
6239
  "--artifacts": { default: "artifacts/playtest", summary: "artifact output directory", takesValue: true },
@@ -4510,6 +6315,7 @@ function parseStandalonePlaytestArgs(argv, cwd = process.cwd()) {
4510
6315
  const browserArgs = explicitBrowserArgs.length > 0 ? explicitBrowserArgs : browserRecipe === "webgpu" ? [...WEBGPU_BROWSER_ARGS] : [];
4511
6316
  return {
4512
6317
  ...flags.get("--adb")?.[0] === void 0 ? {} : { adbPath: flags.get("--adb")[0] },
6318
+ allowSoftwareAdapter: argv.includes("--allow-software"),
4513
6319
  android: {
4514
6320
  activity: flags.get("--activity")?.[0] ?? ".MystralActivity",
4515
6321
  packageName: flags.get("--package")?.[0] ?? "com.mystral.engine"
@@ -4612,14 +6418,14 @@ installThreePlaytestBridge({
4612
6418
  }
4613
6419
  return { created };
4614
6420
  }
4615
- var execFileAsync2 = promisify(execFile);
6421
+ var execFileAsync3 = promisify(execFile);
4616
6422
  var XcrunIosDriver = class {
4617
6423
  constructor(options, run) {
4618
6424
  this.options = options;
4619
6425
  const xcrun = options.xcrunPath ?? "xcrun";
4620
6426
  this.run = run ?? (async (args, commandOptions = {}) => {
4621
6427
  try {
4622
- const { stdout } = await execFileAsync2(xcrun, [...args], {
6428
+ const { stdout } = await execFileAsync3(xcrun, [...args], {
4623
6429
  encoding: "utf8",
4624
6430
  env: commandOptions.env ?? process.env,
4625
6431
  maxBuffer: 16 * 1024 * 1024
@@ -4682,7 +6488,7 @@ var XcrunIosDriver = class {
4682
6488
  if (this.pid === void 0) return false;
4683
6489
  try {
4684
6490
  if (this.options.transport === "simulator") {
4685
- await this.run(["simctl", "spawn", this.device(), "kill", "-0", this.pid]);
6491
+ process.kill(Number(this.pid), 0);
4686
6492
  } else {
4687
6493
  const output = await this.run(["devicectl", "device", "info", "processes", "--device", this.device()]);
4688
6494
  if (!new RegExp(`\\b${this.pid}\\b`, "u").test(output)) return false;
@@ -5078,4 +6884,4 @@ function recordToScenario(value, scenarioPath = "recording.json", oracleValue) {
5078
6884
  };
5079
6885
  }
5080
6886
 
5081
- export { ANDROID_TRANSPORT_CAPABILITIES, AdbAndroidDriver, DeviceBridgeTransport, DeviceMailboxTransport, PLAYTEST_FLAGS, PlaytestBridgeError, PlaytestCliUsageError, PlaywrightTransport, STANDALONE_PLAYTEST_OBSERVATION_FIELDS, XcrunIosDriver, androidMailboxPaths, buildReport, connectPlaytestBridge, connectPlaytestBridgeTransport, deviceMailboxPaths, discoverAdb, formatUsage, initStandalonePlaytest, parseLaunchedPid, parseStandalonePlaytestArgs, preflightDisplay, recordToScenario, requireAssertions, runAndroidPlaytest, runDevicePlaytest, runIosPlaytest, runStandalonePlaytest, validateDeviceEndpoint };
6887
+ export { ANDROID_TRANSPORT_CAPABILITIES, AdbAndroidDriver, DeviceBridgeTransport, DeviceMailboxTransport, PLAYTEST_FLAGS, PlaytestBridgeError, PlaytestCliUsageError, PlaywrightTransport, STANDALONE_PLAYTEST_OBSERVATION_FIELDS, XcrunIosDriver, androidMailboxPaths, androidTouchBatches, boundedTeardownStep, buildReport, captureVisualSurface, connectPlaytestBridge, connectPlaytestBridgeTransport, deviceMailboxPaths, discoverAdb, failedDiagnosticsAssertion, formatUsage, initStandalonePlaytest, isRuntimeReadout, openPageAndConnectBridge, pageLifecycleDiagnostic, parseAndroidConsole, parseLaunchedPid, parseStandalonePlaytestArgs, playtestStepDrivesMovement, preflightDisplay, recordToScenario, requireAssertions, rotatedTouchPosition, runAndroidPlaytest, runDevicePlaytest, runIosPlaytest, runStandalonePlaytest, validateDeviceEndpoint, writeCaptureProvenance, writeObservationArtifacts };