@threenative/playtest 0.3.13 → 0.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,6 +7,9 @@ npx @threenative/playtest playtests/movement.playtest.json \
7
7
  --url http://127.0.0.1:5173 --server-command "npm run dev"
8
8
  ```
9
9
 
10
+ Flags, exit codes and every assertion are in `docs/reference.md`; ticks, `holdTicks` and the
11
+ startup wait are in `docs/determinism.md`. Both ship in this package.
12
+
10
13
  Install the bridge from `@threenative/playtest/three` when semantic entity, camera,
11
14
  movement, or visibility assertions are required. Browser-only input, screenshot,
12
15
  DOM, console, network, and trace evidence does not require an adapter. Run
@@ -804,7 +804,7 @@ interface IPlaytestFramebufferCoverageObservation {
804
804
  windowStarted: boolean;
805
805
  }
806
806
 
807
- type PlaytestDiagnosticCode = "TN_PLAYTEST_ANDROID_LIFECYCLE_NOT_APPLIED" | "TN_PLAYTEST_ANDROID_LIFECYCLE_PHYSICS_UNOBSERVED" | "TN_PLAYTEST_ANDROID_LIFECYCLE_SESSION_CHANGED" | "TN_PLAYTEST_ANDROID_LIFECYCLE_UNOBSERVED" | "TN_PLAYTEST_BRIDGE_INCOMPATIBLE" | "TN_PLAYTEST_BRIDGE_CAPABILITY_UNKNOWN" | "TN_PLAYTEST_BRIDGE_MISSING" | "TN_PLAYTEST_BRIDGE_NOT_READY" | "TN_PLAYTEST_CAPTURE_PROVENANCE_MISSING" | "TN_PLAYTEST_CAPABILITY_MISSING" | "TN_PLAYTEST_DEVICE_FAILED" | "TN_PLAYTEST_HOST_EXITED" | "TN_PLAYTEST_MAILBOX_POLL_STALLED" | "TN_PLAYTEST_OBSERVATION_UNAVAILABLE" | "TN_PLAYTEST_OPERATION_TIMEOUT" | "TN_PLAYTEST_PAGE_CLOSED" | "TN_PLAYTEST_PAGE_CRASHED" | "TN_PLAYTEST_PAGE_NAVIGATED" | "TN_PLAYTEST_PAYLOAD_TOO_LARGE" | "TN_PLAYTEST_SERVER_FAILED" | "TN_PLAYTEST_SETUP_UNAPPLIED" | "TN_PLAYTEST_START_TICK_INVALID" | "TN_PLAYTEST_STARTUP_ABORTED" | "TN_PLAYTEST_STARTUP_HOST_EXITED" | "TN_PLAYTEST_STARTUP_NOT_READY" | "TN_PLAYTEST_UNSUPPORTED_ON_TARGET";
807
+ type PlaytestDiagnosticCode = "TN_PLAYTEST_ANDROID_LIFECYCLE_NOT_APPLIED" | "TN_PLAYTEST_ANDROID_LIFECYCLE_PHYSICS_UNOBSERVED" | "TN_PLAYTEST_ANDROID_LIFECYCLE_SESSION_CHANGED" | "TN_PLAYTEST_ANDROID_LIFECYCLE_UNOBSERVED" | "TN_PLAYTEST_BRIDGE_INCOMPATIBLE" | "TN_PLAYTEST_BRIDGE_CAPABILITY_UNKNOWN" | "TN_PLAYTEST_BRIDGE_MISSING" | "TN_PLAYTEST_BRIDGE_NOT_READY" | "TN_PLAYTEST_CAPTURE_PROVENANCE_MISSING" | "TN_PLAYTEST_CHECK_FAILED" | "TN_PLAYTEST_CAPABILITY_MISSING" | "TN_PLAYTEST_DEVICE_FAILED" | "TN_PLAYTEST_HOST_EXITED" | "TN_PLAYTEST_MAILBOX_POLL_STALLED" | "TN_PLAYTEST_OBSERVATION_UNAVAILABLE" | "TN_PLAYTEST_OPERATION_TIMEOUT" | "TN_PLAYTEST_PAGE_CLOSED" | "TN_PLAYTEST_PAGE_CRASHED" | "TN_PLAYTEST_PAGE_NAVIGATED" | "TN_PLAYTEST_PAYLOAD_TOO_LARGE" | "TN_PLAYTEST_SERVER_FAILED" | "TN_PLAYTEST_SETUP_UNAPPLIED" | "TN_PLAYTEST_START_TICK_INVALID" | "TN_PLAYTEST_STARTUP_ABORTED" | "TN_PLAYTEST_STARTUP_HOST_EXITED" | "TN_PLAYTEST_STARTUP_NOT_READY" | "TN_PLAYTEST_UNSUPPORTED_ON_TARGET";
808
808
  interface IPlaytestProtocolDiagnostic {
809
809
  capability?: string;
810
810
  code: PlaytestDiagnosticCode;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { c as IPlaytestStep, d as IPlaytestScenarioDiagnostic, e as IPlaytestScenario } from './schema-base-D8wNuOLE.js';
2
2
  export { f as IPlaytestArtifactRequest, g as IPlaytestFramebufferCoverageAssertion, h as IPlaytestGamepad, i as IPlaytestMedia, j as IPlaytestPathAssertion, k as IPlaytestPerformanceAssertion, l as IPlaytestPointer, m as IPlaytestRenderChainAssertion, n as IPlaytestResourceWait, o as IPlaytestSignalAssertion, p as IPlaytestStartupAssertion, a as IPlaytestToneAssertion, q as IPlaytestToneObservation, r as IPlaytestVisualAssertion, s as IPlaytestVisualElementRegion, t as IPlaytestVisualRegion, u as IPlaytestVisualRegionBounds, v as IPlaytestVisualRegionTarget, w as IPlaytestWheel, x as IPlaytestWorldRuntimeAssertion, I as IToneMetrics } from './schema-base-D8wNuOLE.js';
3
- import { I as IPlaytestReport, a as IPlaytestAssertionResult, b as IPlaytestDiagnostic } from './diagnostics-0g-Uyvds.js';
4
- export { D as DEVICE_METRICS_CADENCE_MS, c as DEVICE_METRICS_MAX_SAMPLES, d as DeviceMetricsError, e as DeviceMetricsRecorder, H as HOT_START_TEMPERATURE_C, f as IPlaytestCaptureProvenance, g as IPlaytestDeviceBattery, h as IPlaytestDeviceMetricsObservation, i as IPlaytestDeviceMetricsSample, j as IPlaytestDeviceMetricsVerdict, k as IPlaytestDeviceThermal, l as IPlaytestDiagnosticsPolicy, m as IPlaytestFootSlipObservation, n as IPlaytestFramebufferCoverageObservation, o as IPlaytestObservations, p as IPlaytestProtocolDiagnostic, q as IPlaytestSetupApplication, r as IPlaytestSetupRecord, s as IPlaytestTrivialityOptOut, t as IPlaytestVisualElementRegionObservation, P as PlaytestDeviceMeasurement, u as PlaytestDevicePowerRails, v as PlaytestVec3, w as parseDeviceBattery, x as parseDeviceCurrent, y as parseDevicePowerRails, z as parseDeviceThermal, A as playtestDiagnostic, B as resolveDiagnosticsPolicy, C as summarizeDeviceMetrics } from './diagnostics-0g-Uyvds.js';
3
+ import { I as IPlaytestReport, a as IPlaytestAssertionResult, b as IPlaytestDiagnostic } from './diagnostics-BDWgOKJj.js';
4
+ export { D as DEVICE_METRICS_CADENCE_MS, c as DEVICE_METRICS_MAX_SAMPLES, d as DeviceMetricsError, e as DeviceMetricsRecorder, H as HOT_START_TEMPERATURE_C, f as IPlaytestCaptureProvenance, g as IPlaytestDeviceBattery, h as IPlaytestDeviceMetricsObservation, i as IPlaytestDeviceMetricsSample, j as IPlaytestDeviceMetricsVerdict, k as IPlaytestDeviceThermal, l as IPlaytestDiagnosticsPolicy, m as IPlaytestFootSlipObservation, n as IPlaytestFramebufferCoverageObservation, o as IPlaytestObservations, p as IPlaytestProtocolDiagnostic, q as IPlaytestSetupApplication, r as IPlaytestSetupRecord, s as IPlaytestTrivialityOptOut, t as IPlaytestVisualElementRegionObservation, P as PlaytestDeviceMeasurement, u as PlaytestDevicePowerRails, v as PlaytestVec3, w as parseDeviceBattery, x as parseDeviceCurrent, y as parseDevicePowerRails, z as parseDeviceThermal, A as playtestDiagnostic, B as resolveDiagnosticsPolicy, C as summarizeDeviceMetrics } from './diagnostics-BDWgOKJj.js';
5
5
  export { IPlaytestBridgeDescription, IPlaytestBridgeReady, IPlaytestBridgeV1, IPlaytestCameraObservation, IPlaytestContactObservation, IPlaytestDeviceRequest, IPlaytestDeviceResponse, IPlaytestFogObservation, IPlaytestFramePassSample, IPlaytestGameplayObservation, IPlaytestLightObservation, IPlaytestObservationSnapshot, IPlaytestPerformanceObservation, IPlaytestRenderChainObservation, IPlaytestRuntimeDiagnosticsSample, IPlaytestSampleRequest, IPlaytestSceneObservation, IPlaytestSetupConfirmation, IPlaytestSetupRequest, IPlaytestSightLineObservation, IPlaytestStartupObservation, IPlaytestStartupTimeline, IPlaytestStrideObservation, IPlaytestWorldObservation, IPlaytestWorldRuntimeObservation, JsonValue, PLAYTEST_ADVANCE_TICK_BUDGET_MS, PLAYTEST_BRIDGE_GLOBAL, PLAYTEST_FRAME_PASS_KINDS, PLAYTEST_FROZEN_MARKER, PLAYTEST_PROTOCOL_LIMITS, PLAYTEST_PROTOCOL_VERSION, PLAYTEST_STARTUP_COMPILE_BUDGET_MS, PLAYTEST_STARTUP_READY_TIMEOUT_MS, PlaytestFramePassKind, assertJsonSafe, jsonByteLength } from './protocol.js';
6
6
 
7
7
  type PlaytestLane = "browser" | "android" | "desktop" | "ios";
@@ -1,5 +1,6 @@
1
1
  declare const CONSOLE_MARKER: {
2
2
  readonly bridgeCensus: "TN_BRIDGE_CENSUS";
3
+ readonly firstFrame: "TN_FIRST_FRAME";
3
4
  readonly frameBudget: "TN_FRAME_BUDGET";
4
5
  readonly frameHitch: "TN_FRAME_HITCH";
5
6
  readonly hostGap: "TN_HOST_GAP";
package/dist/protocol.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // src/generated/console-markers.ts
3
3
  var CONSOLE_MARKER = {
4
4
  bridgeCensus: "TN_BRIDGE_CENSUS",
5
+ firstFrame: "TN_FIRST_FRAME",
5
6
  frameBudget: "TN_FRAME_BUDGET",
6
7
  frameHitch: "TN_FRAME_HITCH",
7
8
  hostGap: "TN_HOST_GAP",
@@ -1,8 +1,8 @@
1
- import { I as IStandalonePlaytestConfig, a as IStandalonePlaytestReport } from '../shared-CRg0jlDU.js';
1
+ import { I as IStandalonePlaytestConfig, a as IStandalonePlaytestReport } from '../shared-C6k3MGh2.js';
2
2
  import '../schema-base-D8wNuOLE.js';
3
3
  import '../protocol.js';
4
4
  import 'playwright';
5
- import '../diagnostics-0g-Uyvds.js';
5
+ import '../diagnostics-BDWgOKJj.js';
6
6
 
7
7
  interface IRunnerDiagnostic {
8
8
  code: string;
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { PNG } from 'pngjs';
3
- import { existsSync, realpathSync, createWriteStream, readdirSync, readFileSync, constants as constants$1, rmSync } from 'fs';
4
- import { execFile, spawn, execFileSync, spawnSync } from 'child_process';
3
+ import { existsSync, realpathSync, readFileSync, createWriteStream, readdirSync, constants as constants$1, rmSync } from 'fs';
4
+ import { execFile, spawnSync, spawn, execFileSync } from 'child_process';
5
5
  import path, { resolve, dirname, join, basename, extname, isAbsolute, relative } from 'path';
6
6
  import { readFile, access, mkdir, writeFile, stat, mkdtemp, readdir, rm, unlink, rename, open, rmdir, copyFile } from 'fs/promises';
7
7
  import { fileURLToPath } from 'url';
@@ -291,6 +291,25 @@ var init_browser = __esm({
291
291
  }
292
292
  });
293
293
 
294
+ // src/diagnostics.ts
295
+ function playtestDiagnostic(code, message, instruction, details = {}) {
296
+ return {
297
+ ...details.capability === void 0 ? {} : { capability: details.capability },
298
+ code,
299
+ fix: {
300
+ instruction,
301
+ ...details.nextCommand === void 0 ? {} : { nextCommand: details.nextCommand }
302
+ },
303
+ message,
304
+ ...details.path === void 0 ? {} : { path: details.path },
305
+ severity: "error"
306
+ };
307
+ }
308
+ var init_diagnostics = __esm({
309
+ "src/diagnostics.ts"() {
310
+ }
311
+ });
312
+
294
313
  // src/scenario/errors.ts
295
314
  function invalidScenario(scenarioPath, message) {
296
315
  return new PlaytestScenarioError({
@@ -594,6 +613,7 @@ var init_console_markers = __esm({
594
613
  "src/generated/console-markers.ts"() {
595
614
  CONSOLE_MARKER = {
596
615
  bridgeCensus: "TN_BRIDGE_CENSUS",
616
+ firstFrame: "TN_FIRST_FRAME",
597
617
  frameBudget: "TN_FRAME_BUDGET",
598
618
  frameHitch: "TN_FRAME_HITCH",
599
619
  hostGap: "TN_HOST_GAP",
@@ -10391,25 +10411,6 @@ var init_capabilities = __esm({
10391
10411
  }
10392
10412
  });
10393
10413
 
10394
- // src/diagnostics.ts
10395
- function playtestDiagnostic(code, message, instruction, details = {}) {
10396
- return {
10397
- ...details.capability === void 0 ? {} : { capability: details.capability },
10398
- code,
10399
- fix: {
10400
- instruction,
10401
- ...details.nextCommand === void 0 ? {} : { nextCommand: details.nextCommand }
10402
- },
10403
- message,
10404
- ...details.path === void 0 ? {} : { path: details.path },
10405
- severity: "error"
10406
- };
10407
- }
10408
- var init_diagnostics = __esm({
10409
- "src/diagnostics.ts"() {
10410
- }
10411
- });
10412
-
10413
10414
  // src/index.ts
10414
10415
  var init_index = __esm({
10415
10416
  "src/index.ts"() {
@@ -11062,9 +11063,10 @@ var PLAYTEST_FLAGS = {
11062
11063
  "--artifact": { default: "none (browser and android: with --build-report)", summary: "the built artifact this run exercises, hashed to prove the build report describes it", takesValue: true },
11063
11064
  "--artifacts": { default: "artifacts/playtest", summary: "artifact output directory", takesValue: true },
11064
11065
  "--build-report": { default: "none", summary: "the <artifact>.build-report.json threenative build published; its performanceBudget bounds every scenario, and a stale or foreign report refuses the run", takesValue: true },
11066
+ "--skip-check": { default: "false", summary: "skip an installed project's typecheck and lint scripts, which otherwise run first and fail the run (reported as TN_PLAYTEST_CHECK_SKIPPED)", takesValue: false },
11065
11067
  "--no-screenshots": { default: "false", summary: "skip the before/after artifact frames; scenarios that assert on a frame still capture one", takesValue: false },
11066
11068
  "--browser-arg": { allowDashValue: true, default: "none (repeatable)", repeatable: true, summary: "one additional Chromium argument", takesValue: true },
11067
- "--browser-recipe": { default: "none", summary: "named browser recipe (webgpu)", takesValue: true },
11069
+ "--browser-recipe": { default: "none", summary: "named browser recipe (webgpu, which also launches headed)", takesValue: true },
11068
11070
  "--cpu-prof": { default: "none", summary: "write a Chrome DevTools .cpuprofile for this run (browser and desktop targets)", takesValue: true },
11069
11071
  "--bundle-id": { default: "dev.threenative.runtime", summary: "iOS application bundle identifier", takesValue: true },
11070
11072
  "--device": { default: "platform default", summary: "Android serial or iOS device identifier", takesValue: true },
@@ -11313,7 +11315,10 @@ function parseStandalonePlaytestArgs(argv, cwd = process.cwd()) {
11313
11315
  }
11314
11316
  },
11315
11317
  endpoint: flags.get("--endpoint")?.[0] ?? "http://127.0.0.1:41777/playtest",
11316
- headless: !argv.includes("--headed"),
11318
+ // A WebGPU run is headed: headless Chromium on a GPU-less Linux host serves WebGPU from SwiftShader
11319
+ // and cannot create the canvas swap-chain image, so the first present destroys the device on any
11320
+ // engine. Headed, the runner's private Xvfb holds the window and SwiftShader presents.
11321
+ headless: !argv.includes("--headed") && browserRecipe !== "webgpu",
11317
11322
  ios: {
11318
11323
  ...appPath === void 0 ? {} : { appPath: resolve(projectPath, appPath) },
11319
11324
  bundleId: flags.get("--bundle-id")?.[0] ?? "dev.threenative.runtime",
@@ -11467,6 +11472,36 @@ async function toneCommand(paths) {
11467
11472
  return 0;
11468
11473
  }
11469
11474
 
11475
+ // src/runner/projectCheck.ts
11476
+ init_diagnostics();
11477
+ var CHECK_SCRIPTS = ["typecheck", "lint"];
11478
+ function insideWorkspace(projectPath) {
11479
+ for (let directory = projectPath; ; directory = dirname(directory)) {
11480
+ if (existsSync(join(directory, "pnpm-workspace.yaml"))) return true;
11481
+ if (dirname(directory) === directory) return false;
11482
+ }
11483
+ }
11484
+ function runProjectCheck(projectPath) {
11485
+ if (insideWorkspace(projectPath)) return void 0;
11486
+ const manifestPath = join(projectPath, "package.json");
11487
+ if (!existsSync(manifestPath)) return void 0;
11488
+ const scripts = JSON.parse(readFileSync(manifestPath, "utf8")).scripts ?? {};
11489
+ const manager = existsSync(join(projectPath, "pnpm-lock.yaml")) ? "pnpm" : "npm";
11490
+ for (const script of CHECK_SCRIPTS) {
11491
+ if (scripts[script] === void 0) continue;
11492
+ const run2 = spawnSync(manager, ["run", "--silent", script], { cwd: projectPath, encoding: "utf8" });
11493
+ if (run2.status === 0) continue;
11494
+ const output = `${run2.stdout ?? ""}${run2.stderr ?? ""}${run2.error === void 0 ? "" : String(run2.error)}`.trim();
11495
+ return playtestDiagnostic(
11496
+ "TN_PLAYTEST_CHECK_FAILED",
11497
+ `\`${manager} run ${script}\` failed (exit ${run2.status ?? "none"}), so no scenario ran:
11498
+ ${output.slice(-4e3)}`,
11499
+ `Fix what \`${manager} run ${script}\` reports, then rerun. \`--skip-check\` skips this check and says so.`
11500
+ );
11501
+ }
11502
+ return void 0;
11503
+ }
11504
+
11470
11505
  // src/runner/cli.ts
11471
11506
  init_scenario();
11472
11507
 
@@ -16713,6 +16748,7 @@ async function readCaptureProvenance(page, config, scenario) {
16713
16748
  let rendererKind;
16714
16749
  if (engine.includes("webgpu")) rendererKind = "webgpu";
16715
16750
  else if (engine.includes("webgl")) rendererKind = "webgl";
16751
+ else if (engine.startsWith("three.js")) rendererKind = "webgl";
16716
16752
  else if (adapter !== null && canvas !== null) {
16717
16753
  try {
16718
16754
  if (canvas.getContext("webgpu") !== null) rendererKind = "webgpu";
@@ -16721,8 +16757,15 @@ async function readCaptureProvenance(page, config, scenario) {
16721
16757
  }
16722
16758
  let webglAdapterInfo;
16723
16759
  if (rendererKind === void 0 || rendererKind === "webgl") {
16760
+ const contextOf = (target) => {
16761
+ try {
16762
+ return target?.getContext("webgl2") ?? target?.getContext("webgl");
16763
+ } catch {
16764
+ return void 0;
16765
+ }
16766
+ };
16724
16767
  try {
16725
- const context = canvas?.getContext("webgl2") ?? canvas?.getContext("webgl");
16768
+ const context = contextOf(canvas) ?? (rendererKind === "webgl" ? contextOf(document.createElement("canvas")) : void 0);
16726
16769
  if (context !== null && context !== void 0) {
16727
16770
  rendererKind = "webgl";
16728
16771
  const debugInfo = context.getExtension("WEBGL_debug_renderer_info");
@@ -22733,6 +22776,18 @@ async function main(argv = process.argv.slice(2)) {
22733
22776
  }
22734
22777
  config = await resolveBuildReport(parseStandalonePlaytestArgs(argv));
22735
22778
  assertCpuProfileTargetSupported(config.target ?? "browser", config.cpuProfilePath);
22779
+ if (argv.includes("--skip-check")) {
22780
+ process.stderr.write(`${JSON.stringify({ diagnostics: [{ code: "TN_PLAYTEST_CHECK_SKIPPED", message: "--skip-check: the project's typecheck and lint did not run before these scenarios.", severity: "warning" }] })}
22781
+ `);
22782
+ } else {
22783
+ const failed = runProjectCheck(config.projectPath);
22784
+ if (failed !== void 0) {
22785
+ process.stderr.write(`${JSON.stringify({ diagnostics: [failed], pass: false }, null, 2)}
22786
+ `);
22787
+ process.exitCode = 1;
22788
+ return 1;
22789
+ }
22790
+ }
22736
22791
  const scenarioPaths = config.scenarioPaths ?? [config.scenarioPath];
22737
22792
  const reports = config.target === "browser" ? config.device === void 0 ? await runStandalonePlaytests(config) : await runAndroidBrowserPlaytests(config) : await runDevicePlaytests(config, scenarioPaths);
22738
22793
  const output = reports.length === 1 ? reports[0] : { pass: reports.every(({ pass }) => pass), reports };
@@ -1,10 +1,10 @@
1
1
  import { IPlaytestSetupRequest, JsonValue, IPlaytestBridgeDescription, IPlaytestBridgeReady, IPlaytestSampleRequest, IPlaytestObservationSnapshot } from '../protocol.js';
2
2
  import { e as IPlaytestScenario, f as IPlaytestArtifactRequest, l as IPlaytestPointer } from '../schema-base-D8wNuOLE.js';
3
- import { q as IPlaytestSetupApplication, p as IPlaytestProtocolDiagnostic, o as IPlaytestObservations, n as IPlaytestFramebufferCoverageObservation, f as IPlaytestCaptureProvenance, h as IPlaytestDeviceMetricsObservation, b as IPlaytestDiagnostic, E as IAndroidDriver, F as IAndroidAppState, G as IAndroidPointer, J as IAndroidPointerInjection } from '../diagnostics-0g-Uyvds.js';
4
- export { K as AdbAndroidDriver, L as IAndroidDriverOptions, M as IAndroidLifecycleOperation, N as IAndroidTouchViewport, O as IPlaytestDeviceLifecycleObservation, Q as IPlaytestDeviceLifecyclePhase, R as IPlaytestDeviceLifecyclePhysics, S as IPlaytestDeviceLifecycleSteps, T as androidTouchBatches, U as discoverAdb, V as keyboardIsShown, W as parseAndroidConsole, X as parseAndroidTouchViewport, Y as rotatedTouchPosition, Z as tapCommand, _ as touchPositionForViewport, $ as touchRotationFromWindowDump, a0 as viewportPresentationCommands, a1 as viewportPresentationObserved, a2 as viewportRestoreCommands } from '../diagnostics-0g-Uyvds.js';
3
+ import { q as IPlaytestSetupApplication, p as IPlaytestProtocolDiagnostic, o as IPlaytestObservations, n as IPlaytestFramebufferCoverageObservation, f as IPlaytestCaptureProvenance, h as IPlaytestDeviceMetricsObservation, b as IPlaytestDiagnostic, E as IAndroidDriver, F as IAndroidAppState, G as IAndroidPointer, J as IAndroidPointerInjection } from '../diagnostics-BDWgOKJj.js';
4
+ export { K as AdbAndroidDriver, L as IAndroidDriverOptions, M as IAndroidLifecycleOperation, N as IAndroidTouchViewport, O as IPlaytestDeviceLifecycleObservation, Q as IPlaytestDeviceLifecyclePhase, R as IPlaytestDeviceLifecyclePhysics, S as IPlaytestDeviceLifecycleSteps, T as androidTouchBatches, U as discoverAdb, V as keyboardIsShown, W as parseAndroidConsole, X as parseAndroidTouchViewport, Y as rotatedTouchPosition, Z as tapCommand, _ as touchPositionForViewport, $ as touchRotationFromWindowDump, a0 as viewportPresentationCommands, a1 as viewportPresentationObserved, a2 as viewportRestoreCommands } from '../diagnostics-BDWgOKJj.js';
5
5
  import { Page } from 'playwright';
6
- import { I as IStandalonePlaytestConfig, b as IRunnerConsoleEntry, c as ILabeledPlaytestSample, d as IMovementSampleInterval, a as IStandalonePlaytestReport } from '../shared-CRg0jlDU.js';
7
- export { e as IPlaytestFlagHelp, f as IPlaytestServerConfig, g as IRunStepSamples, M as ManagedServerError, P as PLAYTEST_FLAGS, h as PlaytestCliUsageError, i as advanceFixedStep, j as captureVisualSurface, k as failedDiagnosticsAssertion, l as formatUsage, p as parseStandalonePlaytestArgs, m as playtestStepDrivesMovement, w as withScenarioClock } from '../shared-CRg0jlDU.js';
6
+ import { I as IStandalonePlaytestConfig, b as IRunnerConsoleEntry, c as ILabeledPlaytestSample, d as IMovementSampleInterval, a as IStandalonePlaytestReport } from '../shared-C6k3MGh2.js';
7
+ export { e as IPlaytestFlagHelp, f as IPlaytestServerConfig, g as IRunStepSamples, M as ManagedServerError, P as PLAYTEST_FLAGS, h as PlaytestCliUsageError, i as advanceFixedStep, j as captureVisualSurface, k as failedDiagnosticsAssertion, l as formatUsage, p as parseStandalonePlaytestArgs, m as playtestStepDrivesMovement, w as withScenarioClock } from '../shared-C6k3MGh2.js';
8
8
  import { ChildProcess } from 'node:child_process';
9
9
 
10
10
  /** The only seam between assertion orchestration and an application bridge. */
@@ -11114,9 +11114,10 @@ var PLAYTEST_FLAGS = {
11114
11114
  "--artifact": { default: "none (browser and android: with --build-report)", summary: "the built artifact this run exercises, hashed to prove the build report describes it", takesValue: true },
11115
11115
  "--artifacts": { default: "artifacts/playtest", summary: "artifact output directory", takesValue: true },
11116
11116
  "--build-report": { default: "none", summary: "the <artifact>.build-report.json threenative build published; its performanceBudget bounds every scenario, and a stale or foreign report refuses the run", takesValue: true },
11117
+ "--skip-check": { default: "false", summary: "skip an installed project's typecheck and lint scripts, which otherwise run first and fail the run (reported as TN_PLAYTEST_CHECK_SKIPPED)", takesValue: false },
11117
11118
  "--no-screenshots": { default: "false", summary: "skip the before/after artifact frames; scenarios that assert on a frame still capture one", takesValue: false },
11118
11119
  "--browser-arg": { allowDashValue: true, default: "none (repeatable)", repeatable: true, summary: "one additional Chromium argument", takesValue: true },
11119
- "--browser-recipe": { default: "none", summary: "named browser recipe (webgpu)", takesValue: true },
11120
+ "--browser-recipe": { default: "none", summary: "named browser recipe (webgpu, which also launches headed)", takesValue: true },
11120
11121
  "--cpu-prof": { default: "none", summary: "write a Chrome DevTools .cpuprofile for this run (browser and desktop targets)", takesValue: true },
11121
11122
  "--bundle-id": { default: "dev.threenative.runtime", summary: "iOS application bundle identifier", takesValue: true },
11122
11123
  "--device": { default: "platform default", summary: "Android serial or iOS device identifier", takesValue: true },
@@ -11365,7 +11366,10 @@ function parseStandalonePlaytestArgs(argv, cwd = process.cwd()) {
11365
11366
  }
11366
11367
  },
11367
11368
  endpoint: flags.get("--endpoint")?.[0] ?? "http://127.0.0.1:41777/playtest",
11368
- headless: !argv.includes("--headed"),
11369
+ // A WebGPU run is headed: headless Chromium on a GPU-less Linux host serves WebGPU from SwiftShader
11370
+ // and cannot create the canvas swap-chain image, so the first present destroys the device on any
11371
+ // engine. Headed, the runner's private Xvfb holds the window and SwiftShader presents.
11372
+ headless: !argv.includes("--headed") && browserRecipe !== "webgpu",
11369
11373
  ios: {
11370
11374
  ...appPath === void 0 ? {} : { appPath: resolve(projectPath, appPath) },
11371
11375
  bundleId: flags.get("--bundle-id")?.[0] ?? "dev.threenative.runtime",
@@ -14236,6 +14240,7 @@ async function readCaptureProvenance(page, config, scenario) {
14236
14240
  let rendererKind;
14237
14241
  if (engine.includes("webgpu")) rendererKind = "webgpu";
14238
14242
  else if (engine.includes("webgl")) rendererKind = "webgl";
14243
+ else if (engine.startsWith("three.js")) rendererKind = "webgl";
14239
14244
  else if (adapter !== null && canvas !== null) {
14240
14245
  try {
14241
14246
  if (canvas.getContext("webgpu") !== null) rendererKind = "webgpu";
@@ -14244,8 +14249,15 @@ async function readCaptureProvenance(page, config, scenario) {
14244
14249
  }
14245
14250
  let webglAdapterInfo;
14246
14251
  if (rendererKind === void 0 || rendererKind === "webgl") {
14252
+ const contextOf = (target) => {
14253
+ try {
14254
+ return target?.getContext("webgl2") ?? target?.getContext("webgl");
14255
+ } catch {
14256
+ return void 0;
14257
+ }
14258
+ };
14247
14259
  try {
14248
- const context = canvas?.getContext("webgl2") ?? canvas?.getContext("webgl");
14260
+ const context = contextOf(canvas) ?? (rendererKind === "webgl" ? contextOf(document.createElement("canvas")) : void 0);
14249
14261
  if (context !== null && context !== void 0) {
14250
14262
  rendererKind = "webgl";
14251
14263
  const debugInfo = context.getExtension("WEBGL_debug_renderer_info");
@@ -1,7 +1,7 @@
1
1
  import { e as IPlaytestScenario, k as IPlaytestPerformanceAssertion } from './schema-base-D8wNuOLE.js';
2
2
  import { IPlaytestObservationSnapshot } from './protocol.js';
3
3
  import { Page } from 'playwright';
4
- import { I as IPlaytestReport, p as IPlaytestProtocolDiagnostic, l as IPlaytestDiagnosticsPolicy, a as IPlaytestAssertionResult } from './diagnostics-0g-Uyvds.js';
4
+ import { I as IPlaytestReport, p as IPlaytestProtocolDiagnostic, l as IPlaytestDiagnosticsPolicy, a as IPlaytestAssertionResult } from './diagnostics-BDWgOKJj.js';
5
5
 
6
6
  /** Capture the largest rendered canvas bounds without waiting for locator screenshot stability. */
7
7
  declare function captureVisualSurface(page: Page, artifactPath?: string): Promise<Buffer | undefined>;
@@ -228,6 +228,11 @@ declare const PLAYTEST_FLAGS: {
228
228
  readonly summary: "the <artifact>.build-report.json threenative build published; its performanceBudget bounds every scenario, and a stale or foreign report refuses the run";
229
229
  readonly takesValue: true;
230
230
  };
231
+ readonly "--skip-check": {
232
+ readonly default: "false";
233
+ readonly summary: "skip an installed project's typecheck and lint scripts, which otherwise run first and fail the run (reported as TN_PLAYTEST_CHECK_SKIPPED)";
234
+ readonly takesValue: false;
235
+ };
231
236
  readonly "--no-screenshots": {
232
237
  readonly default: "false";
233
238
  readonly summary: "skip the before/after artifact frames; scenarios that assert on a frame still capture one";
@@ -242,7 +247,7 @@ declare const PLAYTEST_FLAGS: {
242
247
  };
243
248
  readonly "--browser-recipe": {
244
249
  readonly default: "none";
245
- readonly summary: "named browser recipe (webgpu)";
250
+ readonly summary: "named browser recipe (webgpu, which also launches headed)";
246
251
  readonly takesValue: true;
247
252
  };
248
253
  readonly "--cpu-prof": {
@@ -0,0 +1,112 @@
1
+ # playtest determinism and startup readiness
2
+
3
+ Why scenario timing is ticks rather than milliseconds, and what the runner waits for
4
+ before it observes a game. Moved out of
5
+ [`@threenative/playtest/AGENTS.md`](../AGENTS.md) verbatim; every paragraph below is the text
6
+ AGENTS.md used to carry.
7
+
8
+ ## Scenario steps count fixed-step ticks, not milliseconds
9
+
10
+ Scenario steps count fixed-step ticks, not milliseconds — use `holdTicks`, `waitTicks`. The
11
+ deprecated `holdFrames` and `waitFrames` aliases remain accepted for compatibility and are
12
+ treated as ticks when the bridge exposes `runtime.fixedStep`; `warmupFrames` remains a genuine
13
+ requestAnimationFrame warmup. Never introduce a wall-clock sleep or a millisecond-based step
14
+ into scenario semantics.
15
+
16
+ `"reducedMotion": "reduce"` (web target only) opens the page with `prefers-reduced-motion: reduce`
17
+ emulated before navigation, so a game that suppresses flashes or motion for it can prove so.
18
+
19
+ ## Ticks are not the clock a launch runs on
20
+
21
+ **Ticks are not the clock a launch runs on.** A run advances ticks as fast as the machine allows,
22
+ so a whole scenario can complete during a launch that has not finished — and everything the
23
+ application gates on startup (compute dispatch, the first world present) then never happens inside
24
+ the run. `starter-look` read `flagSteps` 0 before and 0 after because the cloth had never been
25
+ dispatched; twelve starter scenarios photographed the loading screen and reported
26
+ `TN_CAPTURE_BLANK`. Both depended only on how long boot took.
27
+
28
+ So after `warmupFrames` and before the baseline observation, the runner waits for the application
29
+ to say its world is safe to observe: a bridge that advertises **`runtime.startup`** reports
30
+ `{ phase, progress }` from `ready()` (core's `playtest()` plugin publishes `ctx.startup`), and the
31
+ runner holds — pumping frames on browser, ticks on device — until `phase` is `"ready"`. Bounded by
32
+ `PLAYTEST_STARTUP_READY_TIMEOUT_MS`; a game that never gets there fails
33
+ `TN_PLAYTEST_STARTUP_NOT_READY` rather than being observed mid-load. An application that reports no
34
+ startup at all — a plain Three.js page — is never waited on, and advertising the capability without
35
+ reporting it is malformed and throws.
36
+
37
+ Readiness means two things, and the wait always insists on both. Core reaches `"ready"` after
38
+ first-use compilation settles **and** a frame window — five sustained in-budget frames, or a
39
+ bounded expiry of `STARTUP_STABLE_WINDOW_MS` (10s) when a CPU rasteriser can never meet them.
40
+ Observing at bare compile settlement is not enough: a game that builds its world on `whenReady()`
41
+ (the puzzle's crate pile is one) has not run yet, and the run then asserts against a half-built
42
+ world. So the software lane waits for `"ready"` like any other — at most 10s more per scenario —
43
+ and the declaration (`--allow-software` / `TN_PLAYTEST_ALLOW_SOFTWARE=1`) only **labels** the
44
+ result: `startup.rule` is `"compile-settled"`, because a CPU rasteriser reached readiness on the
45
+ bounded window rather than on sustained frames, and an operator must not read that pass as a
46
+ smoothness measurement. A lane that reaches readiness immediately is labelled the same way.
47
+
48
+ Compile settlement is still required — it is the part that makes a run observe the game rather than
49
+ the loading screen — and a game whose phase never leaves `"collapsing"` fails
50
+ `TN_PLAYTEST_STARTUP_NOT_READY` rather than being observed mid-load. The label is keyed *only* off
51
+ that declaration, never off a timeout or an adapter guess. Every report carries `startup.rule`,
52
+ `"sustained-frames"` or `"compile-settled"`, so a software-lane pass is never read as a smoothness
53
+ measurement.
54
+
55
+ A bridge that stops answering is not automatically a slow launch. A host that has **exited** looks
56
+ identical from the runner's side — both are operation timeouts — so on the device targets the wait
57
+ also asks the driver whether the process is still there, and a dead one fails immediately as
58
+ `TN_PLAYTEST_STARTUP_HOST_EXITED` with the console tail that says why. Only a `false` reading ends
59
+ the wait: a driver that cannot answer leaves it exactly as it was, because inferring a crash from an
60
+ unreadable probe is the implicit fallback everything else here refuses. Without it a crashed runtime
61
+ spent the full `PLAYTEST_STARTUP_READY_TIMEOUT_MS` and was then reported as the game's loading gate
62
+ being too slow — three minutes of silence blamed on the wrong layer, which is how the hosted
63
+ Windows performance collector read on PR #122.
64
+
65
+ Never fix a boot race by lengthening a wait. Padding changes which runs get lucky; the tick counts
66
+ were already identical in the runs that disagreed.
67
+
68
+ ## `--live-clock`: the one wall clock a measurement may ask for
69
+
70
+ **A standing scene is not measurable on counted ticks, and that is not the game's defect.** The
71
+ browser runner sends each fixed-step tick through its own bounded `advance(1)` request, while recording
72
+ path samples in groups of ten ticks. A counted group presents no extra observation frame: a game
73
+ standing still while a scenario watches it reports one boot window and nothing after it, because
74
+ there was no second frame to close a window on.
75
+
76
+ Browser assertions containing `maxFrameMsP95` or `minFps` select this live clock automatically:
77
+ forced simulation batches do not measure normal frame pacing. An explicit `liveClock: false`
78
+ run configuration retains counted ticks; draw-count-only assertions and other targets keep their
79
+ existing default.
80
+
81
+ `--live-clock` (browser and desktop targets) also opts in, and it is the harness half of what the
82
+ native production profile's own `--live-clock` already does there. On the browser the runner puts
83
+ `globalThis.__THREENATIVE_PLAYTEST_CLOCK__ = "wall-clock"` in an `addInitScript` — ahead of every
84
+ page script, so a request that lands after the game's module evaluated cannot happen — and on the
85
+ native desktop host it hands the same request over as `TN_PLAYTEST_CLOCK=wall-clock`, which
86
+ `loadScript` reads before it evaluates the game entry (`runtime.cpp`). Either way the
87
+ producer reads it: the loop is left unfrozen, the host's frame pump moves the simulation at the
88
+ machine's own rate, and `advance` spends the span of wall time its ticks name and reports the ticks
89
+ that pump really ran instead of insisting on the count it asked for. Every report then carries
90
+ `clock: "wall-clock"`, so a rate is never read without the clock that produced it.
91
+
92
+ The request lives in the protocol beside the mode it names, so a game that installs the bridge
93
+ itself (`installThreePlaytestBridge`, a plain Three.js project) honours it too: only an installer
94
+ that names its own mode outranks it, and a producer with no request still reports the clock it
95
+ really runs on. An unrecognised value throws `TN_PLAYTEST_CLOCK_UNSUPPORTED` rather than falling
96
+ back — a misspelling that quietly left the loop frozen published a frame rate for a game that was
97
+ not playing.
98
+
99
+ A browser scenario can ask for it itself with `"clock": "wall-clock"` (target `web` only, any other value
100
+ or target throws at load). The flag then applies to that scenario alone, so a kit's glob run
101
+ (`--scenario "playtests/*.playtest.json"`) measures its `performance` scenario on the wall clock and
102
+ leaves every other scenario on counted ticks. On the counted clock a 300-tick window of a kit
103
+ performance run closed on 44 to 53 presented frames and held 1 to 3 GPU samples; on the wall clock the
104
+ same windows held 17 to 38 (desktop RTX 2080 on a shared GPU, four kits). A performance judgment
105
+ needs the second, and the frame bound fails closed with `TN_PLAYTEST_PERF_FEW_GPU_SAMPLES` without it.
106
+
107
+ It is a measurement switch, not scenario semantics. `holdTicks` and `waitTicks` stay tick counts,
108
+ the flag is refused on the device targets (their hosts take the request from the production
109
+ profile's injected instrumentation, not from this runner). Ordinary deterministic scenarios retain
110
+ counted ticks. A value the host does not recognize is refused there too:
111
+ `TN_PLAYTEST_CLOCK_UNSUPPORTED` on stderr, and the launch fails rather than reporting a wall-clock
112
+ run that never happened.
@@ -0,0 +1,558 @@
1
+ # playtest reference
2
+
3
+ Flag tables, exit codes, per-target detail and the assertion vocabulary for
4
+ [`@threenative/playtest`](../AGENTS.md), moved out of that file verbatim so the
5
+ always-loaded rules stay short. Every paragraph below is the text AGENTS.md used to carry.
6
+
7
+ ## Running a scenario — flags, exit codes and the display
8
+
9
+ Exit `0` passed, `1` assertions failed, `2` never reached assertions, `69` when a command's
10
+ external decoder is absent so nothing was inspected, and `75` when the capture lock queue timed
11
+ out — the last two are explicitly **not** test failures, and `75` prints the holder and queue
12
+ depth. `--build-report <artifact>.build-report.json` adopts the `performanceBudget` a
13
+ `threenative build` published beside that artifact: the run re-hashes the artifact under test and
14
+ exits `2` when it is not the one the report describes (`TN_PLAYTEST_BUILD_REPORT_STALE`), and
15
+ merges the budget per key into the scenario's own `assert.performance`. It needs `--artifact` on
16
+ browser and Android, which is the only thing that says which build the run exercises. `--server-command` needs a workspace that has a `dev` script — an example or a scaffolded
17
+ project; there is no root `pnpm dev`. `--browser-recipe webgpu` supplies the current Chromium WebGPU
18
+ flags including `--enable-features=Vulkan`, without which Chromium silently serves WebGPU from
19
+ SwiftShader and reports healthy-looking limits from a CPU rasteriser; `--browser-arg` is the escape
20
+ hatch, and a run that does not name its adapter is not evidence. `--cpu-prof` starts before page navigation so the profile includes startup plus steps, and profiling perturbs the measurement so it is diagnose-only, never a timing verdict. **On Linux the runner provisions a
21
+ private Xvfb for every pixel-producing run, whether or not a display exists** (stripping Wayland env
22
+ itself), so a scenario never opens windows over whatever the operator is doing — a sweep that
23
+ borrows `:0` makes the machine unusable for as long as it runs. Set `TN_PLAYTEST_HOST_DISPLAY=1` to
24
+ paint on the session's own display instead; opt in when the run needs the session's real GPU adapter
25
+ (heavy TSL post chains have been seen falling back to SwiftShader under Xvfb) or when a human wants
26
+ to watch it. An explicit host request verifies the X connection with `xdpyinfo` (including
27
+ abstract Xwayland sockets) using the session's `DISPLAY` and credentials. Missing `DISPLAY`,
28
+ an unavailable connection, or a missing probe command fails with
29
+ `TN_PLAYTEST_HOST_DISPLAY_UNAVAILABLE`; it never silently substitutes a private Xvfb.
30
+ Do **not** reach for `--headless` to keep windows off a screen: headless Chromium
31
+ cannot capture WebGPU here, so it changes what you measure. `--browser-recipe webgpu` therefore
32
+ launches headed without `--headed`: on a GPU-less Linux host headless Chromium serves WebGPU from
33
+ SwiftShader and cannot create the canvas swap-chain image, so the first present destroys the device
34
+ ("Device was destroyed.") on the owned engine and upstream three alike. The runner takes a capture lock only
35
+ when it detects competing runners — or always with `CAPTURE_LOCK=1`; lock state is printed to stderr
36
+ either way. `sh scripts/xvfb.sh` remains as an optional compatibility wrapper — never `xvfb-run`,
37
+ whose exit status is its own failing cleanup kill rather than the command's.
38
+
39
+ An installed project (no `pnpm-workspace.yaml` above it) runs its own `typecheck` and `lint`
40
+ scripts before any scenario. A failure is exit `1`, `TN_PLAYTEST_CHECK_FAILED`, with the scripts'
41
+ output: those rules are the framework's guardrails, and a game that breaks them is not passing.
42
+ `--skip-check` skips them and prints `TN_PLAYTEST_CHECK_SKIPPED`.
43
+
44
+ ## A frame rate from a private Xvfb is wrong, not missing
45
+
46
+ **A frame rate from that private Xvfb is wrong, not missing**, so no command may print one as
47
+ though it were measured: without vsync the present wait lands inside the update phase (13.3 fps
48
+ there against 57.7 on the real display, one build). `trace` never prints one. `perf` prefers the
49
+ display's own rate whenever a window carries one — core reads the host's `__tnPresentedCount` and
50
+ reports `presents`/`presentedFps` beside the loop's `fps` — and otherwise suppresses the column and
51
+ refuses a `--min-fps` bound when the run's display is private (`--executable`) **or the log says for
52
+ itself that the frames never reached the display**: the host counts loop frames and presents
53
+ separately in `TN_PRESENTS_TICK`, and a loop the presentation cap outran inflates `fps` by exactly
54
+ that ratio — midway's native launch log reported 2631 fps beside its own
55
+ `{"frames":1740,"presents":133,"capHz":60}`, and passed a 55 fps bound. A window that counted zero
56
+ presents carries no rate at all: the column prints `0.00`, the windows are named in words, and a
57
+ bound over windows that all lack a rate fails closed. Both refusals take `--allow-virtual-display`
58
+ when the operator is deliberately reading phase timings alone. A
59
+ `--min-fps` bound that can be satisfied by a number nobody can vouch for is a green with nothing
60
+ behind it — the desktop build above reported 20,000 fps that way.
61
+
62
+ ## A drawn frame every N ticks
63
+
64
+ A step's ticks advance without drawing, and a component that samples a GPU readback lands at most
65
+ one sample per **drawn** frame, so a scenario's sample count is a property of the adapter and not of
66
+ its ticks. `drawEvery` (a positive safe integer, ticks) makes the fixed-step runner draw one frame —
67
+ the `render: true` advance plus one presented frame — every `drawEvery` ticks of each tick-advancing
68
+ step (`holdTicks`, `waitTicks`, the settling tick after a release). Absent, ticks advance undrawn as
69
+ before, and a drawn frame costs real time, so ask for the sample rate the assertions need: `60` on a
70
+ 1,800-tick hold draws 30 frames. It fails closed rather than being ignored: a bridge that advertises
71
+ no `runtime.fixedStep` fails the handshake, `--live-clock` (or `clock: "wall-clock"`) is
72
+ `TN_PLAYTEST_UNSUPPORTED_ON_TARGET`, and the device and desktop lanes name it unsupported too.
73
+
74
+ ## Captured tone
75
+
76
+ `assert.tone[]` bounds `mean`, `p1`, `p50`, `p99` in display luminance bytes and
77
+ `clipFraction`, `blackFraction` in 0..1. Every metric takes inclusive min/max; at least one
78
+ bound is required. `atStep` selects a named step, otherwise the final capture is used.
79
+ Tone requests survive disabled convenience screenshots and fail on absent captures. The browser
80
+ and device paths retain their shared PNG histogram as TN_TONE under observations.tone. The game's
81
+ bridge never supplies these host measurements. The offline command
82
+ `threenative-playtest tone <png...>` prints identical metrics and a frame-average row.
83
+
84
+ ## One scenario, four targets
85
+
86
+ `--target browser|android|desktop|ios` runs the same scenario file against a browser, an Android
87
+ device or emulator, a native desktop executable, and an iOS simulator or device
88
+ (`runner/deviceRunner.ts` holds the flow the three device lanes share; `runner/androidRunner.ts`,
89
+ `runner/desktopRunner.ts` and `runner/iosRunner.ts` only start their lane; `runner/deviceTransport.ts`). Desktop requires `--executable`, and the game bundle reaches the host
90
+ through repeatable `--host-arg` (`--host-arg run --host-arg dist/game.js`) — without it the host
91
+ launches with no game and the run reports `TN_PLAYTEST_BRIDGE_MISSING` at zero frames. The runner
92
+ owns a temporary local
93
+ mailbox and passes its root to the native host through `TN_PLAYTEST_MAILBOX_ROOT`. Keep it that way:
94
+ an assertion that only
95
+ means something on one target is a fork of the harness. `--live-clock` adds
96
+ `TN_PLAYTEST_CLOCK=wall-clock` beside it, and only when the flag is named; the host reads it before
97
+ the game entry evaluates.
98
+
99
+ A device target that cannot be reached fails `TN_PLAYTEST_DEVICE_FAILED`; it never degrades
100
+ to a browser run. The iOS simulator launches only after `simctl listapps` lists the newly
101
+ installed bundle, because `simctl install` returns while the replaced build is still listed; an install
102
+ that stays unlisted for 60 s fails `TN_PLAYTEST_IOS_INSTALL_UNREGISTERED`. Desktop observes HTTP and asset fetch failures through the native host mailbox
103
+ and checks network errors by default. Missing, malformed or overflowing observations fail closed.
104
+ Android and iOS still lack a runner network observer; an explicit network assertion **errors and
105
+ names the working target**, it does not skip.
106
+ The negative-control scenarios in `examples/native-smoke/playtests/` (`-misspelled`,
107
+ `-wrong-value`) prove the device path still fails closed; run them when you change transport
108
+ or observation code.
109
+
110
+ ## `perf` — read the frame meters without opening a log
111
+
112
+ `threenative-playtest perf` parses `TN_FRAME_BUDGET` and `TN_HOST_GAP` out of one source —
113
+ `--file <log>`, `--executable <bin>` with repeatable `--host-arg`, or `--logcat <serial>` — and
114
+ reports fps, frame/render/hostGap p50/p95 per window plus the host-gap segments. It exists
115
+ because every number in the Android-fps hunt was read from these markers by hand; the parser
116
+ (`runner/perf.ts`) is that hand-read, encoded.
117
+
118
+ Protocol rules are built in, not optional: **window 1 is discarded as startup** (it always
119
+ lies), `--require-windows` (default 2) counts *steady* windows and a run with fewer exits **2**
120
+ — not enough evidence, never an empty pass — and a marker line whose JSON cannot be parsed
121
+ **throws** (`TN_PERF_MARKER_MALFORMED`) rather than silently vanishing. Optional bounds
122
+ `--max-frame-p95 <ms>` / `--min-fps <fps>` fail with exit **1** on any steady-window violation;
123
+ without bounds the command reports and exits 0. The host's `Present mode:` line is captured
124
+ when the host logs one. `--text` renders the human-readable table; default output is JSON.
125
+
126
+ Desktop spawn under a headless session rides the same Xvfb rule as any pixel run:
127
+ `sh scripts/xvfb.sh threenative-playtest perf --executable … --host-arg run --host-arg game.js …`,
128
+ and that Xvfb is exactly the display whose frame rate cannot be trusted — such a run prints no
129
+ `fps` column and refuses `--min-fps` (exit 1, `TN_PERF_VIRTUAL_DISPLAY`) unless the operator passes
130
+ `--allow-virtual-display`. The phase and host-gap rows, which are what the native lane's baselines
131
+ quote, are unaffected.
132
+ The command never launches a browser — the browser lane already bounds performance through
133
+ `assert.performance` — and it never tunes anything; it is a meter reader.
134
+
135
+ ## `audio` — look at the sound, because nobody listens in CI
136
+
137
+ `threenative-playtest audio --expect <manifest.json>` decodes every clip a game declares and
138
+ reports band energy, peak, DC, silence and loop-seam continuity, writing one spectrogram PNG per
139
+ clip. No browser, no display, no capture lock: inspecting audio reads files, and taking the capture
140
+ queue for it would block the machine's pixel work for nothing.
141
+
142
+ It exists because **every check that does not involve listening passes on audio that is wrong**.
143
+ The file exists, it is served 200, it decodes, no page error, it is inside the byte budget — and the
144
+ clip is a hum where a chime should be. That shipped here: a discovery cue with 80% of its energy in
145
+ 100-500 Hz and 1% above 2 kHz, on the one sound a player waits to hear. So did fifteen footsteps
146
+ with up to 45% of their energy below 100 Hz, which is a thud, not a boot on stone. Both are
147
+ unmistakable in a band profile and a spectrogram, and invisible in a size, a duration or a green
148
+ `loaded` marker.
149
+
150
+ **The game declares the expectations, because the inspector cannot know them.** Nothing here knows
151
+ that a forest bed should be broadband and a discovery chime should be bright. The manifest is the
152
+ game saying so:
153
+
154
+ ```json
155
+ { "version": 1, "clips": [
156
+ { "path": "public/audio/forest-bed.ogg", "loop": true,
157
+ "bands": { "sub": { "max": 3 }, "high": { "min": 20 }, "air": { "min": 20 } } },
158
+ { "path": "public/audio/landmark-found.ogg", "loop": false,
159
+ "bands": { "low": { "max": 25 }, "high": { "min": 25 } } }
160
+ ] }
161
+ ```
162
+
163
+ Bands are `sub` (<100 Hz), `low` (100-500), `mid` (500-2k), `high` (2k-8k) and `air` (>8k),
164
+ contiguous to Nyquist, reported as percentages of summed magnitude over Hann-windowed frames
165
+ covering the whole signal. They are comparable to each other and to what a game declares, not to
166
+ another tool's numbers. The frame hop shrinks on a short clip so its spectrogram is wide enough to
167
+ read a transient off — a half-second footstep holds twenty non-overlapping frames, and a
168
+ twenty-column picture defeats the only reason the picture exists.
169
+
170
+ Fails closed, on this package's own rule: an unknown key, a band nobody measures, a bound that can
171
+ never hold, a `seamMaxRatio` on a clip whose `loop` is false, a duplicate path, or an empty clip
172
+ list all **throw** rather than skip. `loop` is required rather than defaulted, because it is the one
173
+ fact that decides whether the seam is checked. `--dir <dir>` additionally fails when any audio file
174
+ under it is undeclared — otherwise the gate is only as good as the manifest and a clip added later
175
+ is a clip nothing checks.
176
+
177
+ **Two measurement rules, both learned by getting them wrong.**
178
+
179
+ *Decode at the file's own rate.* A seam measured on a resampled decode measures the resampler: its
180
+ FIR window runs off the end of the data at the first and last output sample and is zero-padded, so
181
+ the edge samples are the only wrong ones in the file — exactly where a seam test looks. On one real
182
+ set that inflated the reported step three to sevenfold and reordered which clip looked worst. The
183
+ command never passes `-ar` to ffmpeg.
184
+
185
+ *Judge the wrap against the steps beside it.* A click is a step that is anomalous **where it
186
+ happens**. A sparse clip is mostly quiet, so a whole-clip percentile flatters its seam; a dense one
187
+ is mostly loud, so the same percentile condemns a join nobody could hear. The reference is the
188
+ 99th-percentile sample step within 50 ms either side, and the default ceiling is 1.5x rather than
189
+ 1.0x — a flawless wrap that lands on the signal's steepest point *is* the largest step in its
190
+ neighbourhood and measures exactly 1.0.
191
+
192
+ Exit `0` when every check passed, `1` when one failed, `2` when it could not run (a malformed or
193
+ unreadable manifest), and `69` when ffmpeg is absent. That last code is the point: **"I could not
194
+ check" and "I checked and it is fine" must never be the same answer**, so CI can treat 69 as a skip
195
+ and still treat 1 as a defect.
196
+
197
+ `--text` prints `✓`/`!`/`✗` lines with a `fix:` on anything that is not ok; default output is JSON.
198
+ The numbers are the gate and the picture is what a person or an agent looks at when the gate fires,
199
+ so every spectrogram written is named in both. Verdicts, parsing and analysis live in
200
+ `runner/audio.ts` and are unit-tested against synthesised signals in `__tests__/audio.spec.ts`;
201
+ `runner/audioRun.ts` only drives ffmpeg.
202
+
203
+ ## Startup time is an observation
204
+
205
+ The runtime stamps its startup milestones on its own clock — `loadStartedMs`, `enteredMs`,
206
+ `compileSettledMs`, `readyMs`, in milliseconds since navigation — and publishes them as
207
+ `observations.startup.timeline`. Scenarios bound them with `assert.startup`: `maxEnteredMs`,
208
+ `maxCompileSettledMs`, `maxReadyMs`, `maxOffscreenBytes`. A milestone the run never reached fails closed
209
+ (`TN_PLAYTEST_STARTUP_UNOBSERVABLE`); one past its ceiling fails
210
+ `TN_PLAYTEST_STARTUP_TOO_SLOW` with the measured value. Before this, startup was a console
211
+ anecdote read off `TN_STARTUP_WARMUP` after the fact.
212
+
213
+ ### Bytes the reveal waited for that the spawn camera does not show
214
+
215
+ At the reveal the runtime measures which models the game awaited through `ctx.assets` and how many of
216
+ their manifest bytes have no object visible to the spawn camera (in the frustum, not hidden), and
217
+ publishes it as `observations.startup.offscreenBytes`: `awaitedBytes`, `visibleBytes`, `offscreenBytes`,
218
+ `unattributedBytes` (textures and audio, which no scene object ties to a view), `unsizedFiles`, the
219
+ five largest off-screen files with a reason (`outside-view`, `hidden`, `not-placed`), `warn` and the fix.
220
+ It also logs `TN_STARTUP_OFFSCREEN_BYTES:{...}`. No fixed MB threshold: it warns when off-screen bytes
221
+ exceed visible bytes, and informs on any other off-screen byte. A warning run carries the
222
+ `TN_PLAYTEST_STARTUP_OFFSCREEN_BYTES` warning diagnostic; the fix is to stream those files with
223
+ `WorldCells`, or `ctx.assets.prefetch` them after the reveal, and keep awaiting everything the spawn camera
224
+ sees. Never defer what the camera sees to lower `readyMs`. `assert.startup.maxOffscreenBytes` turns it
225
+ into a gate (`0` means everything awaited is in view); it fails closed with
226
+ `TN_PLAYTEST_STARTUP_UNOBSERVABLE` when the runtime reported nothing or no awaited file has a manifest
227
+ size. `doctor --url` prints awaited and off-screen MB with the estimated download time at 20 Mbit/s.
228
+ Proof fixture: `examples/startup-offscreen/`.
229
+
230
+ `steadyCover: true` checks what the player saw instead. The browser runner records every
231
+ compositor frame through Chromium's screencast (128 x 72) from before navigation until 30
232
+ frames after `readyMs`, and compares each frame before readiness with the last one before
233
+ readiness, the loading cover. A frame with more than a quarter of its pixels off by more than 48
234
+ per channel fails `TN_PLAYTEST_STARTUP_COVER_BROKEN` with its time and mean colour, so a black
235
+ frame, a blank page or a page background in a different colour fails. After readiness, the first
236
+ frame that differs from the cover is the world frame. A frame before it with more than 0.5% of
237
+ its pixels off the cover and on the world frame's colour shows page UI (a HUD) over the cover and
238
+ fails `TN_PLAYTEST_STARTUP_UI_OVER_COVER`. No recorded frame, or no world frame after readiness,
239
+ fails `TN_PLAYTEST_STARTUP_COVER_UNOBSERVED`; that includes every target except the browser.
240
+
241
+ ## Device thermal, power and battery
242
+
243
+ Every `--target android` run measures the phone around itself and reports it as
244
+ `observations.deviceMetrics` — battery temperature and level, Android thermal status, charging
245
+ state, current draw, and Pixel's per-rail ODPM power breakdown. It is sampled before `prepare()`
246
+ (the only moment a pre-launch baseline is still readable, since `prepare` clears logcat), every
247
+ five seconds during the run, and once after the last bridge sample.
248
+
249
+ The point is **comparability**. On 2026-08-24 two cold-launch runs read 44 s to first frame
250
+ against a 14.7 s baseline and the difference was blamed on a code change; the device had reached
251
+ 43.2 °C at thermal status 2 while the baseline ran at 38.2 °C at status 0. A run is flagged
252
+ `thermallyConfounded` with named reasons — `hot-start` (≥ 40 °C), `throttled-start`,
253
+ `thermal-status-rose`, `charging`, `incomplete` — and a flagged run's numbers are still reported
254
+ in full. The verdict withdraws the claim of comparability, never the measurement.
255
+
256
+ Scenarios assert on it with `deviceMetrics`: `notThermallyConfounded`, `maxTemperatureRiseC`,
257
+ `maxThermalStatus`. On browser, desktop or iOS the assertion fails
258
+ `TN_PLAYTEST_UNSUPPORTED_ON_TARGET` and names android — it never skips. A reading the device does
259
+ not expose (per-rail power off Pixel hardware, `current_now` where the sysfs node is absent)
260
+ reports `{ available: false, reason }`; **nothing here ever reports an unmeasured zero**.
261
+
262
+ Ask *before* spending a run: `doctor --device <serial>` reports the phone's battery temperature,
263
+ thermal status, charge level and charging state next to the machine checks. It warns — a hot
264
+ phone is a run that will not be comparable, not a broken machine — and only fails on a device
265
+ that is unreachable or a probe that cannot be parsed.
266
+
267
+ ```sh
268
+ node packages/playtest/dist/runner/cli.js doctor --device <serial> --text
269
+ ```
270
+
271
+ Parsers and verdict live in `runner/deviceMetrics.ts` and are unit-tested against captured device
272
+ output in `__tests__/fixtures/device-metrics/`. Add real captures there rather than inventing a
273
+ `dumpsys` format. Both the observation lane and `doctor --device` only report; the gate that
274
+ *refuses* a hot or charging device before a benchmark is
275
+ `packages/runtime-native/scripts/device-preflight.mjs`, and they share the same battery floor so
276
+ an operator is never told two different stories.
277
+
278
+ ## The room, and the feet
279
+
280
+ Two things the harness measured and nothing could read.
281
+
282
+ `doctor --url` used to end its report with *not observed: lights, materials and textures* and
283
+ *not observed: camera framing*. An agent looking at a black or washed-out frame therefore had
284
+ nothing between "the bridge answered" and a screenshot, which is the one instrument that cannot
285
+ say **why**. The bridge now reports the room as `observations.scene` — lights with their colours
286
+ and intensities, materials counted per distinct material by constructor name, fog with its own
287
+ near/far or density, the background, the camera's position, forward, fov and clip planes, and the
288
+ scene's world extent. Counts and names only: it decides nothing about how anything looks, and a
289
+ value the scene does not carry is absent rather than zero. The walk is capped
290
+ (`SCENE_WALK_OBJECT_CAP`, `SCENE_LIGHT_CAP`) and a scene past either reports `truncated: true`,
291
+ so a floor is never read as a total.
292
+
293
+ `doctor --url` reads it back as three lines — `lighting`, `materials`, `camera` — and names the
294
+ ways a frame dies while every other number stays healthy: **lit materials with no visible light**,
295
+ a **fog far plane in front of the scene it is fogging**, and a **camera far plane that clips it**.
296
+ The second is round 9's lost visual column, where a radius-90 sky dome sat behind `Fog(bottom, 18,
297
+ 80)` and rendered as one flat wash; no gate could see it.
298
+
299
+ `AnimationPlayer.stride` has measured the *feet meet the floor* convention since it shipped — what
300
+ the clip carries against what the body covered — and it never crossed the bridge either, so a game
301
+ that set `strideSync: false` had turned the measurement off as far as any proof was concerned.
302
+ It now rides in `gameplay.animation.<entity>.stride`, and `assert.animation[]` bounds it:
303
+
304
+ - `maxFootSlide` — ceiling on `|feet − ground| / ground`. The feet move at the rate the clip is
305
+ *actually playing*, which is the measured `rate` only when `synced`; an overridden clip keeps
306
+ its authored rate. Reading `rate` unconditionally scored an overridden run at zero slide —
307
+ the exact case the bound exists to catch, found by the locomotion scenario, not by a unit test.
308
+ - `strideSynced` — require the convention applied (`true`) or deliberately overridden (`false`).
309
+
310
+ Both fail closed, and each failure names which kind: `TN_PLAYTEST_STRIDE_UNOBSERVED` when the
311
+ producer reported no stride, reported half of one, or the body covered no ground to compare
312
+ against; `TN_PLAYTEST_STRIDE_NOT_SYNCED`; `TN_PLAYTEST_FOOT_SLIDE` with both speeds and the
313
+ ceiling. A game that does not measure stride has not measured zero slide.
314
+
315
+ A procedural rig plays no clip, so it reports no stride. `assert.footSlip[]` measures the screen
316
+ instead: `{ atStep, feet: ["footL", "footR"], maxSlip: 0.35, entity? }` advances the labelled step
317
+ one tick at a time and samples the world position of the subject and of each named sole node
318
+ after every tick. A foot is planted while it is in the lowest quarter of its height below the
319
+ body, and its slip is planted-foot travel over body travel on those ticks: 0 is planted, about 1
320
+ skates with the body. It fails `TN_PLAYTEST_FOOT_SLIP`. `maxSlideSpeed` (m/s) bounds the same
321
+ planted-foot travel in metres per second instead of as a ratio, so a body that barely moves cannot
322
+ hide a slide; it assumes `stepSeconds` (default 1/60) per tick, because the bridge does not report
323
+ the game's step. Set `maxSlip`, `maxSlideSpeed` or both; one is required. A missing node, a step that moved the
324
+ subject under 0.5 m, fewer than 4 planted tick pairs, or a target other than the browser fails
325
+ `TN_PLAYTEST_FOOT_SLIP_UNOBSERVED`. A moving character whose clip is `inPlace` with a zero
326
+ `clipGroundSpeed` has no foot plant for stride sync to match: `footSlip`, `strideSynced` and
327
+ `maxFootSlide` all fail closed with `no foot plant found: stride sync is off`
328
+ (`TN_PLAYTEST_STRIDE_NO_FOOT_PLANT`).
329
+
330
+ `assert.sightLine: { maxBlockedRatio, entity? }` watches the camera instead: every sample casts a ray
331
+ from the camera's world position to the subject's world bounds centre and reports whether solid
332
+ geometry is in the way. A rope or a rail (thin in two axes, crossed in under 15 cm) does not count. A cutout (`alphaTest`), a transparent surface that writes no depth and a mostly
333
+ transparent surface are not solid. `maxBlockedRatio` (0..1) is the share of samples that may be blocked, and
334
+ `entity` defaults to the scenario subject. A blocked sample names the five nearest blockers; a run
335
+ over the share fails `TN_PLAYTEST_SIGHT_LINE_BLOCKED`. The check runs on the browser target only and
336
+ fails `TN_PLAYTEST_SIGHT_LINE_UNOBSERVED` when it sampled nothing.
337
+
338
+ `assert.engineCost: { maxPerFrame?, maxInFrame?, minWindows?, skipWindows?, still?, moving?, source }` bounds the
339
+ engine's own work counters. The runner sets `__THREENATIVE_ENGINE_COST__`, and core then puts each
340
+ frame's counts into every `TN_FRAME_BUDGET` window as `counters.engine` (a per-frame summary per name):
341
+ the web back end's `childrenReads`, `walkVisits` and `hierarchyMoves`, the engine's `matrixEvaluations`,
342
+ `share`, `shareHits`, `shareMints`, `contentClassOf`, `contentVersionKeys`, `classify`, `buffers` and
343
+ `textures`, and every name a module adds to `globalThis.__tnEngineCost` (core's `cullRigRebuilds` and
344
+ `cullRigWalks`, physics' `physicsTransformReads` and `physicsForceResets`). `counters.bridgeCrossings`
345
+ joins as `bridgeCrossings`. A name that multiplies with content — one per asset URL, one per bridged
346
+ property (`bridge:…`) — is deliberately not a per-frame series, so it cannot be bounded here: the
347
+ `TN_DEBUG_REPORT` ranks the largest ten of the run's totals under `contentScaled` instead. `maxPerFrame` bounds a window's mean and `maxInFrame` its largest frame.
348
+ `skipWindows` (default 0) leaves the first windows, the boot, unbounded. Every later window must hold
349
+ every top-level bound; `still: { windows, maxPerFrame }` bounds only the first `windows` of them, which
350
+ the scenario keeps still, and `moving: { maxPerFrame?, maxInFrame? }` only the
351
+ windows after them. Fewer windows than `minWindows` (default 1), an unreadable window, or a bounded
352
+ counter a window omits fails `TN_PLAYTEST_ENGINE_COST_UNOBSERVED` or `TN_PLAYTEST_ENGINE_COST_OVER_BOUND`;
353
+ an over-bound message names the counter, the window and the top caller of the three-native
354
+ `TN_BRIDGE_CENSUS` printed before it. `source` states where each bound came from.
355
+
356
+ The same name-based bounds accept debug-only counters after a pre-boot `TN_DEBUG=1`, `?tnDebug=1`
357
+ or `__THREENATIVE_DEBUG__ = true` request. An absent or malformed summary, including a zero-sample
358
+ summary, fails closed. `TN_DEBUG_REPORT` is informational; bounds read the numeric
359
+ `TN_FRAME_BUDGET.counters.engine` source. Counts/bytes and getter-equivalent estimates retain
360
+ their units and must not be described as measured CPU time.
361
+
362
+ `assert.hudAudit: { noDebugText?, minContrast? }` reads the text the page draws after the last step.
363
+ `noDebugText` (only `true`) fails when an item reads like developer copy — debug, TODO, FIXME,
364
+ lorem ipsum, placeholder, probe, raycast, hitbox, wall ray, an unresolved `undefined`, `null` or
365
+ `NaN`, or a coerced `[object Object]` — as `TN_PLAYTEST_HUD_DEBUG_TEXT`. `minContrast` (1..21) is a
366
+ WCAG 2.x floor on the ratio between the text colour and the colour composited behind it; text over
367
+ the canvas (background alpha under 0.5) is counted as `unjudged`, not guessed at, and a judged item
368
+ below the floor fails `TN_PLAYTEST_HUD_CONTRAST`. At least one key is required, the check runs on
369
+ the browser target only, and a run that reported no text fails `TN_PLAYTEST_HUD_AUDIT_UNOBSERVED`.
370
+
371
+ **The frame budget is 60 fps on every tier.** A `performance` assertion without `maxFrameMsP95`
372
+ holds the run to 16.7 ms at nearest-rank p95, on a discrete, integrated or mobile GPU alike; the
373
+ `frameBudget` row detail says which budget applied. A software adapter is unmeasurable and fails
374
+ `TN_PLAYTEST_PERFORMANCE_UNMEASURABLE`. A scenario may set a looser `maxFrameMsP95` only with
375
+ `maxFrameMsReason`, which the report prints; without it the scenario throws at load. The runner
376
+ reads no display period from the host today, so 16.7 ms is the whole rule.
377
+
378
+ What 16.7 ms judges depends on the display. The runner paints on a private Xvfb unless
379
+ `TN_PLAYTEST_HOST_DISPLAY=1` names the session's display, and a virtual display paces frames on its
380
+ own timer, so its rAF interval is cadence, not game cost. On a **virtual display** the run is judged
381
+ on the engine's own cost: the p95 of update plus render per frame, or the GPU p95 of the latest
382
+ `TN_FRAME_BUDGET` window that measured it (the first window holds the startup shader compile) when
383
+ that is larger. The interval p95 is still in the row details, marked `gated: false`
384
+ with the reason. On a **real display** the interval p95 and the cost p95 must both hold 16.7 ms,
385
+ because host gap only the interval sees is part of what a player feels. A run with no CPU split on
386
+ its samples, or no GPU reading in any `TN_FRAME_BUDGET` window (an adapter without timestamp
387
+ queries), fails closed: an unmeasured cost is not a zero. So does a judged GPU window that holds
388
+ fewer than 3 GPU samples (`TN_PLAYTEST_PERF_FEW_GPU_SAMPLES`; the row prints `cost.gpuSamples`): the
389
+ counted-tick clock advances ticks faster than frames draw, so a 300-tick window closes on about 50
390
+ presented frames. A performance scenario sets `"clock": "wall-clock"` (target `web`; see
391
+ [determinism.md](determinism.md)). Below 20 samples the p95 is the maximum. 3 is chosen, not measured:
392
+ it is the least that stops one query deciding the verdict. There is no tolerance multiplier.
393
+
394
+ **An engine performance warning fails the run.** Any `TN_SCENE_WARNING`, `TN_BRIDGE_WARNING` or
395
+ `TN_HOT_CALL` console line, and any
396
+ `TN_RENDER_PROJECTION` line with `projecting: false`, fails the `diagnostics` row with
397
+ `TN_PLAYTEST_PERF_WARNING`, whatever the console-error policy. The report prints the marker text and,
398
+ for a projection decline, the `cause` code (`uniqueGeometry` or `uniqueMaterial`) with its hint.
399
+ Two lines are not defects: `reasonCode: "disabled"`, the game's `renderer.projection: false`, and
400
+ `belowMeshFloor`, the engine's verdict that too few meshes are batchable for a mirror to pay.
401
+
402
+ A scenario bounds the same numbers with `assert.scene`, so the check outlives whoever ran
403
+ `doctor` once:
404
+
405
+ - `minVisibleLights` — floor on lights the renderer will actually see. An invisible light is no
406
+ light.
407
+ - `litMaterialsAreLit` — fail when lit materials are mounted and nothing lights them. A scene of
408
+ `MeshBasicMaterial` needs no light and is not failed for having none.
409
+ - `fogClearsScene` — fail when a linear fog goes opaque in front of the scene's furthest corner.
410
+ - `cameraClearsScene` — fail when the camera's far plane cuts the world it is pointed at.
411
+
412
+ `assert.scene` bounds the room. It cannot say **where one object is**, and that is the other half
413
+ of every screenshot an agent takes: is the crate in the vault or under the floor, is the camera
414
+ pointed at it, did the plate's normal map ever load, is the character's mesh visible once every
415
+ ancestor's `visible` flag is counted. Those kill a frame while every count above them stays
416
+ healthy, and a screenshot shows the damage without naming the cause.
417
+
418
+ `sceneNodes` reports the graph node by node, for the nodes a selector picks out — `name`,
419
+ `nameContains`, `pathContains`, `type` — and bounds them:
420
+
421
+ ```json
422
+ { "assert": { "sceneNodes": [
423
+ { "select": { "nameContains": "crate" }, "minCount": 30, "visible": true, "texturesLoaded": true },
424
+ { "select": { "name": "seal" }, "inFrustum": true },
425
+ { "select": { "nameContains": "debug" }, "maxCount": 0 }
426
+ ] } }
427
+ ```
428
+
429
+ - `visible` — the node's own flag **and every ancestor's**, which is what the renderer acts on. A
430
+ visible mesh under a hidden group draws nothing and reports `visible: true` on itself.
431
+ - `inFrustum` — the node's world bounds against the active camera's frustum. A node with no
432
+ bounds is never tested and reports no membership, which fails rather than passing unmeasured.
433
+ - `texturesLoaded` — every bound map slot carries pixels. A slot bound to a texture whose image
434
+ never arrived samples black while the material, the light count and the network all read fine.
435
+ - `animated` — clips are mounted on the object. This is not what the game's mixer is *playing*;
436
+ that is `gameplay.animation` and `assert.animation`, and the failure message says so.
437
+ - `minCount` (default 1) / `maxCount` — `maxCount: 0` is how a scenario asserts a node is absent.
438
+ - `minTriangles` — summed across the matched nodes, and reported as a floor when the selector's
439
+ limit cut the list.
440
+
441
+ Each observation is walked only when a scenario asks for it, because reading geometry, materials
442
+ and world bounds per object is real work on a large scene. The walk is capped
443
+ (`SCENE_NODE_WALK_CAP`, per-selector `limit`), `matched` always counts every match, and a cut list
444
+ reports `truncated: true` — a floor is never read as a total. A selector that filters nothing, an
445
+ assertion that selects nodes and bounds none of them, and a `minCount` above its `maxCount` all
446
+ throw at load. A run with no node observation fails once as `sceneNodes.observed`
447
+ (`TN_PLAYTEST_SCENE_NODES_UNOBSERVED`). Advertised as the `scene.nodes` capability.
448
+
449
+ ## "Because", not "and then"
450
+
451
+ A run could always say *a contact happened* and *the state reads `won`*. Nothing related the two.
452
+ `assert.states[].atSteps` orders them at **step** boundaries, which cannot separate a win arriving
453
+ with the contact from one arriving 199 ticks later inside the same step — and that is exactly the
454
+ shape of a terminal state driven by a timer or a distance check that merely lands near a contact.
455
+
456
+ Measured in the field: a sandbox physics puzzle reported `won` on frame one with the player
457
+ untouched eight metres away, because its goal volume overlapped the floor slab. Its own HUD agreed
458
+ the game was won. Every assertion in the harness was green, because each was individually true.
459
+
460
+ Both sides are now tick-stamped by the producer, and `assert.causedBy` relates them:
461
+
462
+ ```json
463
+ { "assert": { "causedBy": [
464
+ { "cause": { "contact": { "entity": "warden", "with": "seal", "kind": "trigger" } },
465
+ "effect": { "path": "state.status", "becomes": "won" },
466
+ "neverBefore": true, "withinTicks": 4 }
467
+ ] } }
468
+ ```
469
+
470
+ - `neverBefore` fails when the effect is ever observed before the first matching cause. That is the
471
+ frame-one fake win, at tick granularity.
472
+ - `withinTicks` bounds `effectTick - causeTick`. A win long after the contact was not caused by it.
473
+ - `cause` takes a `contact` **or** a `transition`, never both — two causes in one row would
474
+ silently make the earlier one the cause. So "the door opened because the plate was pressed" is
475
+ the same row shape.
476
+ - A row setting neither `neverBefore` nor `withinTicks` throws at load: ordering alone is what
477
+ `atSteps` already does, and asserting only that both events happened is two assertions wearing
478
+ one name.
479
+
480
+ Core's `playtest()` plugin drains both logs **per tick** rather than per sample and advertises
481
+ `runtime.transitions`. The transition watcher diffs each registered entity's `state` and the
482
+ top-level primitive fields of the published game state, recording `{ path, from, to, tick }` —
483
+ `states.<entity>` or `state.<field>`. A path's first observed value is its starting point, not a
484
+ transition; recording it as one would fail every `neverBefore` against the game's own initial
485
+ state. The log is bounded by `PLAYTEST_TRANSITION_LOG_LIMIT`.
486
+
487
+ Every failure mode is named and closed. A run with no transition log fails once as
488
+ `causedBy.observed` (`TN_PLAYTEST_TRANSITIONS_UNOBSERVED`) — a loop that never ticked has observed
489
+ nothing, not nothing-changed. A matching contact carrying **no tick** fails
490
+ `TN_PLAYTEST_CAUSE_UNSTAMPED` rather than being read as a cause at tick zero, and the message says
491
+ the producer drains only at sample time. A cause the run never observed is
492
+ `TN_PLAYTEST_CAUSE_NOT_OBSERVED`; an effect that never transitioned is
493
+ `TN_PLAYTEST_EFFECT_NOT_OBSERVED`; the frame-one case is `TN_PLAYTEST_EFFECT_PRECEDES_CAUSE` with
494
+ both ticks; a late effect is `TN_PLAYTEST_CAUSE_TOO_DISTANT`. **The family never falls back to step
495
+ granularity** — that is a different measurement, and answering a tick question with it would be the
496
+ confident wrong number this package exists to refuse.
497
+
498
+ One related fix in core, from the same build: an area's contact used to be dropped unless the game
499
+ passed an explicit `entity` option, so a trigger that demonstrably fired reported no contact at all
500
+ and a `contacts` assertion went green over a run whose own state proved the overlap. The far side
501
+ now falls back to the scene-registry id the area is registered under.
502
+
503
+ A run with no scene observation fails once as `scene.observed`
504
+ (`TN_PLAYTEST_SCENE_UNOBSERVED`) rather than failing each bound against nothing, and an
505
+ `assert.scene` that sets no bound throws at load. An unmeasurable comparison — no world extent,
506
+ no far plane — fails; it never counts as cleared.
507
+
508
+ Advertised as the `scene.observe` capability. A capability the runner's registry does not define
509
+ is rejected (`TN_PLAYTEST_BRIDGE_CAPABILITY_UNKNOWN`), so a new observation channel is registered
510
+ in `src/capabilities.ts` in the same change that starts advertising it.
511
+
512
+ ## Scenario-controlled spawn & aim
513
+
514
+ The scenario `setup` block carries a placement vocabulary so capturing a vantage frame is
515
+ one scenario, not a patch-run-revert ceremony:
516
+
517
+ - `setup.spawn { x, z }` (+ optional `y`) overrides the SUBJECT player start's position.
518
+ An absent `y` preserves the game's own height (eye or ground line); it is never silently
519
+ defaulted to zero. Requires `subject`.
520
+ - `setup.aim { yaw, pitch }` overrides the SUBJECT player start's aim; both angles are
521
+ radians, Three.js convention (forward is -Z at yaw 0, pitch positive up). Requires
522
+ `subject`.
523
+ - `setup.place[]` entries `{ entity, at: {x,y,z}, facing?: {yaw} | lookAt?: {x,y,z}, frozen?: boolean }`
524
+ put named entities at explicit transforms. `frozen` sets `PLAYTEST_FROZEN_MARKER`
525
+ (`__threenativeFrozen`) on the entity's userData — data the game reads to suppress
526
+ physics motion, never a runner-side teleport loop.
527
+
528
+ Presence semantics are explicit and fail closed: an unknown entity id, an entity missing
529
+ from the registry at apply time, or a target coincident with the subject is a NAMED error
530
+ (`TN_PLAYTEST_SETUP_UNAPPLIED`), never a silent skip. One entity may be placed by only one
531
+ of `setup.entities` / `setup.place`.
532
+
533
+ A `click` step's `at` is viewport pixels `{ x, y }`, a registered entity `{ entity }`, or (browser
534
+ only) a DOM element `{ element: { id } | { selector } }` clicked at the centre of its live box. Prefer
535
+ the element form for interface controls: pixel positions move with the fonts a machine has
536
+ installed, which is how a rain scenario passed locally and missed its switch on CI.
537
+ Steps can also carry `{ kind: "aimAt", target: { x, z } | { entity }, pitch?, waitTicks?, screenshot?, label? }`.
538
+ The runner samples the subject's current position, computes yaw/pitch toward the target,
539
+ and applies them through the setup channel as quaternion data — no CDP mouse events and no
540
+ OS-focus dependency. An `aimAt` step cannot also deliver input (`press`, pointers) or
541
+ ignored holds (`holdTicks`/`holdFrames`); follow it with a `waitTicks` step to hold the pose.
542
+
543
+ `{ kind: "explore", seed, ticks, move: [...keys], actions?: [...keys], pointer?: true, label? }`
544
+ plays the way a player does, not the way the author thought to: at load it expands into seeded
545
+ `input` steps of 10-59 ticks. Each holds a heading `move` key that usually carries on to the next
546
+ step, sometimes a second `move` key, and half the time one or two `actions` keys pressed together;
547
+ `pointer: true` also moves the mouse to a seeded spot each step. The same seed is the same run, it
548
+ covers `ticks` exactly, and `label` lands on its last step. Because it is ordinary input it runs on
549
+ every target an `input` step runs on. List one key for every bound action: an action left out is a
550
+ control no exploration reaches. Pair it with `diagnostics` (a page error or a throw in the frame
551
+ loop fails `noConsoleErrors`) and a bound on the subject's final state.
552
+
553
+ Every requested override rides into the run report as `setup.requested` next to what
554
+ applied (`setup.applied`). A run whose placement cannot apply fails with the reason named —
555
+ an overridden spawn must be visible in diagnostics, never green-with-silence. The game keeps
556
+ its own spawn constants; scenarios override them for determinism, through this one channel.
557
+ The template-teaching copy of this vocabulary ships via the create-threenative shared
558
+ fragment when games adopt it; until then this section is the harness contract.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/playtest",
3
- "version": "0.3.13",
3
+ "version": "0.3.15",
4
4
  "license": "MIT",
5
5
  "description": "Scenario-driven playtest harness for Three.js games. Runs on plain Three.js with zero ThreeNative dependencies.",
6
6
  "keywords": [
@@ -24,6 +24,7 @@
24
24
  "type": "module",
25
25
  "files": [
26
26
  "dist",
27
+ "docs",
27
28
  "README.md"
28
29
  ],
29
30
  "main": "./dist/index.js",